if
单层
if [ expression ];then
statement1
statement2
...
fi
选择
if [ expression ];then
statement1
statement2
...
else
statement3
statemnnt4
...
fi
组合
if [ expression1 ];then
statement1
statement2
...
elif [ expression2 ];then
statement3
statement4
...
else
statement5
statement6
fi
符号 | 对照 | 注释 |
---|---|---|
if | if | 判断开始 |
elif | else if | 二次判断 可多重 |
fi | {} | shell 无{} 用 fi 表示结束囊括代码块 |
脚本
修改密码
上一篇有一个例子。
((!id godme && echo "godme does not exist, add godme" && useradd godme && echo "add godme success") || (echo "godme was existed"))|| echo "modify passwd" && (passwd --stdin godme && echo "modify password success" || echo "modify password failure") || echo "modify password over"
用逻辑连接符难免表意不清,现在修改一下。
#!/bin/bash
if id godme &>/dev/null ; then
echo "godme was existed"
else
echo "godme does not exist, add godme"
if useradd godme; then
echo "add godme success"
fi
fi
echo "modify password"
if passwd --stdin godme; then
echo "modify password success"
else
echo "modify password failure"
fi
echo "modify password over"
现在清楚多了。
power
上一篇有一个例子
#!/bin/bash
[ $# -eq 1 ] && file=$1
[ $# -eq 2 ] && mark=$1 && file=$2
[ -z $mark ] && position='2-10'
[ "$mark" = '-a' ] && position='8-10'
[ "$mark" = '-o' ] && position='2-4'
[ "$mark" = '-g' ] && position='5-7'
echo -n `ls -l $file | cut -d' ' -f1 | cut -c$position`
echo -e "\t $file"
修改
#!/bin/bash
if [ $# -eq 1 ] ;then
file=$1
elif [ $# -eq 2 ]; then
file=$2
mark=$1
else
exit 0
fi
if [ "$mark" = "-a" ];then
position="8-10"
elif [ "$mark" = "-o" ];then
position="2-4"
elif [ "$mark" = "-g" ];then
position="5-7"
else
position="2-10"
fi
echo -e `ls -l $file | cut -d' ' -f1 | cut -c$position` "\t $file"
vim
#!/bin/bash
user=`id -un`
if [ "$user" -eq "godme" ];then
\vim $*
else
echo "no power to vim"
fi
alias vim='/home/godme/vim'
设置好别名以后,就只有godme
能够去vim
了。
不过,之前就说过了,也只能骗骗不会的人了。