Get some common variables:
# 获取当前脚本所在目录
SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
# 获取当前脚本的文件名
SCRIPT_NAME=$( basename "$0" )
# 在 $DIR 中搜索第一个 jar 文件的名字
JAR_FILE=$(find $DIR -maxdepth 1 -type f -name "*.jar" | head -1)
Some common judgments:
# 判断变量是否为空
if [ -z "$VAR" ]; then
echo "\$VAR is empty"
else
echo "\$VAR is $VAR"
fi
# 判断路径是否存在
# -d 表示目录,-f 表示文件
if [ -d "$PATH" ]; then
echo "File $PATH exists"
else
echo "File $PATH not found"
fi
# 判断当前用户是否是 root
if [ "${EUID:-$(id -u)}" -eq 0 ]; then
do_root_stuff
fi
# 判断 docker 命令能否执行
if ! command -v docker &> /dev/null; then
echo "当前系统不能运行 docker 命令"
fi
Search process ID based on keywords in process start command
# set pid=$(get_pid "some-service-name")
get_pid() {
SERVICE_NAME=$1
PID=$(ps aux | grep "[${SERVICE_NAME:0:1}]${SERVICE_NAME:1}" | awk '{print $2}')
echo "$PID"
}
Generic way to parse and query command line arguments
This script is very useful, you just need to add the following at the beginning of your script to parse the parameters in the format --param value
Since this script is written as short as possible and does not take up space, the format requires all parameters to have values. For example, --daemon
--daemon true
must be passed.
### 解析命令行参数
PARAMS_ARR=()
while (( "$#" )); do
case "$1" in --*) PARAMS_ARR+=($1); shift;; *) PARAMS_ARR[-1]="${PARAMS_ARR[-1]} $1"; shift;; esac
done
### 获取命令行参数,如果没有则返回默认值
### 示例:value=$(get_param "param_name" "default_value")
function get_param {
for param in "${PARAMS_ARR[@]}"; do if [[ $param =~ "--$1" ]]; then echo ${param#"--$1"} && return 0; fi done
echo $2
}
### 获取命令行参数,如果没有则报错退出(退出机制需要 set -e 来开启,否则你就要自行处理返回值)
### 示例:value=$(get_param_required "param_name")
function get_param_required {
for param in "${PARAMS_ARR[@]}"; do if [[ $param =~ "--$1" ]]; then echo ${param#"--$1"} && return 0; fi done
echo -e "\e[31mParameter '$1' is required\e[m" >&2 && return 1
}
set -e
Parse the parameter value as an array from the above script
If the parameter value is more than one, it can be extracted into an array with the following statement:
# 假设要提取名为 PARAM_NAME 的参数值赋给数组 ARR,可以用下面一行
IFS=', ' read -r -a ARR <<< $(get_param PARAM_NAME)
# 这里多个参数值可以用逗号或空格隔开,例如 "--values a,b, c d",
# 解析出来的数组元素不会包含空白字符
# 检查解析结果
echo "ARR size: ${#ARR[@]}"
echo "ARR content: ${ARR[@]}"
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。