条件判断
单分支的if语句
if 判断条件;then
statement1
statement2
....
fi
双分支的if语句
if 判断条件;then
statement1
statement2
else
statement3
....
fi
如
#!/bin/bash
name=ylis
if id $name &> /dev/null;then
echo "$name exists"
else
echo "$name does not exist"
echo $name | passwd --stdin $name
useradd $name
echo "Add $name finished"
fi
练习
- 给一个用户,UID为0,显示为管理员,
否则,显示为普通用户
nano par.sh
#!/bin/bash
name=yli
userid=`id -u $name`
if [ $userid -eq 0 ]; then #或者 if [ `id -u $name` -eq 0 ] 则不要上一个变量
echo "$name is the Admin"
else
echo "$name is a user"
fi
$ chmod +x par.sh
$ ./pra.sh
yli is a user
- 显示用户shell为bash的用户
$ nano bash.sh
#!/bin/bash
#
grep '\bbash$' /etc/passwd &> /dev/null
stat=$?
if [ $stat -eq 0 ]; then
users=`grep '\bbash$' /etc/passwd | wc -l`
echo "$users users"
names=`grep '\bbash$' /etc/passwd | cut -d: -f1`
echo -e "their names are \n$names"
else
echo "no such user."
fi
$ chmod +x bash.sh
$ ./bash.sh
20 users
their names are
root
ubuntu
jmzeng
spguo
fzhao
zgxu
myshen
syqu
yxwei
htwang
xlwan
tercent
jksong
dzhang
lmsong
yxiao
gyli
xyli
hocchan
yinqi
友情阅读推荐:
生信技能树公益视频合辑:学习顺序是linux,r,软件安装,geo,小技巧,ngs组学!
B站链接:https://m.bilibili.com/space/338686099
YouTube链接:https://m.youtube.com/channel/UC67sImqK7V8tSWHMG8azIVA/playlists
生信工程师入门最佳指南:https://mp.weixin.qq.com/s/vaX4ttaLIa19MefD86WfUA