首页 > 解决方案 > 将参数分配给位置参数

问题描述

我正在调用具有大量参数的 shell 脚本,例如./train-rnn.sh 0 0 0 "63 512". 是否可以将每个参数分配给特定的位置参数?例如

./train-rnn.sh $1=0 $2=0 $4=0 $3="63 512"

标签: bashpositional-parameter

解决方案


Bash 没有这样的机制,但你可以做点什么。

最好的方法是解析脚本中的命令行参数。在这种情况下,您可能希望通过允许表单选项来改善用户体验,option=argument而不是让用户(和开发人员也一样!)记住 、 等的$1含义$2

#! /usr/bin/env bash
declare -A opt
for arg; do
  if [[ "$arg" =~ ^([^=]+)=(.*) ]]; then
    opt["${BASH_REMATCH[1]}"]=${BASH_REMATCH[2]}
  else
    echo "Error: Arguments must be of the form option=..." >&2
    exit 1
  fi
done
# "${opt["abc"]}" is the value of option abc=...
# "${opt[@]}" is an unordered (!) list of all values
# "${!opt[@]}" is an unordered (!) list of all options

示例用法:

script.sh abc=... xyz=...

如果您真的想坚持位置参数,请使用

#! /usr/bin/env bash
param=()
for arg; do
  if [[ "$arg" =~ ^\$([1-9][0-9]*)=(.*) ]]; then
    param[BASH_REMATCH[1]]=${BASH_REMATCH[2]}
  else
    echo "Error: Arguments must be of the form $N=... with N>=1" >&2
    exit 1
  fi
done
if ! [[ "${#param[@]}" = 0 || " ${!param[*]}" == *" ${#param[@]}" ]]; then
  echo "Error: To use $N+1 you have to set $N too" >&2
  exit 1
fi
set -- "${param[@]}"
# rest of the script
# "$@" / $1,$2,... are now set accordingly

示例用法:

script.sh $1=... $3=... $2=...

如果您的脚本/程序无法修改,上述方法也可以用作包装器。为此,请替换set -- "${param[@]}"exec program "${param[@]}",然后使用wrapper.sh $1=... $3=... $2=....


推荐阅读