Shell脚本通过参数名传递参数

平常在写shell脚本都是用$1,$2…这种方式来接收参数,然而这种接收参数的方式不但容易忘记且不易于理解和维护。Linux常用的命令都可指定参数名和参数值,然而我们怎样才能给自己的shell脚本也采用参数名和参数值这样的方式来获取参数值呢?而不是通过$1,$2这种方式进行获取。下面的例子定义了短参数名和长参数名两种获取参数值的方式。其实是根据getopt提供的特性进行整理而来。

#!/bin/bash
while getopts i:o:p:s:t: OPT; do
  case ${OPT} in
    i) in_file=${OPTARG}
       ;;
    o) out_dir=${OPTARG}
       ;;
    p) product_code=${OPTARG}
       ;;
    s) software_version=${OPTARG}
       ;;
    t) type=${OPTARG}
       ;;
    \?)
       printf "[Usage] `date '+%F %T'` -i <INPUT_FILE> -o <OUTPUT_DIR> -o <P
RODUCT_CODE> -s <SOFTWARE_VERSION> -t <TYPE>\n" >&2
       exit 1
  esac
done

# check parameter
if [ -z "${in_file}" -o -z "${out_dir}" -o -z "${product_code}"  -o -z "${software_version}"  -o -z "${type}" ]; then
    printf "[ERROR] `date '+%F %T'` following parameters is empty:\n-i=${in_file}\n-o=${out_dir}\n-p=${product_code}\n-s=${software_version}\n-t=${type}\n"
    exit 1
fi

# block enc
java -jar openailab-command-line-auth-0.1-SNAPSHOT.jar ${in_file} ${out_dir} ${product_code} ${software_version} ${type}

到此Shell脚本通过参数名传递参数介绍完成。

发布了371 篇原创文章 · 获赞 417 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/qq_19734597/article/details/104199928