最近网上找了点脚本练习题,希望各位对各位练习shell的朋友能有所帮助。
(一)
写一个脚本:
1、创建目录/tmp/scripts
2、切换工作目录至此目录中
3、复制/etc/pam.d目录至当前目录,并重命令为test
4、将当前目录中的test及其里面的文件和子目录的属主改为redhat
5、将test及其子目录中的文件的其它用户的权限改为没有任何权限
#!/bin/bash # i=`grep -o 'root' /etc/passwd | cut -d: -f1 | head -n1` [ -d /tmp/scripts ] || mkdir /tmp/scripts if cp -rf /etc/pam.d /tmp/scripts ; then cd /tmp/scripts/ mv pam.d/ test/ if [ i = $0 ]; then chown -R redhat:root test/ else useradd redhat chown -R redhat:root test/ chmod -R o-rwx test/ fi fi
写一个脚本:
1、显示当前系统日期和时间,而后创建目录/tmp/lstest
2、切换工作目录至/tmp/lstest
3、创建目录a1d, b56e, 6test
4、创建空文件xy, x2y, 732
5、列出当前目录下以a、x或者6开头的文件或目录;
6、列出当前目录下以字母开头,后跟一个任意数字,而后跟任意长度字符的文件或目录;
#!/bin/bash # date mkdir /tmp/lstest cd /tmp/lstest mkdir ald b56e 6test touch xy x2y 732 echo "`ls | grep '^[a|x|6]'`" echo "`ls [[:alpha:]][[:digit:]]*`"
写一个脚本,完成以下功能:
1、传递两个整数给脚本,让脚本分别计算并显示这两个整数的和、差、积、商
#!/bin/bash # read -p "parameter1: " a1 read -p "parameter2: " a2 cat << EOF he) option cha) option ji) option shang) option EOF read -p " options: " s1 case $s1 in he) echo "$((a1+a2))" ;; cha) echo "$((a1-a2))" ;; ji) echo "$((a1*a2))" ;; shang) echo "$((a1/a2))" ;; esac
写一个脚本:
1、切换工作目录至/var
2、依次向/var目录中的每个文件或子目录问好,形如:
(提示:for FILE in /var/*; 或for FILE in `ls /var`; )
3、统计/var目录下共有多个文件,并显示出来
#!/bin/bash # cd /var for i in `ls -R /var` do echo "for File in var/$i" done ls -R /var | wc -l
写一个脚本:
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 head -$i $FILE | tail -1 >>/tmp/mypasswd done
写一个脚本:
1、设定变量FILE的值为/etc/passwd
2、依次向/etc/passwd中的每个用户问好
例如:Hello, root.
3、统计一共有多少个用户
#!/bin/bash # FILE=`cat /etc/passwd | cut -d: -f1` for i in $FILE do echo "Hello: $i." done echo "`cat /etc/passwd | cut -d: -f1 | wc -l`"
写一个脚本:
1、设定变量FILE的值为/etc/passwd
2、依次向/etc/passwd中的每个用户问好,并且说出对方的ID是什么,
Hello, root,your UID is 0.
3、统计一共有多少个用户
#!/bin/bash # FILE=/etc/passwd let LINE=0 LINE=`wc -l /etc/passwd | cut -d" " -f1` for i in `seq 1 $LINE`; do USERNAME=`head -$i $FILE | tail -1 | cut -d: -f1` UUID=`head -$i $FILE | tail -1 | cut -d: -f3` echo "Hello, $USERNAME,your UID is $UUID." done echo "users $LINE"
写一个脚本:
1、添加10个用户user1到user10,但要求只有用户不存在的情况下才能添加;
#!/bin/bash # for (( i=1; i<=10; i++ )) do grep "user$i" /etc/passwd &> /dev/null || useradd user$i &> /dev/null done
#!/bin/bash # for i in {1..10} do id user$i &> /dev/null if [ $? -eq 0 ]; then echo "user$i is zai" else useradd user$i &> /dev/null fi done
写一个脚本:
1、通过ping命令测试192.168.0.151到192.168.0.254之间的所有主机是否在线,
如果在线,就显示"ip is up."
如果不在线,就显示"ip is down."
#!/bin/bash # j=10.15.201. for (( i=151; i<=254; i++ )) do ping -c 1 -w 1 $j$i &>/dev/null && echo "$j$i ip is up" || echo "$j$i ip is down" done