Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何从getopts获取2个参数_Bash_Shell_Getopts - Fatal编程技术网

Bash 如何从getopts获取2个参数

Bash 如何从getopts获取2个参数,bash,shell,getopts,Bash,Shell,Getopts,我正在创建一个bash脚本,该脚本将从命令行从用户获取两个参数。但我不确定如何从用户处获取2个参数,如果未传递,这两个参数都是必需的,将显示错误并从脚本返回。下面是我用来获取用户参数的代码,但目前我的getopts只获取一个参数 optspec="h-:" while getopts "$optspec" optchar; do case "${optchar}" in -) case "$OPTARG" in file) displa

我正在创建一个bash脚本,该脚本将从命令行从用户获取两个参数。但我不确定如何从用户处获取2个参数,如果未传递,这两个参数都是必需的,将显示错误并从脚本返回。下面是我用来获取用户参数的代码,但目前我的getopts只获取一个参数

optspec="h-:"
while getopts "$optspec" optchar; do
  case "${optchar}" in
    -)
      case "$OPTARG" in
        file)
          display_usage ;;
        file=*)
          INPUTFILE=${OPTARG#*=};;
      esac;;
    h|*) display_usage;;
  esac
done
如何添加一个选项以从命令行获取更多参数。如下

script.sh --file="abc" --date="dd/mm/yyyy"

getopts
不支持长参数。它只支持单字母参数

你可以用。它的可用性不如来自posix且随处可见的
getopts
getopt
肯定可以在任何linux上使用,而不仅仅是在linux上。在linux上,它是
linux-utils
的一部分,这是一组最基本的实用程序,如
mount
swapon

典型的
getopt
用法如下:

if ! args=$(getopt -n "your_script_name" -oh -l file:,date: -- "$@"); then
    echo "Error parsing arguments" >&2
    exit 1
fi
# getopt parses `"$@"` arguments and generates a nice looking string
# getopt .... -- arg1 --file=file arg2 --date=date arg3
# would output:
# --file file --date date -- arg1 arg2 arg3
# the idea is to re-read bash arguments using `eval set`
eval set -- "$args"
while (($#)); do
   case "$1" in
   -h) echo "help"; exit; ;;
   --file) file="$2"; shift; ;;
   --date) date="$2"; shift; ;;
   --) shift; break; ;;
   *) echo "Internal error - programmer made an error with this while or case" >&2; exit 1; ;;
   esac
   shift
done

echo file="$file" date="$date"
echo Rest of arguments: "$@"

@chepner我想做一些像这样的事情。sh--file=“abc”--date=“dd/mm/yyyy”
getopts
也不做长选项。如果两个参数都是必需的,不要让它们成为选项(从
-
开始),让它们成为位置参数。@chepner您能建议我们如何从getoptt执行它吗?为什么使用这个语法?您可以编写零代码并以
file=abc date=dd/mm/yy script.sh
的形式调用脚本。如果要分析参数,请调用脚本作为
script.sh file=abc date=dd/mm/yy
。额外的
--
不提供任何附加值。