n=0 until [ "$n" -ge 5 ] do command && break# substitute your command here n=$((n+1)) sleep 15 done # 或者 # command 退出码为 0 则为 true 继续执行 break 而不会执行 sleep for i in {1..5}; docommand && break || sleep 15; done # 或者写成函数 function fail { echo$1 >&2 exit 1 }
function retry { local n=1 local max=5 local delay=15 whiletrue; do "$@" && break || { if [[ $n -lt $max ]]; then ((n++)) echo"Command failed. Attempt $n/$max:" sleep $delay; else fail "The command has failed after $n attempts." fi } done }
# -z 检查目标变量值长度是否为零 if [[ -z "${DEPLOY_ENV}" ]]; then MY_SCRIPT_VARIABLE="Some default value because DEPLOY_ENV is undefined" else MY_SCRIPT_VARIABLE="${DEPLOY_ENV}" fi
# or even shorter use MyVar="${DEPLOY_ENV:-default_value}"
# 未设置则报错 : "${STATE?Need to set STATE}" : "${DEST:?Need to set DEST non-empty}" [ -z "$STATE" ] && echo"Need to set STATE" && exit 1;
# 或者 if [[ ! -v DEPLOY_ENV ]]; then echo"DEPLOY_ENV is not set" elif [[ -z "$DEPLOY_ENV" ]]; then echo"DEPLOY_ENV is set to the empty string" else echo"DEPLOY_ENV has the value: $DEPLOY_ENV" fi
让脚本执行更安全
1 2 3 4 5 6 7 8 9 10
set -euxo pipefail # 默认情况下某行命令执行出错后脚本会继续执行 # set -e 使脚本执行出错则立即退出,不再执行后续命令, 如果想阻止命令执行失败退出,则可以在命令后增加 || true invalid_cmd || true # 默认对于管道连接的多个命令只要最后一个执行成功则就认为执行成功 # set -o pipefail 则会检查管道连接的所有的命令,只有所有命令都执行成功才算成功 invalid_cmd | echo"true"# 默认该行命令被视为成功执行,设置 pipefail 则被视为失败 # 变量未设置时,默认为空值,引用不会报错 # set -u 让引用未设置的变量立即报错 # set -x 会在执行每条命令前先将其打印出来
#!/bin/bash # 创建临时目录并在脚本执行结束或中断时清理临时目录 # the directory of the script DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # the temp directory used, within $DIR # omit the -p parameter to create a temporal directory in the default location # -t 按指定格式命名文件夹 TMP_DIR=`mktemp -d -p "$DIR" -t test.XXXX` # check if tmp dir was created if [[ ! "$TMP_DIR" || ! -d "$TMP_DIR" ]]; then echo "Could not create temp dir" exit 1 fi # deletes the temp directory function cleanup { rm -rf "$TMP_DIR" echo "Deleted temp working directory $TMP_DIR" } # register the cleanup function to be called on the EXIT signal trap cleanup EXIT # implementation of script starts here ...
error() { local parent_lineno="$1" local message="$2" local code="${3:-1}" if [[ -n "$message" ]] ; then echo"Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}" else echo"Error on or near line ${parent_lineno}; exiting with status ${code}" fi exit"${code}" } trap'error ${LINENO}' ERR # 手动触发方式 error ${LINENO}"the foobar failed" 2
# 另外可以使用 $@ , r.sh 包含如下内容 #!/bin/bash echo"params only 2 : ${@:2:1}" echo"params 2 and 3 : ${@:2:2}" echo"params all from 2: ${@:2:99}" echo"params all from 2: ${@:2}"
# 执行脚本 $ r.sh 1 2 3 4 5 6 7 8 9 10
# 输出 params only 2 : 2 params 2 and 3 : 2 3 params all from 2: 2 3 4 5 6 7 8 9 10 params all from 2: 2 3 4 5 6 7 8 9 10