从脚本和命令行调用bash脚本参数解析时会有所不同



我试图从另一个脚本调用一个脚本,但命令行参数的解析不正确。这是bug还是我遗漏了什么?test.sh

#!/bin/bash
set -o errexit
set -o nounset
set -x
while test $# -gt 0; do
case "$1" in 
-n) shift
name=$1
shift
;;
-s)
shift
ssh_options=$1
shift
;;
*)
echo "see --help"
exit 1
;;
esac
done
$ssh_cmd="${ssh_options}"
echo "${name} ssh_options=${ssh_options}"

call_test.sh

#!/bin/bash
set -x
cmd=$'./test.sh -n foo -s "-foo -bar -F"'
$($cmd)
echo done
#output
./test.sh -n foo -s "-foo -bar -F"
+ test 4 -gt 0
+ case "$1" in
+ shift
+ name=foo
+ shift
+ test 2 -gt 0
+ case "$1" in
+ shift
+ ssh_options='-foo -bar -F'
+ shift
+ test 0 -gt 0
+ echo 'foo ssh_options=-foo -bar -F'
foo ssh_options=-foo -bar -F

./call_test.sh
+ cmd='./test.sh -n foo -s "-foo -bar -F"'
++ ./test.sh -n foo -s '"-foo' -bar '-F"'
+ test 6 -gt 0
+ case "$1" in
+ shift
+ name=foo
+ shift
+ test 4 -gt 0
+ case "$1" in
+ shift
+ ssh_options='"-foo'
+ shift
+ test 2 -gt 0
+ case "$1" in
+ echo 'see --help'
+ exit 1
+ see --help
./call_test.sh: line 5: see: command not found
+ echo done
done

感谢您的帮助。

$ssh_cmd="${ssh_options}"不是您想要的。当分配时,不要在变量上使用$

养成将错误贯穿始终的习惯https://www.shellcheck.net/-

Line 26:
$ssh_cmd="${ssh_options}"
^-- SC2281: Don't use $ on the left side of assignments.
^-- SC2154: ssh_cmd is referenced but not assigned.
Did you mean: (apply this, apply all SC2281)
ssh_cmd="${ssh_options}"

编辑并重新测试。

相关内容

最新更新