Introduction to Bash Programming

Variables

Variables can be copied directly and assigned values multiple times. There must be no spaces on either side of =. To use a variable, prefix it with $; when embedding it in a longer string, use ${Val}. The shell has no concept of data types: everything is a string by default. Variables can appear anywhere in a command. When scanning a command, the shell first substitutes variables, then filenames, and finally processes command arguments. Use (()) for arithmetic.

your_name="haha"
echo $your_name # haha 

Passing Arguments

To pass arguments to a script, append them to the command that runs it. Within the script, access them with $1, $2, and so on (for numbers greater than 10, use $(n)). Use $# to get the number of arguments passed.

Conditional Statements

Syntax

if command
then
	command
	command
	...
elif command2
then
    command
    command
    ...
else
	command
	command
	...
fi
# 其中判断的条件可以用test expression 或者 [ expression ]
# 逻辑操作符 与:-a; 或 -o ; 非:!

Examples

A program that checks whether a user is logged in

Display different greetings based on the current time

An example of case: converting numbers to English words

Loops

# 格式1
for var in word1 word2 ... wordn
do
	command
	command
	...
done

# 格式2
while command1
do
	command
	command
	...
done
# 格式3
until command1
do
	command
	command
	...
done
## break , continue的语义同一般编程语言一样

The difference between how $@ and $# are interpreted in for loops

Standard Input, Output, and I/O Redirection

Each Linux/Unix process opens three files when it runs: standard output (stdin), standard output (stdout), and standard error (stderr). Their file descriptors are 0, 1, and 2. By default, input is read from the keyboard, and output and errors are sent to the display. To redirect input/output elsewhere, use redirection commands. The output redirection command is <, and the output redirection command is >.

# 输入重定向命令
command < input_file
# 输出重定向命令
command > output_file
# 输出附加定向命令
command >> outpur_file
# 标准错误重定向命令
command 2> error_file
# read命令 从标准输入读取
read val val2 ...
# 输出到标准输出
echo val1 val2 ...

Pipes

The | symbol passes the output of the preceding file as the input to the following file.

Functions

Syntax

function function_name {
command...
}

function_name () { 
command...
}

# 一个例子
#!/bin/bash

JUST_A_SECOND=1

funky()
{
    echo "This is a funky function." 
    echo "Now exting funcky function."
}

fun ()
{
    i=0
    REPEATS=30

    echo
    echo "And now the fun really begins."
    echo

    sleep $JUST_A_SECOND
    while [ $i -lt $REPEATS ]
    do
        echo "-------FUNCTIONS------------>"
        echo "<---------ARE----------------"
        echo "<---------FUN---------------->"
        echo
        let "i+1"
    done
}

funky

fun

exit $?


# 带有参数的函数
#!/bin/bash

DEFAULT=default 

func2(){
    if [ -z "$1" ]
    then 
        echo "-Parameter #1 is zero length.-"
    else
        echo "-Parameter #1 is \"$1\".-"
    fi 

    variable=${1-$DEFAULT}
    echo "variable = $variable"


    if [ "$2" ]
    then
        echo "-Parameter #2 is \"$2\".-"
    fi

    return 0
}

echo 


echo "Nothing passed."
func2
echo

echo "Zero-length parameter passed."
func2 ""
echo

echo "Null parameter passed."
func2 "$uninitialized_param"
echo

echo "Two paramenters passed."
func2 first second 
echo

echo "\"\" \|second\" passed"
func2 "" second 
echo 
 
exit 0

Points to remember about functions

  • A function must be defined before its first call.
  • Functions cannot be empty.
  • If multiple functions have the same name, later definitions overwrite earlier ones; the last one is called.
  • The integer value returned by a function using return is stored in ¥?.