1.设定变量FILE的值为/etc/passwd
2.依次向/etc/passwd中的每个用户问好,并且说出对方的ID是什么
形如:(提示:LINE=`wc -l /etc/passwd | cut -d" " -f1`)
Hello,root,your UID is 0.
3.统计一个有多少个用户
答案一:#!/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"
答案二:#!/bin/bash
file=/etc/passwd
let num=0
for I in `cat $file`;do
username=`echo "$I" | cut -d: -f1`
userid=`echo "$I" | cut -d: -f3`
echo "Hello,$username,your UID is $userid"
num=$[$num+1]
done
echo "there are $num users"
练习二:写一个脚本
1.切换工作目录至/var
2.依次向/var目录中的每个文件或子目录问好,形如:
(提示:for FILE in /var/*;或for FILE in `ls /var`;)
Hello,log
3.统计/var目录下共有多个文件,并显示出来
答案:#!/bin/bash
cd /var
let num=0
for I in `ls /var/*`;do
echo "hello $I"
num=$[$num+1]
done
echo "the number of files is $num"
练习三:写一个脚本
1.设定变量file的值为/etc/passwd
2.使用循环读取文件/etc/passwd的第2,4,6,10,13,15行,并显示其内容
3.把这些行保存至/tmp/mypasswd文件中
答案:#!/bin/bash
file="/etc/passwd"
for I in 2 4 6 10 13 15;do
exec 3>/tmp/mypasswd
line=`head -$I $file | tail -1`
echo "$line"
echo "$line" >&3
exec 3>&-
done
答案如下:vim test.sh
#!/bin/bash
echo "first number $1" (表示输出第一个数)
echo " $(($1+$2))" (输出两数之和)
echo "$[$1-$2]" (输出两数之差)
echo "$[$1*$2]" (输出两数之积)
:wq (表示保存并退出vi编辑器)
chmod +x test.sh (给test.sh执行的权限)
./test.sh 2 3 (传递两个参数并执行脚本
#!/bin/bash
mkdir -v /tmp/scripts
cd /tmp/scripts
cp -r /etc/pam.d ./test
chown -R redhat ./test
chmod -R o=--- ./test
#!/bin/bash
date
mkdir -pv /tmp/lstest
cd /tmp/lstest
mkdir a1d b56e 6test
touch xy x2y 732
ls [ax6]*
ls [[:alpha:]][[:digit:]]*
作业三:写一个脚本
添加10个用户user1到user10,但要求只有用户不存在的情况下才能添加
答案:
#!/bin/bash
for I in `seq 1 10`;do
cut -d: -f1 /etc/passwd |grep "user$I" 2>>/tmp/etc.err || useradd user$I
done
作业四:写一个脚本
通过ping命令测试192.168.0.151到192.168.0.254之间的所有主机是否在线
如果在线,就显示“ip is up”
如果不在线,就显示“ip is down”
答案: #!/bin/bash
for I in `seq 151 254`;do
ping -c1 -w1 192.168.0.$I &>/dev/null && echo "192.168.0.$I is up" || echo "192.168.0.$I is down"
done
577



被折叠的 条评论
为什么被折叠?



