在bash脚本中将“flags”与“arguments”分开

时间:2017-07-31 16:49:30

标签: linux bash shell scripting

我正在使用遗留的shell脚本,该脚本用于测试二进制文件中的某些功能(即调用nmobjdumpldd等;并对结果进行一些解析)。 shell脚本目前非常“敏感”,而且很大,所以我想尽量减少对它所做的更改。

目前首先检查参数的数量,每个参数都是一个路径,即:

if [ "$#" -lt 3 ]
then
  echo "Error. Invalid number of arguments."
  exit
fi

我想添加一些额外的参数及其长形式等价来禁用脚本内部的某些功能,而不会使上述测试无效,即:

-h | --help: Print shell usage and expected arguments.
-x | --xfer: Do some extra copy logic.
-d | --dry:  Do a dry-run, and don't actually change any files.

但是,我不希望将标志(即以连字符开头的参数)计为参数(即不影响将参数分配给$1$2和{ {1}})。例如,以下是我的脚本的有效调用:

$3

我希望以下可能的调用也能正常工作:

bash ./test.sh ./ ./out ./logs

如何设置脚本以“过滤”以连字符(一个或两个)开头的参数,并保持对bash ./test.sh ./ ./out ./logs --dry bash ./test.sh --xfer ./ ./out ./logs bash ./test.sh --help bash ./test.sh ./ --xfer ./out --dry ./logs $1$2的相同分配?

1 个答案:

答案 0 :(得分:3)

您可以在事后修改参数列表:

set -- one two three

因此,您可以将自己的解析放在顶部,并使用set --将您想要的任何参数放入所需的位置。

考虑作为过滤的一个例子:

#!/usr/bin/env bash
#              ^^^^- not /bin/sh, as arrays are bash-only

help_and_exit() {
  local retval=${1:-1}
  cat <<EOF
${0##*/} [-d|--dry-run] [-x|--xfer] input output whatever

...put your extended help here...
EOF
  exit "$retval"
}

args=( )
dry_run=0; xfer=0
while (( $# )); do
  case $1 in
    -d|--dry)  dry_run=1 ;;
    -x|--xfer) xfer=1 ;;
    -h|--help) help_and_exit 0 ;;
    -*)        printf 'Unknown option: %q\n\n' "$1"
               help_and_exit 1 ;;
    *)         args+=( "$1" ) ;;
  esac
  shift
done
set -- "${args[@]}"
相关问题