当前位置: 移动技术网 > 网络运营>服务器>Linux > Shell脚本通过参数名传递参数的实现代码

Shell脚本通过参数名传递参数的实现代码

2020年05月12日  | 移动技术网网络运营  | 我要评论

平常在写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}

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网