Linux shell for循环
bash shell提供了for命令,允许你创建一个遍历一系列值的循环。每次迭代都使用其中一个值来执行已定义好的一组命令。
格式:
for var in list
do
commands
done
例子:
#!/bin/bash
for test in 北京 上海 深圳 成都 武汉 郑州
do
echo The next state is $test
done
#!/bin/bash
for test in 北京 上海 深圳 成都 武汉 郑州
do
echo The next state is $test
done
echo last time we visited was $test
#!/bin/bash
for test in I don't know if this'll work
do
echo "word:$test"
done
#!/bin/bash
for test in I don\'t know if this\'ll work
do
echo "word:$test"
done
#!/bin/bash
for test in I "don't" know if "this'll" work
do
echo "word:$test"
done
#!/bin/bash
for test in Nevada New Hampshire New Mexico New York
do
echo "word:$test"
done
for 命令用空格来划分列表中的每个值。
#!/bin/bash
for test in Nevada "New Hampshire" "New Mexico" "New York"
do
echo "word:$test"
done
#!/bin/bash
list='Nevada "New Hampshire" "New Mexico" "New York"'
for test in $list
do
echo "word:$test"
done
#!/bin/bash
file_name=$HOME/number
for num in $(cat $file_name)
do
echo $num
done
#!/bin/bash
file_name=$HOME/line
for item in $(cat $file_name)
do
echo $item
done
可以从输出看到行中有空格,输出就会换行。是因为IFS的原因。
特殊环境变量IFS:内部字段分隔符,默认将空格,制表符,换行符当作字段分隔符
#!/bin/bash
file_name=$HOME/line
IFS_OLD=$IFS
IFS=$'\n'
for item in $(cat $file_name)
do
echo $item
done
IFS=$IFS_OLD
#!/bin/bash
file_name=$HOME/line
IFS_OLD=$IFS
IFS=$'\n':;
for item in $(cat $file_name)
do
echo $item
done
IFS=$’\n’:;会将换行,冒号和分号当作分隔符。
#!/bin/bash
file_name=$HOME/*
for item in $file_name
do
if [ -d "$item" ]; then
echo $item is a directory
elif [ -f "$item" ]; then
echo $item is a file
fi
done
在Linux中,目录名和文件名中包含空格当然是合法的。要适应这种情况,应该将$item变量用双引号圈起来。如果不这么做,遇到含有空格的目录名或文件名时就会有错误产生。
#!/bin/bash
file_name="$HOME/sentinel $HOME/post*"
for item in $file_name
do
if [ -d "$item" ]; then
echo $item is a directory
elif [ -f "$item" ]; then
echo $item is a file
fi
done
C语言的for:
#!/bin/bash
for((i=0;i<10;i++ ))
do
echo $i
done
#!/bin/bash
for(( a=1,b=10;a<=10;a++,b--))
do
echo "$a - $b"
done