将bash参数的子序列传递给函数

时间:2016-06-02 07:03:43

标签: bash

我试图将--之后的所有参数传递给函数。

以下是脚本的示例调用。

$ ./myscript.sh exec -- run "Hello  World"
Arg 1 run
Arg 2 Hello  World

如何修改所需输出的myscript.sh(下方)?

#! /bin/bash

f () {
  echo Arg 1 "$1"
  echo Arg 2 "$2"
}

ARGS=
CHILD_ARGS=

# Look to see if we want to pass args through to a script
for ((ARGS_POS=1 ; ARGS_POS <= $# ; ARGS_POS++)); do
  if [[ "--" == ${!ARGS_POS} ]]; then
    ((ARGS_POS++))

    CHILD_ARGS=${@:$ARGS_POS}
    ARGS=${@:1:$((ARGS_POS-2))}
    break
  fi
done

# Do something $ARGS

# Run the child
f $CHILD_ARGS

2 个答案:

答案 0 :(得分:1)

据我了解,您希望删除所有位置参数,包括--

% cat myscript.bash
#!/bin/bash
while [ -n "$1" ] && [ "$1" != "--" ]; do :
  shift
done
shift
printf "<%s>\n" "$@"

测试:

% ./myscript.bash exec -- run 'hello world'
<run>
<hello world>
% ./myscript.bash 1 2 3
<>
% ./myscript.bash 'hello world' -- 'john doe'
<john doe>

这也可以通过任何阵列来完成,两者都更加繁琐:

#!/bin/bash
arr=("$@")
i=0
while [ "${#arr[@]}" -gt 0 ] && [ "${arr[$i]}" != "--" ]; do :
  unset arr[$i]
  ((i+=1))
done
unset arr[$i]
printf "<%s>\n" "${arr[@]}"
printf -- "--------\n"
printf "<%s>\n" "$@"

测试:

./myscript.bash john doe -- 'hello world' a b
<hello world>
<a>
<b>
--------
<john>
<doe>
<-->
<hello world>
<a>
<b>

答案 1 :(得分:0)

您可以尝试使用以下脚本来实现此要求,

    #! /bin/bash

    f () {
      echo Arg 1 "$1"
      echo Arg 2 "$2 $3"
    }

    ARGS=
    CHILD_ARGS=

    # Look to see if we want to pass args through to a script
    for ((ARGS_POS=1 ; ARGS_POS <= $# ; ARGS_POS++)); do
      if [[ "--" == ${!ARGS_POS} ]]; then
        CHILD_ARGS=${@:$ARGS_POS+1}
        ARGS=${@:1:$((ARGS_POS-2))}
        break
      fi
    done

    # Do something $ARGS

    # Run the child
    f $CHILD_ARGS

在上面的脚本中,值只使用一个名为&#34; $ CHILD_ARGS&#34;的变量传递。因此,在函数中,函数参数将划分w.r.t空间。