快速参考

https://quickref.cn/docs/bash.html#bash-%E5%87%BD%E6%95%B0

入门

hello.sh

#!/bin/bash
VAR="world"
echo "Hello $VAR!" # => Hello world!

执行脚本

$ bash hello.sh

变量

NAME="John"
echo ${NAME}    # => John (变量)
echo $NAME      # => John (变量)
echo "$NAME"    # => John (变量)
echo '$NAME'    # => $NAME (字符串原样输出)
echo "${NAME}!" # => John! (变量)
NAME = "John"   # => Error (注意不能有空格)

注释-Comments

# This is an inline Bash comment.
: '
This is a
very neat comment
in bash
'

多行注释使用 :’ 打开和 ‘ 关闭

参数Arguments

序号 名称
$1 … $9 Parameter 1 … 9
$0 Name of the script itself
$1 First argument
${10} Positional parameter 10
$# Number of arguments
$$ Process id of the shell
$* All arguments
$@ All arguments, starting from first
$- Current options
$_ Last argument of the previous command

函数 Functions

get_name() {
    echo "John"
}

echo "You are $(get_name)"

条件句

if [[ -z "$string" ]]; then
    echo "String is empty"
elif [[ -n "$string" ]]; then
    echo "String is not empty"
fi

大括号扩展

echo {A,B}.js
序号 描述
{A,B} Same as A B
{A,B}.js Same as A.js B.js
{1..5} Same as 1 2 3 4 5

Shell执行

# => I'm in /path/of/current
echo "I'm in $(PWD)"

# Same as:
echo "I'm in `pwd`"

Bash 参数扩展