1. # 直接使用管道
ps -ef |while read firstvar
do
echo "firstvar : $firstvar"
secondvar=$firstvar
echo "secondvar: $secondvar"
done
# bash中循环中设置的变量firstvar无效
# bash中循环内设置的变量secondvar无效
echo "firstvar outside: $firstvar"
echo "secondvar outside: $secondvar"
2. # 使用临时文件进行改造
ps -ef >./tmp.txt
while read firstvar
do
echo "firstvar : $firstvar"
secondvar=$firstvar
echo "secondvar: $secondvar"
done <./tmp.txt
# bash中循环中设置的变量firstvar无效
# bash中循环内设置的变量secondvar有效
echo "firstvar outside: $firstvar"
echo "secondvar outside: $secondvar"
3.# 使用here document方案解决
INPUT=`ps -ef`
while read firstvar
do
echo "firstvar : $firstvar"
secondvar=$firstvar
echo "secondvar: $secondvar"
done <
$INPUT
EOF
# bash中循环中设置的变量firstvar无效
# bash中循环内设置的变量secondvar有效
echo "firstvar outside: $firstvar"
echo "secondvar outside: $secondvar"
4. # 不使用管道
ps -ef >/root/tmp.txt
filecount=`wc -l /root/tmp.txt|awk '{print $1}'`
count=0
while [ "$count" -le "$filecount" ]
do
firstvar=`tail -$count /root/tmp.txt |head -1`
echo "firstvar: $firstvar"
secondvar=$firstvar
echo "secondvar: $secondvar"
count=`echo $count+1 |bc`
done <./tmp.txt
# bash中循环中设置的变量firstvar有效
# bash中循环内设置的变量secondvar有效
echo "firstvar outside: $firstvar"
echo "secondvar outside: $secondvar"
5. # 逐字处理shift左移
set `echo a b c d e`
while [ "$1" != "" ]
do
foo=$1 bar=$2
echo $*
shift
echo foo $foo
echo bar $bar
echo "---------------"
done
阅读(699) | 评论(0) | 转发(0) |