您的位置:首页 > 运维架构 > Shell

shell---practice2

2016-01-12 12:38 381 查看
要求:
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,会有报错,待改进!

本文出自 “经验来自痛苦” 博客,谢绝转载!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: