#!/bin/bash
#xxxxxxxxxxx
echo $0 bash.sh 名称
echo $#,$* 6,a b c d e f
echo $1,$3,$5 a,c,e
:wq!
bash haha.sh a b c d e f
[ -d /etc ]
Echo $? 返回0 正常值存在
[ -d /etcghjksdfg ]
Echo $? 返回1 不存在
&& 当命令成功,则执行后面的语句
|| 当命令失败,则执行后面的语句
! 取反值
[ -f /etc/fstab ] && echo “ok”
[ -f /etc/fstabkiejieke ] && echo “ok”
[ -f /etc/fstabkijeiekek ] || echo “no”
Echo $USER
[ $USER = root ] && echo “admin” || echo “user”
su - linuxprobe
[ $USER = root ] && echo “admin” || echo “user”
[ $USER = root ]
echo $?
[ ! $USER = root ]
echo $?
> 输入重定向 < 输入重定向 = 赋值法
[ `free –m | grep Mem: | awk `’{print $4}’` -lt 1024 ] && echo “buzu” || echo “chongzu”
lnmp.org 用shell 脚本编出来的
判断变量值是否为空
[ -z String ]
echo $?
if分为单次、双次、多次
#!/bin/bash
#xxxxxxxxxxxxxxxxxxx
if [ ! -e /meida/haha ]
then
mkdir –p /media/haha
fi
:wq!
Ls /media
Bash haha.sh
Ls /media
单分支判断语句
#!/bin/bash
ping - c 3 – i 0.2 – W 3 $1 &> /dev/null
if [ $? –eq 0 ]
then
echo “Host $1 is On-line”
else
echo “Host $1 is Off-line”
fi
:wq!
bash haha.sh 192.168.10.10
双分支的判断语句
#!/bin/bash
read –p “Enter: ” GRADE -p提示信息
if [ $GRADE – ge 85 ] && [ $GRADE – le 100 ] ; then
echo “Excellent”
elif [ $GRADE - ge 70 ] && [ $GRADE- le 84 ] ; then
n
echo “Pass”
else
echo “Failure”
fi
:wq!
bash haha..sh
90
else是所有没有被规定以外的都是else
vim user.txt
zhangshan
lishi
wangwu
zhaoliu
:wq!
vim haha.sh
#!/bin/bash
read –p “Enter:” PASSWD
for UNAME in `cat user.txt`
do
id $UNAME &> /dev/null
if [ $? – eq 0 ]
then
echo “Already exist”
else
useradd $UNAME &> /dev/null
echo “$PASSWD” | passwd - - stdin &> /dev/null
if [ $? - eq 0 ]
then
echo “$UNAME,Create success”
else
echo “$UNAME,Create.fail”
fi
done
bash haha.sh
id zhangsan
id lisi
id wangwu
多次循环
Vim ip.txt
192.168.10.10
192.168.10.11
192.168.10.12
vim haha.sh
#!/bin/bash
for IP in `cat ip.txt`
do
ping – c 3 – I 0.2 – W 3 $ IP &> /dev/null
If [ $? –eq 0 ] ; then
echo “host $IP is on-line”
else
echo “Host $IP is off-line”
fi
done
原文:https://www.cnblogs.com/fangbin/p/11878275.html