标签:
for命令格式:
– list参数:迭代中要用的一系列值
– 每个迭代中,变量var会包含列表中的当前值
– do和done语句之间输入的命令可以是一条或多条标准的bash shell命令
1
2
3
4
|
for var in list
do
commands
done
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
$cat test
#!/bin/bash
for test in Alabama Alaska Arizona Arkansas California Colorado
do
echo The next state is $test
done
echo "The last state we visited was $test"
test=Connecticut
echo "Wait , now we‘re visiting was $test"
$./test
The next state is Alabama
The next state is Alaska
...
The last state we visited was Colorado
wait, now we‘re visiting Connecticut
|
1
2
3
4
5
6
7
8
9
10
11
|
$cat test
#!/bin/bash
for test in I don‘t know if "this‘ll" work
do
echo "word:$test"
done
$./test
word:I
word:don‘t
...
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
$cat test
#!/bin/bash
list=“Alabama Alaska Arizona Arkansas California Colorado”
list=$list" Connecticut"
for state in $list
do
echo "Have you ever visited $state?"
done
$./test
Have you ever visited Alabama?
...
Have you ever visited Connecticut?
$
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
$cat test
#!/bin/bash
file="states"
for state in `cat $file`
do
echo "Visit beautiful $state"
done
$cat states
Alabama
Alaska
...
$./test
Visit beautiful Alabama
Visit beautiful Alaska
...
|
1
2
3
4
|
IFS.OLD=$IFS
IFS=$‘\n‘
<use the new IFS value in code>
IFS=$IFS.OLD
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
...
for file in /home/rich/test/*
do
if [ -d "$file" ]
then
echo "$file is a directory"
elif [ -f第12章:更多结构化命令
第6章:理解Linux文件权限.md "$file" ]
then
echo "$file is a file"
fi
done
...
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
...
for file in /home/rich/.b* /home/rich/badtest
do
if [ -d "$file" ]
then
echo "$file is a directory"
elif [ -f "$file" ]
then
echo "$file is a file"
else
echo "$file doesn‘t exist"
fi
done
|
1
2
3
4
5
6
7
8
9
10
11
|
$cat test
#!/bin/bash
for (( i=0; i<10; i++ ))
do
echo "The next number is $i"
done
$./test
The next number is 1
The next number is 2
...
|
1
2
3
4
5
6
|
...
for (( a=1, b=10; a <= 10; a++, b-- ))
do
echo "$a - $b"
done
...
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
while test command
do
other commands
done
//eg:
...
var1=10
while [ $var1 -gt 0 ]
do
echo $var1
var1=$[ $var1 - 1 ]
done
...
|
1
2
3
4
|
until test commands
do
other commands
done
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
$cat test
#!/bin/bash
IFS.OLD=$IFS
IFS=$‘\n‘
for entry in `cat /etc/passwd`
do
echo "values in $entry -"
IFS=:
for value in $entry
do
echo " $value"
done
done
$./test
Value in rich:x:501:501:Rich Blum:/home/rich:/bin/bash -
rich
x
501
...
/bin/bash
Value in ...
|
1
2
3
4
5
6
7
8
9
|
for file in /home/rich*
do
if [ -d "$file" ]
then
echo "$file is a directory"
elif
echo "$file is a file"
fi
done > output.txt
|
1
2
3
4
5
6
|
...
for ...
...
done | sort
echo "This completes our place to go"
$
|
标签:
原文地址:http://www.cnblogs.com/zhangmingcheng/p/5812750.html