If condition judgment and if True and false judgment
Directory:
1. Correct wording
2. Wrong wording
3. Summary
First, the correct wording
When writing shell scripts, to simplify the line numbers and structure of the code, it is common to write command execution results and judgments in a single statement (often encountered when writing programs in C language), such as:
[[Email protected] ~] #touch test.sh if Useradd root &>/dev/null; then #如果用户添加成功 is not displayed, otherwise the display user add fails echo "User1 created Successfu" &>/dev/null
Else echo "User1 created failed" Fi [[Email protected] ~] #chmod +x test.sh [Email protected] ~]#./test.sh User1 created failed |
Second, the wrong wording
But if you add [] judgment because of memory lapses or scripting habits, the script becomes as follows:
[[Email protected] ~] #touch test.sh If [Useradd user1 &>/dev/null]; then #如果用户添加成功 is not displayed, otherwise the display user add fails echo "User1 created Successfu" &>/dev/null
Else echo "User1 created failed" Fi [[Email protected] ~] #chmod +x test.sh [Email protected] ~]#./test.sh #
User1 created failed [[Email protected] ~] #id user1 #用户添加成功, should not be displayed, but display add failed uid=1005 (user1) gid=1005 (user1) groups=1005 (user1)
[[Email protected] ~] #userdel-R user1 ##################### #调试模式执行 ################################################### [[Email protected] ~] #bash-X 4.sh + ' [' Useradd user1 '] ' #命令执行成功, but the display fails, the reason is judged in the add [] condition,
+ Echo ' User1 created failed ' #条件判断默认是判断useradd User1 added successfully, command results are not displayed User1 created failed #因此默认 [-n '] is empty, so the display fails
|
Iii. Summary
Summing up, in the use if judgment and the command execution result of the grammatical structure, the command line in the middle of avoid the judgment, conditional judgment must add conditional judgment expression. The essence is the difference between true and false judgment and if condition judgment
true and false judgment Conditional Judgment
if CMD; Then if [statement]; Then
CMD statement cmd statement
else Else
CMD statement cmd statement
Fi fi
|
####################################################################################
### For details, please contact: QQ767743577 e-mail address: [email protected], have asked to answer, there is Bing, everyone for me, I for everyone ###
####################################################################################
This article from "Progress a little bit, self-discipline" blog, please be sure to keep this source http://wbxue.blog.51cto.com/11831715/1964460
Shell programming if condition judgment and if true and false judgment