Linux Structured Commands

内容概要: if-then, test condition ,case , for, while, until, nested loop ,looping on file data ,controlling loop…


1.if-then-fi:

The bash shell if statement is different from other languages. if the exit status of the if-command is 0, the commands listed under the then are executed.

if-then-elif-then-else-fi:
1
2
3
4
5
6
7
8
9
10
11
12
if command1
then
commands
elif command2
then
commands
elif command3
then
commands
else
commands
fi

Give a example:

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
if grep $1 /etc/passwd
then
echo "1. The bash files for user $1 are: "
ls -a /home/$2/.b*
elif grep $2 /etc/passwd
then
echo "2. The bash files for user $2 are: "
ls -a /home/$2/.b*
else
echo "Invalid user!"
fi


2.The test command:

2.1 The test command provides a way to test different conditions in an if-then statement.
1
2
3
4
5
6
7
8
9
10
11
#条件判断有两种可选的方式:
if test condtion
then
commands
fi

#或者采用下面的,注意空格
if [ condition ]
then
commands
fi
2.2 There are three classes of conditions the test commands can evaluate:
  • Numeric comparisons
  • String comparisons
  • File comparisons
2.3 Numeric comparison:
Comparison Description
m -eq n m等于n
m -ne n m不等于n
m -ge n m大于或等于n
m -gt n m大于n
m -le n m小于或等于n
m -lt n m小于n
举例说明:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/bin/bash
# 注意空格
m=10
n=20
if [ $m -eq 10 ]
then
echo "m==10"
fi

if test $m -ge $n
then
echo "m >= n"
elif [ $m -ne $n ]
then
echo "m != n"
else
echo "m<n"
fi
2.4 String comparison:
comparison description
str1 = str2
str != str2
str1 < str2
str1 > str2
-n str1 str1长度大于0
-z str1 str1长度等于0
2.5 File comparison:
comparison description
-d file file存在并且是direcory
-e file file存在
-f file file存在并且是FILE
-r file file存在并且可读
-s file file存在并且不为空
-w file file存在并且可写
-x file file存在并且可执行
-O file file存在并且由当前用户拥有
-G file file存在并且默认group与当前用户的group相同
file1 -nt file2 file1 is newer than file2
file1 -ot file2 file1 is older than file2
举例说明:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/bin/bash
if [ -e $HOME ]
then
echo "Your home directory exists!"
if [ -f $HOME ]
then
echo "yes,It is a file"
else
echo "NO, it is a directory!"
if [ -e $HOME/.bash_history ]
then
#var=`cat $HOME/.bash_history`
#echo $var
if [ -w $HOME/.bash_history ]
then
echo ".bash_history is a file you can write!"
else
echo ".bash_history is not writable!"
fi
fi
fi
else
echo "sorry, your HOME file does not exists!"
fi
2.6 Compound Condition Testing:

[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]

1
2
3
4
5
6
7
8
$ bash << EOF
> #!/bin/bash
> if [ -d $HOME ] && [ -w $HOME/test ];then
> echo The file exists and you can write to it!
> else
> echo I cannot write to the file
> fi
> EOF


3.Advanced if-then :

There are two advanced features that you can use in if-then statements

  • Double parentheses for mathematical expressions
  • Double square brackets for advanced string handling functions

3.1 Double parentheses: (( expression ))

The double parentheses command allows you to incorporate advanced mathematical formulas in your comparisons.

1
2
3
4
5
6
7
8
#!/bin/bash
val1=10

if (( $val1 ** 2 > 90 ))
then
(( val2 = $val1 **2 ))
echo The square of $val1 is $val2
fi

For循环

1
2
3
4
5
6
#!/bin/bash

for((x=0;x<10;x++))
do
echo $x
done

The double parentheses command symbols:
Symbol Description
val++
val–
++val
–val
! logical negation
~ bitwise negation
** exponentiation
<< left bitwise shift
>> right bitwise shift
& bitwise Boolean AND
bitwise Boolean OR
&& logical AND
logical OR

3.2 Double brackets: [[ expression ]]

The double brackets command provides advanced features for string comparisons.

1
2
3
4
5
6
7
8
#!/bin/bash

if [[ $USER == r* ]]
then
echo "Hello $USER"
else
echo "Sorry, I don't know you"
fi


4.Case command:

The case command checks multiple values of a single variable in a list-oriented format,

1
2
3
4
5
6
case variable in
pattern1) commands1;;
pattern2) commands2;;
pattern3 | pattern4) commands;;
*) default commands;;
esac

举例说明:

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash

case $1 in
jay)
echo "Hello jay!";;
root)
echo "This is root user!";;
zhang | bryant)
echo "zhang or bryant!";;
*)
echo "This is default commands!";;
esac


5.for command:

A loop that iterates through a series of values.
for

1
2
3
4
for var in list
do
commands
done

5.1 Reading values in a list && from a variable:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
list="Alabama Alaska Arizona Arkansas California Colorado"
list=$list" Washington"
for var in $list
do
echo "The next state is $var"
done
echo "The last state you visit is $var"

i=0
for var in Alabama Alaska Arizona Arkansas California Colorado "New Mexico"
do
((i=$i+1))
echo "state $i is $var"
done
5.2 Reading values from a command:

Another way to generate values for use in the list is to use the output of a command.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/bin/bash
file="/home/jay/.bash_history"

count=0
for var in `cat $file`
do
((count++))
echo "Command NO.$count : $var"
done


# Reading a directory using wildcards
for file in /home/jay/* /etc/*
do
if [ -d $file ]
then
echo "$file is a directory!"
elif [ -f $file ]
then
echo "$file is a file"
fi
done

5.3 The C-style for command:
for(( varibale assignment; condition; iteration process ))
1
2
3
4
5
6
7
#!/bin/bash
sum=0
for((i=1;i<=100;i++ ))
do
((sum=sum+i))
done
echo "sum of 1+...+100 = $sum"

6. while command:

When the test command returns a non-zero exit status, the while command stops executing the set of commands.
Basic format of the while command is

1
2
3
4
while test command
do
other commands
done

举例说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash

var=10
while [ $var -gt 0 ]
do
echo $var
var=$[$var-1]
done

# using multuple test commands
var=10
while echo $var
[ $var -gt 0 ]
do
echo "Inside the loop!"
var=$[$var-1]
done


7. until command:

The util command works exactly the opposite way from the while command. Once the test command returns a zero exit status, the loop stops.
The format of the until command is:

1
2
3
4
until test commands
do
other commands
done

举例说明:

1
2
3
4
5
6
var=100
until [ $var -eq 0 ]
do
echo $var
var=$[ $var-10 ]
done


8. Nesting Loops:

Some examples for nesting loops:

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash

var=5
while [ $var -gt 0 ]
do
echo "Outer loop: $var"
for ((var2=1;$var2<3;var2++))
do
var3=$[$var*$var2]
echo " Inner loop: $var * $var2 = $var3"
done
var=$[$var-1]
done


9. Looping on File Data:

Sometimes, you must iterate through items stored inside a file. This require combining two of the techniques covered:

  • using nested loops
  • changing the IFS environment variable
    By changing the IFS environment variable, you can force the for command to handle each line in the file as a separate item for processing, even if the data contains spaces.
    Here is an example of doing that:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    #!/bin/bash

    IFS_OLD=$IFS
    echo "Initial IFS=$IFS"

    #change IFS value to parse the individual lines
    IFS=$'\n'
    echo "Changed IFS=$IFS"

    count=0
    for entry in `cat /etc/passwd`
    do
    count=$[ $count+1 ]
    echo "Rows NO.$count >>> " $entry
    #change IFS value to the colon, which allows you to parse the individual values within each line.
    IFS=:
    for value in $entry
    do
    echo " $value"
    done
    done

10. Controlling the loop:

  • break command
  • continue command
    10.1 break command
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    #!/bin/bash

    #for loop
    for var in 1 2 3 4 5 6 7 8 9
    do
    if [ $var -eq 5 ]
    then
    break
    fi
    echo "for Iteration NO.$var"
    done

    #while loop
    var=1
    while [ $var -lt 10 ]
    do
    if [ $var -eq 5 ]
    then
    break
    fi
    echo "while Iteraion NO.$var"
    var=$[$var+1]
    done
10.2 break command
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/bin/bash

#continue in for loop
for (( var=1;var<15;var++ ))
do
if [ $var -gt 5 ] && [ $var -lt 10 ]
then
continue
fi
echo "for iteratin NO.$var"
done

#continue in while loop
var=0
while echo "while iteraion NO.$var"
[ $var -lt 15 ]
do
if [ $var -gt 5 ] && [ $var -lt 10 ]
then
var=$[$var+2]
continue
fi
echo " Inside iteration NO.$var"
var=$[$var+1]
done

11. 数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/bin/bash
#1.创建一个空数组
arrs=()

#2.初始化数组
arrs=("helo" "beijing" "china" 12 58 "well")

#3.数组的第二个元素
echo ${arr[1]}

#4.取得数组的所有元素
${arrs[@]}

#5.数组长度
${#arrs[@]}

#6.修改第一个元素
arrs[0]=2

#7.数组尾部添加一个元素
arrs+="jay"

#8.把ls的输出保存到字符串
str=$(ls)

#9.把ls的输出保存到数组
arrs=($(ls))

#10.取得从索引m开始的n个元素
${arr[@]:m:n}


#举例: 数组迭代
for i in ${arrs[@]}
do
echo $i
done

#数组迭代with index
for i in ${!arrs[@]}
do
echo "arrs["$i"]="${arrs[$i]}
done