Shell learning if statement

branch

if/then/elif/else/fi

Similar to the C language, the commands of if , then , elif , else , and fi are used to implement branch control in Shell . This flow control statement is also essentially composed of several shell commands, such as the previously mentioned

if [ -f ~/.bashrc ]; then

. ~/.bashrc

be

其实是三条命令,if [ -f ∼/.bashrc ]是第一条,then . ∼/.bashrc是第二条,fi是第三条。如果两条命令写在同一行则需要用;号隔开,一行只写一条命令就不需要写;号了,另外,then后面有换行,但这条命令没写完,Shell会自动续行,把下一行接在then后面当作一条命令处理。和[命令一样,要注意命令和各参数之间必须用空格隔开。if命令的参数组成一条子命令,如果该子命令的Exit Status0(表示真),则执行then后面的子命令,如果Exit Status0(表示假),则执行elifelse或者fi后面的子命令。if后面的子命令通常是测试命令,但也可以是其它命令。Shell脚本没有{}括号,所以用fi表示if语句块的结束。见下例:

#! /bin/sh
if [ -f /bin/bash ]
then
echo "/bin/bash is a file"
else
echo "/bin/bash is NOT a file"
be
if :; then echo "always true"; fi

" : " is a special command called empty command which does nothing but Exit Status is always true. In addition, you can also execute /bin/true or /bin/false to get a true or false Exit Status . Let's look at another example:

#! /bin/sh
echo "Is it morning? Please answer yes or no."

read YES_OR_NO

if [ "$YES_OR_NO" = "yes" ]; then

echo "Good morning!"

elif [ "$YES_OR_NO" = "no" ]; then

echo "Good afternoon!"

else

echo "Sorry, $YES_OR_NO not recognized. Enter yes or no."

exit 1

be

exit 0

The function of the read command in the above example is to wait for the user to input a line of string and store the string in a Shell variable.

In addition, Shell also provides && and || syntax, similar to C language, with Short-circuit feature, many Shell scripts like to write like this:

test "$(whoami)" != 'root' && (echo you are using a non-privileged account; exit 1)

&& is equivalent to " if ... then ..." and || is equivalent to " if not ... then ...". && and || are used to connect two commands, while -a and -o mentioned above are only used to connect two test conditions in a test expression, pay attention to their differences, for example:

test "$VAR" -gt 1 -a "$VAR" -lt 3

is equivalent to the following

test "$VAR" -gt 1 && test "$VAR" -lt 3

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324599896&siteId=291194637