我正在尝试将--
后的所有参数传递给函数。
下面是脚本调用的示例。
$ ./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
据
我了解,您想删除所有位置参数,直到并包括--
:
% 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>
您可以尝试以下脚本来实现要求,
#! /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
在上面的脚本中,值仅使用名为"$CHILD_ARGS"的单个变量进行传递。因此,在函数中,函数参数将划分 w.r.t 空间。