需求一:写一个脚本
1.设定变量FILE的值为/etc/passwd
2.依次向/etc/passwd中的每个用户问好,并且说出对方的ID是什么
形如:(提示:LINE=`wc -l /etc/passwd | cut -d" " -f1`)
Hello,root,your UID is 0.
3.统计一个有多少个用户
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
#!/bin/bash file="/etc/passwd" LINES=`wc -l $file | cut -d" " -f1` for I in `seq 1 $LINES`;do userid=`head -$I $file | tail -1 |cut -d: -f3` username=`head -$I $file | tail -1 |cut -d: -f1` echo "hello $username,your UID is $userid" done echo "there are $LINES users"
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 #!/bin/bash 2 file=/etc/passwd 3 let num=0 4 for I in `cat $file`;do 5 username=`echo "$I" | cut -d: -f1` 6 userid=`echo "$I" | cut -d: -f3` 7 echo "Hello,$username,your UID is $userid" 8 num=$[$num+1] 9 done 10 echo "there are $num users"
需求二:写一个脚本
1.切换工作目录至/var
2.依次向/var目录中的每个文件或子目录问好,形如:
(提示:for FILE in /var/*;或for FILE in `ls /var`;)
Hello,log
3.统计/var目录下共有多个文件,并显示出来
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 #!/bin/bash 2 cd /var 3 let num=0 4 for I in `ls /var/*`;do 5 echo "hello $I" 6 num=$[$num+1] 7 done 8 echo "the number of files is $num"
练习三:写一个脚本
1.设定变量file的值为/etc/passwd
2.使用循环读取文件/etc/passwd的第2,4,6,10,13,15行,并显示其内容
3.把这些行保存至/tmp/mypasswd文件中
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 #!/bin/bash 2 file="/etc/passwd" 3 for I in 2 4 6 10 13 15;do 4 exec 3>/tmp/mypasswd 5 line=`head -$I $file | tail -1` 6 echo "$line" 7 echo "$line" >&3 8 exec 3>&- 9 done
练习四:写一个脚本
传递两个整数给脚本,让脚本分别计算并显示这两个整数的和,差,积,商
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 #!/bin/bash 2 echo "first number $1" (表示输出第一个数) 3 echo "second number $2" (表示输出第二个数) 4 echo " $(($1+$2))" (输出两数之和) 5 echo "$[$1-$2]" (输出两数之差) 6 echo "$[$1*$2]" (输出两数之积) 7 echo "$[$1/$2]" (输出两数之商) 8 :wq (表示保存并退出vi编辑器) 9 chmod +x test.sh (给test.sh执行的权限) 10 ./test.sh 2 3 (传递两个参数并执行脚本