美文网首页
LinuxCommandLine -- [脚本 if]

LinuxCommandLine -- [脚本 if]

作者: liaozb1996 | 来源:发表于2018-04-30 13:00 被阅读0次

状态码

  • 范围:0 ~ 255
  • 0: 正常退出
  • 其他:发生异常
  • $? 显示上一条命令的退出状态码
  • true
  • false
  • exit <num>
  • return
# 正常退出
$ ls
$ echo $?
0

# 异常
$ ls non-exist
ls: cannot access non-exist: No such file or directory
$ echo $?
2

if 语法

if [ condition ]; then
    commands
elif [ condition ]; then
    commands
else
    commands
fi

比较符

字符串

String

整数

integer.PNG

文件

test_file_1
test_file_2

test

  • [ condition ]
  • [[ condition ]] 除了支持 [] 的所有特性外,还支持 [[ string =~ regex ]]
  • (( )) 用于整数
  • command1 && command2 command1 执行成功时,执行 command2
  • command1 || command2 command1 执行失败时,执行command2
# is_num.sh
#------------
#!/bin/bash

read -p "Enter something: " num

if [[ "$num" =~ ^-?[[:digit:]]+$ ]]; then
    echo "$num is a number"
else
    echo "$num is not a number"
fi

INT=-5

比较:变量名前不用加 $
(( INT == 0 ))

# 计算
(( ((INT % 2)) == 0))

相关文章

网友评论

      本文标题:LinuxCommandLine -- [脚本 if]

      本文链接:https://www.haomeiwen.com/subject/mneolftx.html