繁体   English   中英

bash 脚本 arguments 从脚本和命令行调用时解析不同

[英]bash script arguments parsing differ when called from script and from command line

我正在尝试从另一个脚本调用脚本,并且命令行 arguments 被错误地解析。 这是一些错误还是我错过了什么? 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}"

再次编辑和测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM