除了前面提到的结构化的命令,还有其他。
for的使用
xin@xin ~/Test $ cat a.sh
#!/bin/bash
for test in aaa bbb ccc ddd eee ; do
echo "当前值为:$test"
done
xin@xin ~/Test $ bash a.sh
当前值为:aaa
当前值为:bbb
当前值为:ccc
当前值为:ddd
当前值为:eee
当遇到'这样的符号时候可以使用\转义,或者使用""
xin@xin ~/Test $ cat b.sh
#!/bin/bash
for test in I don\'t know if "this'll" work ; do
echo "world:$test"
done
xin@xin ~/Test $ bash b.sh
world:I
world:don't
world:know
world:if
world:this'll
world:work
从变量读取列表
xin@xin ~/Test $ cat c.sh
#!/bin/bash
list="Alabama Alaska Arizona Arkansas Colordo"
list=$list" Connecticut"
for state in $list ; do
echo "Have you ever visited $state"
done
xin@xin ~/Test $ bash c.sh
Have you ever visited Alabama
Have you ever visited Alaska
Have you ever visited Arizona
Have you ever visited Arkansas
Have you ever visited Colordo
Have you ever visited Connecticut
从命令中读取
xin@xin ~/Test $ cat d.sh
#!/bin/bash
for state in `cat test` ; do
echo $state
done
xin@xin ~/Test $ bash d.sh
aaaaaaa
bbbbbbb
ccccccc
ddddddd
eeeeeee
fffffff
更改字段的分割符
默认情况下分割符为:空格、制表符、换行符
IFS=$'\n'
往往我们会这么做
IFS.OLD=$IFS
执行后
IFS=$IFS.OLD
通配符对目录的读取
xin@xin ~/Test $ cat e.sh
#!/bin/bash
for file in /home/xin/test/* ; do
if [ -d "$file" ] ; then
echo "$file is a directory"
elif [ -f "$file" ] ; then
echo "$file is a file"
fi
done
xin@xin ~/Test $ bash e.sh
/home/xin/test/1.sh is a file
C语言风格是for
xin@xin ~/Test $ cat a.sh
#!/bin/bash
for (( i=1; i <= 10; i++ )) ; do
echo "The next number is $i"
done
xin@xin ~/Test $ bash a.sh
The next number is 1
The next number is 2
The next number is 3
The next number is 4
The next number is 5
The next number is 6
The next number is 7
The next number is 8
The next number is 9
The next number is 10
使用多个变量
xin@xin ~/Test $ cat b.sh
#!/bin/bash
for (( a=1,b=10; a<=10; a++,b-- )) ; do
echo "$a - $b"
done
xin@xin ~/Test $ bash b.sh
1 - 10
2 - 9
3 - 8
4 - 7
5 - 6
6 - 5
7 - 4
8 - 3
9 - 2
10 - 1
while
xin@xin ~/Test $ cat c.sh
#!/bin/bash
var1=10
while [ $var1 -gt 0 ] ; do
echo $var1
var1=$[ $var1 - 1 ]
done
xin@xin ~/Test $ bash c.sh
10
9
8
7
6
5
4
3
2
1
使用多个测试命令
xin@xin ~/Test $ cat d.sh
#!/bin/bash
var1=10
while echo $var1; [ $var1 -ge 0 ]; do
echo "This is inside the loop"
var1=$[ $var1 - 1 ]
done
xin@xin ~/Test $ bash d.sh
10
This is inside the loop
9
This is inside the loop
8
This is inside the loop
7
This is inside the loop
6
This is inside the loop
5
This is inside the loop
4
This is inside the loop
3
This is inside the loop
2
This is inside the loop
1
This is inside the loop
0
This is inside the loop
-1
until的使用
xin@xin ~/Test $ cat 1.sh
#!/bin/bash
var1=100
until [ $var1 -eq 0 ] ; do
echo $var1
var1=$[ $var1 - 25 ]
done
xin@xin ~/Test $ bash 1.sh
100
75
5