shell 脚本 循环

shell for 循环  参考 Linux下Shell的for循环语句Shell逐行读取文件的3种方法

for循环语法

for var in item1 item2 ... itemN
do
    command
done

 for循环 路径查找

  在/mx文件夹有文件  check_list  md5result  test_for.sh  test.sh

语法:for file in filepath/*

filepath2=/mx/*

for file in ${filepath2}
do echo ${file}
done

输出如下

/mx/check_list
/mx/md5result
/mx/test_for.sh
/mx/test.sh

语法:for file in `find filepath`

filepath=/mx

for file in `find ${filepath}`
do echo ${file}
done

for循环输出如下

/mx
/mx/check_list
/mx/md5result
/mx/test.sh
/mx/test_for.sh

语法:for file in `find filepath -type f `  只查询 一般文件

filepath=/mx

#只查询 /mx文件夹下的 一般文件
for file in `find ${filepath} -type f`
do echo "${file}"    
done

for循环输出如下 只查询 一般文件
/mx/check_list
/mx/md5result
/mx/test.sh
/mx/test_for.sh

while语法: 

while condition
do
    command
done

3.1 cat file | while read 读取文件并处理文件       每次读取一行 ,每一行的内容使用IFS作为分隔符读文件 默认情况下IFS是空格,如果需要使用其它的需要重新赋值  例如   IFS=:    参考while read读取文本内容

例子 有如下文件 

ip user pwd
10.1.1.11 root 123
10.1.1.22 root 111
10.1.1.33 root 123456
10.1.1.44 root 54321

while read 读取文件,以空格作为域分隔符,并给每一列取名字。

cat FILE_PATH |while read ip user pwd 
do 
    echo "$ip--$user--$pwd"
done

3.2 cat file | awk command | while read   结合awk 文本文件处理命令,指定读取文件的行 并处理文件

#从第2行开始读取文件
cat FILE_PATH | aqk 'NR>1' while read ip user pwd 
do 
    echo "$ip--$user--$pwd"
done
发布了208 篇原创文章 · 获赞 84 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/dreamstar613/article/details/105082351
今日推荐