有关shell条件判断语句的用法与实例代码,shell if条件判断,case语句条件判断的例子,linux shell多个条件判断与和或的写法。
1、shell if语句进行条件判断
例子: #!/bin/bash read -p "Please input (Y/N) : " yn
if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then exit 0
(shell条件判断)结果:
复制代码代码示例:
[work@www sh]$ sh hello.sh
Please input (Y/N) : y Yes! [work@www sh]$ sh hello.sh Please input (Y/N) : l Input Error [work@www sh]$
2. case判断
例子: #!/bin/bash
case $1 in
exit 0
运行结果
[work@ww sh]$ sh hello.sh
Usage hello.sh (one|two) [work@www sh]$ sh hello.sh one One [work@www sh]$ linux shell多个条件判断与和或的写法
shell中的if条件判断语法,
if [ -e $file ]; then
echo 'exists' fi
如果是多个条件同时判断,
shell的条件与和条件或对应的运算符是:&&、||,
if [ -n $test1 ] || [ $test2 != 1 ]; then
echo 'test' fi
条件与运算:
if [ -n $test1 ] && [ $test2 != 1 ]; then
echo 'test' fi shell条件判断
传统if 从句子——以条件表达式作为 if条件
1、文件表达式
if [ -f file ] 如果文件存在
if [ -d ... ] 如果目录存在 if [ -s file ] 如果文件存在且非空 if [ -r file ] 如果文件存在且可读 if [ -w file ] 如果文件存在且可写 if [ -x file ] 如果文件存在且可执行
2、整数变量表达式
if [ int1 -eq int2 ] 如果int1等于int2
if [ int1 -ne int2 ] 如果不等于 if [ int1 -ge int2 ] 如果>= if [ int1 -gt int2 ] 如果> if [ int1 -le int2 ] 如果<= if [ int1 -lt int2 ] 如果<
If [ $a = $b ] 如果string1等于string2
字符串允许使用赋值号做等号 if [ $string1 != $string2 ] 如果string1不等于string2 if [ -n $string ] 如果string 非空(非0),返回0(true) if [ -z $string ] 如果string 为空 if [ $sting ] 如果string 非空,返回0 (和-n类似)
1、逻辑非 ! 条件表达式的相反
if [ ! 表达式 ]
if [ ! -d $num ] 如果不存在目录$num
2、逻辑与 –a 条件表达式的并列
if [ 表达式1 –a 表达式2 ]
3、逻辑或 -o 条件表达式的或
if [ 表达式1 –o 表达式2 ]
4、逻辑表达式
if [ -z "$JHHOME" -a -d $HOME/$num ]
注意:逻辑与-a与逻辑或-o很容易和其他字符串或文件的运算符号搞混了
最常见的赋值形式,赋值前对=两边的变量都进行评测
if test $num -eq 0 等价于 if [ $num –eq 0 ]
(责任编辑:IT) |