Linux 教程 之 Linux Shell 教程 Shell 流程控制 5

简介: Shell 流程控制

Linux 教程 之 Linux Shell 教程 Shell 流程控制 5

Shell 教程

Shell 流程控制

和 Java、PHP 等语言不一样,sh 的流程控制不可为空,如(以下为 PHP 流程控制写法):

实例

<?php
if (isset($_GET["q"])) {
search(q);
}
else {
// 不做任何事情
}

在 sh/bash 里可不能这么写,如果 else 分支没有语句执行,就不要写这个 else。

if else

fi

if 语句语法格式:

if condition
then
command1
command2
...
commandN
fi

写成一行(适用于终端命令提示符):

if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi

末尾的 fi 就是 if 倒过来拼写,后面还会遇到类似的。

if else

if else 语法格式:

if condition
then
command1
command2
...
commandN
else
command
fi

if else-if else

if else-if else 语法格式:

if condition1
then
command1
elif condition2
then
command2
else
commandN
fi

if else 的 [...] 判断语句中大于使用 -gt,小于使用 -lt。

if [ "$a" -gt "$b" ]; then
...
fi

如果使用 ((...)) 作为判断语句,大于和小于可以直接使用 > 和 <。

if (( a > b )); then
...
fi

目录
相关文章
|
9月前
|
Shell Linux
|
9月前
|
Shell Linux
|
9月前
|
Shell Linux
|
9月前
|
Shell Linux
|
9月前
|
Shell Linux
|
9月前
|
Shell Linux
|
9月前
|
Shell Linux
|
9月前
|
Unix Shell Linux
|
9月前
|
Java Shell Linux
|
9月前
|
Java Shell Linux