要求:
1.设定变量file的值为/etc/passwd
2.使用循环读取文件/etc/passwd的第2,4,6,10,13,15行,并显示其内容
3.把这些行保存至/tmp/mypasswd文件中
#!/bin/bash #File: for_dir.sh #Date: 2016-01-12 changeFile="/tmp/mypasswd" //定义changFile变量的值 if [ ! -f $changeFile ]; then //判断changFile是否存在 touch $changeFile else echo "The $changeFile is exist." fi #if [ ! -x $changeFile ]; then //此if语句为赋予权限,可以省略 # chmod +x $changeFile #else # echo "The $changeFile with executable permissons." #fi file="/etc/passwd" //定义file变量的值 for i in 2 4 6 10 13 15 //将i做for循环,依次赋值2 4 6 10 13 15 do line=`sed -n "$i"p $file` //取出对应的行,并赋值给变量line echo "$line" echo "$line" >> /tmp/mypasswd done
注:脚本最后追加部分,建议写绝对路径/tmp/mypasswd,如果写成变量$changeFlie,会有报错,待改进!
本文出自 “经验来自痛苦” 博客,谢绝转载!
原文:http://strike.blog.51cto.com/10311680/1734122