bash 从脚本和命令行调用时,脚本参数解析不同
bash script arguments parsing differ when called from script and from command line
我正在尝试从另一个脚本调用一个脚本,但命令行参数解析不正确。这是一些错误还是我遗漏了什么?
test.sh
#!/bin/bash
set -o errexit
set -o nounset
set -x
while test $# -gt 0; do
case "" in
-n) shift
name=
shift
;;
-s)
shift
ssh_options=
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 "" in
+ shift
+ name=foo
+ shift
+ test 2 -gt 0
+ case "" 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 "" in
+ shift
+ name=foo
+ shift
+ test 4 -gt 0
+ case "" in
+ shift
+ ssh_options='"-foo'
+ shift
+ test 2 -gt 0
+ case "" 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}"
再次编辑并测试。
我正在尝试从另一个脚本调用一个脚本,但命令行参数解析不正确。这是一些错误还是我遗漏了什么?
test.sh
#!/bin/bash
set -o errexit
set -o nounset
set -x
while test $# -gt 0; do
case "" in
-n) shift
name=
shift
;;
-s)
shift
ssh_options=
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 "" in
+ shift
+ name=foo
+ shift
+ test 2 -gt 0
+ case "" 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 "" in
+ shift
+ name=foo
+ shift
+ test 4 -gt 0
+ case "" in
+ shift
+ ssh_options='"-foo'
+ shift
+ test 2 -gt 0
+ case "" 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}"
再次编辑并测试。