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}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持安科网。

相关推荐