Bash

基本语法

# 变量不需要声明

root_path=$(realpath "./") # 绝对路径

echo ${root_path}  # 打印变量

echo "Build BASE dir: $root_path" # 打印变量

echo $(pwd) # 打印括号内命令执行结果 ,等价于 echo `pwd`

# \ 用作转义字符
# 单引号内的所有字符都保持它本身字符的意思,而不会被bash进行解释
# 除了$、``、/外,双引号内所有的字符保持字符本身的含义

# $1 $2 指执行 bash 时后面的参数
echo $1 # 在执行 `bash test.sh hhh` 时输出 hhh
# 含参数的函数
param="Null"
function varfield {
    local param="abc"
    # param="123"  # 改写Outer-param的值
    echo "In the function: param=[$param]" # abc
}
varfield
echo "Out of function: param=[$param]"  # Null
# if
if [ -z "$1" ]; then
    ARCH=amd64
else
    ARCH=$1
fi

# if [ -z "$1" ] 如果 $1 值为空则为真
# if [ -n "$1" ] 如果 $1 值存在则为真

# if [ -e /home/test.sh ] # 文件或目录存在则为真
# if [ -f /home/test.sh ] # 文件存在则为真
# if [ -d /home/test ] # 目录存在则为真

常用语句

# 获取 package.json 版本号
export ICONIFY_API_VERSION=$(grep -oE "\"version\": \"([0-9]+.[0-9]+.[a-z0-9.-]+)" package.json | cut -d\" -f4)
export VERSION=$(grep '"version":' package.json -m1 | cut -d\" -f4)

# 删除目录
rm -fR $BUILD_SOURCE/tmp
# 删除文件
rm -f $BUILD_SOURCE/tmp/build-ca-cert.crt

# 新建文件
touch $BUILD_SOURCE/tmp/build-ca-cert.crt

# 新建目录
mkdir -p $BUILD_SOURCE/tmp

# 拷贝文件
cp -f $SHARED_DIR/build-ca-cert.crt $BUILD_SOURCE/tmp/build-ca-cert.crt