Shell基础(三):变量及if 分支

变量

赋值:赋值过程中,变量名,等号,变量值之间必须没有空格。变量值由可以展开成字符串的任意值。
a=z                       # Assign the string "z" to variable a.
b="a string"              # Embedded spaces must be within quotes.
c="a string and $b"       # Other expansions such as variables can be
# expanded into the assignment.
d=$(ls -l foo.txt)        # Results of a command.
e=$((5 * 7))              # Arithmetic expansion.
f="\t\ta string\n"        # Escape sequences such as tabs and newlines.
使用:$name ${name}
g=filename
h="${g}1"                 # filename1

Here Documents

定义:另一种形式的I/O重定向,用于在脚本文件中嵌入正文文本,然后发送给一个命令的标准输入。
语法:
command << token         # command 可以接受标准输入的命令名
text                     # 正文文本
token                    # 指示嵌入文本开始和结束的标记字符串 如:_EOF_
作用:位于Here Documents中的正文文本,其中的双引号和单引号都会失去其shell的特殊含义。
举例1:
#! /bin/bash
cat << _EOF_
Hello world!
This is your shell!
_EOF_
举例2:<<-  shell 会自动忽略正文文本开头的tab ,可提高脚本可读性。
#! /bin/bash
cat <<- _EOF_
    <html>
        <head>hello</head>
        <body>this is your shell</body>
    </html>
_EOF_

if分支结构

语法:
if commands; then 
    commands
[elif commands; then
    commands...]
[else
    commands]
fi
退出状态:命令执行完毕之后(包括shell 脚本,shell 函数),都会给系统返回一个值(0-255),叫退出状态。默认0代表成功,其它代表失败。$? 可以查看命令的退出状态。
ls -d /usr/bin && echo $?  => 0  # 检测存在的目录,退出状态为0.代表成功。
ls -d /bin/usr && echo $?  => 2  # 检测不存在的目录,退出状态为2.代表失败。
判断表达式:[ expression ]
常用检测文件表达式:

文件测试表达式

常用检测字符串表达式:

字符串表达式

常用检测整型表达式:

整型表达式

现代判断表达式:[[ expression ]]
支持原test表达式,新增支持 string =~ regex 支持匹配正则判断。 新增支持==操作符支持类型匹配
#! /bin/bash
# 检测一个值是不是数字
INT=-5
if [[ "$INT" =~ ^-?[0-9]+$ ]]; then
    echo "this is a number!"
fi
现代整型判断表达式:(( expression ))
#! /bin/bash
INT=-5
if ((INT == -5)); then 
    echo "this is -5"
fi
结合表达式:
操作符     测试表达式[]      现代表达式[[]] (())
AND            -a             &&
OR             -o             ||
NOT            !              !

猜你喜欢

转载自blog.csdn.net/YL_max/article/details/81587518
今日推荐