條件判斷
單分支的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
學徒培養(yǎng):https://mp.weixin.qq.com/s/3jw3_PgZXYd7FomxEMxFmw