1

I am trying to call a script from another script and the command line arguments are being parsed incorrectly. Is this some bug or am I missing something? 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

Any help is appreciated.

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36
J Doe
  • 13
  • 5
  • @KamilCuk Remade with reproducible example – J Doe Apr 13 '21 at 12:31
  • Neither of these are zsh. Editing - – Paul Hodges Apr 13 '21 at 13:54
  • 1
    Also - peek at [I'm trying to put a command in a variable, but the complex cases always fail!](https://mywiki.wooledge.org/BashFAQ/050) – Paul Hodges Apr 13 '21 at 13:57
  • See ["Why does shell ignore quoting characters in arguments passed to it through variables?"](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quoting-characters-in-arguments-passed-to-it-through-varia) and ["How to store a command in a variable in a shell script?"](https://stackoverflow.com/questions/5615717/how-to-store-a-command-in-a-variable-in-a-shell-script) – Gordon Davisson Apr 13 '21 at 16:34

1 Answers1

0

$ssh_cmd="${ssh_options}" is NOT what you want. Don't use $ on a variable when assigning.

Make a habit of running errors through 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}"

Edit and test again.

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36
  • 1
    the `ssh_cmd` was a remnant from some previous attempts. Didn't do anything impactful. However the page you linked was god sent. I was way off base with the way i was building arguments. Thanks. – J Doe Apr 13 '21 at 15:12