1、编写一个 Shell脚本,程序执行时从键盘读入一个目录名,如果用户输入的目录不存在,则提示file does not exist;如果用户输入的不是目录则提示用户必须输入目录名;如果用户输入的是目录则显示这个目录下所有文件的信息。
[root@server shell]# mkdir chap03/
[root@server chap03]# vim ml.sh
#编写脚本文件ml.sh内容:
#!/bin/bash
unset file
read -p "please input your filename:" file
! test -a "$file" && echo "the file does not exist" && exit 0
[ -d "$file" ] && filetype="directory"
echo "the $file is a $filetype" && ls $file
[root@server chap03]# bash ml.sh
please input your filename:/shell
the /shell is a directory
chap01 chap02 chap03 chap04
[root@server chap03]# bash ml.sh
please input your filename:chap03
the file does not exist
2、写一个脚本,完成以下要求:让用户输入用户名,如果其UID为0,就显示此为管理员;否则,就显示其为普通用户。
[root@server chap04]# vim test2.sh
#编写脚本test2.sh内容:
#!/bin/bash
read -p "请输入用户名:" username
[ `id -u $username` -eq 0 ] && echo "管理员" || echo "普通用户"
#测试:
[root@server chap04]# bash test2.sh
请输入用户名:root
管理员
[root@server chap04]# bash test2.sh
请输入用户名:xiaoming
普通用户
3、写一个脚本,给定一个用户,判断其UID与GID号码是否一样,如果一样,就显示此用户为“good guy”;否则,就显示此用户为“bad guy”。
[root@server shell]# mkdir chap05
[root@server shell]# cd chap05
[root@server chap05]# ll
total 0
[root@server chap05]# vim test1.sh
#编写脚本文件test1.sh内容:
#!/bin/bash
read -p "请输入一个已有的用户名:" username
[ `id -u $username` -eq `id -g $username` ] && echo "good guy" || echo "bad guy"
[root@server chap05]# bash test1.sh
请输入一个已有的用户名:root
good guy
[root@server chap05]# bash test1.sh
请输入一个已有的用户名:xiaoming
bad guy
4、写一个脚本,给定一个文件,比如/etc/inittab,判断这个文件中是否有空白行;如果有,则显示其空白行数;否则,显示没有空白。
[root@server chap06]# vim test3.sh
#编写脚本文件test3.sh内容:
#!/bin/bash
read -p "please input a file:" file
test3=$(grep '^$' $file |wc -l)
if [ $test3 -eq 0 ]
then
echo '没有空白'
else
echo $test
fi
#测试:
[root@server chap06]# bash test3.sh
please input a file:/etc/inittab
没有空白