失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > shell if/then/elif/else/fi

shell if/then/elif/else/fi

时间:2021-10-13 07:16:34

相关推荐

shell   if/then/elif/else/fi

shell中用if/then/elif/else/fi实现分支控制,本质上是由若干条shell命令组成。

例如

if [ -f ~/.bashrc ]; then. ~/.bashrcfi

如果两条命令需要在同一行写,那么用;隔开,一行只写一个命令则不需要用;隔开。

命令与各参数之间需要用空格隔开。

if 后面的子命令,如果该命令的exit status为0则表示为真,则执行then后面的子句。

如果为假那么则执行elif,else或者fi后面的子命令。

这个子命令通常为测试命令。shell脚本中没有{},所以用fi来表示if语句块的结束。

#! /bin/shif [ -f /bin/basn ]then echo "/bin/bash is a file"else echo "/bin/bash is NOT a file"fiif :;then echo "always true";fi

:是一个空命令,这个命令不做任何事情,结果永为真。此外,也可以执行/bin/true或/bin/false得到真或假的exit status

#!/bin/shecho "Is It morning? Please answer yes or no"read YES_OR_NOif [ "$YES_OR_NO"="yes" ];thenecho "Good morning!"elif [ "YES_OR_NO"="no" ];thenecho "Good afternoon!"else

这个例子中,read命令的作用是等待用户输入一个字符串,将该字符串储存在shell变量之中。

shell提供了&&与||语法,与C语类似,具有Short-circuit特性

&&的作用相当于if then

|| 相当于if not.....then

例如

[root@localhost ~]# test "$(whoami)"!="root" && (echo you are using a non-privileged account; exit 1)you are using a non-privileged account[root@localhost ~]# test "$(whoami)"!="root" || (echo you are using a non-privileged account; exit 1)[root@localhost ~]# #一个执行了后面的语句另一个并没有

如果觉得《shell if/then/elif/else/fi》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。