1

I need to triggeer a bash passing parameter with a format [ variable_name="value" ] like this:

./test.sh ip='164.130.21.98' hostname='whatever' pwd='/test' ftpcmd='CWD debug' user='stefano'

On test.sh script I want to assign to any variable the relevant value:

#!/bin/bash
eval `echo "$@"`
echo $ftpcmd

But I get a prova: command not found error.

I cannot understand what's wrong on my ftpcmd='CWD debug' parameter neither how I should write it instead.

If I try to replace eval with declare then the $ftpcmd is set only to CWD instead of CWD debug as I'm expecting.

  • 2
    don't reinvent the wheel. option parsing was done years ago. use getopts (bash built-in, short single-letter options only) or /usr/bin/getopt (from util-linux, supports both short and --long options) – cas Oct 2 '15 at 10:39
  • 1
    see: unix.stackexchange.com/questions/62950/… – cas Oct 2 '15 at 10:44
  • @cas you're right. As I wrote I've still many things to learn on bash scripting. – Stefano Radaelli Oct 2 '15 at 10:57
2

If you put the assignments before the script

ip='164.130.21.98' hostname='whatever' pwd='/test' ftpcmd='CWD debug' user='stefano' ./test.sh 

the variables are available in the script's environment. The -k option treats all assignments, not just pre-command assignments, as environment modifications.

set -k
./test.sh ip='164.130.21.98' hostname='whatever' pwd='/test' ftpcmd='CWD debug' user='stefano'
set +k

In either case, eval is not required at all and can be removed.

  • In such case your suggestion is to have to to a parent shell that runs test.sh. Am I right? – Stefano Radaelli Oct 2 '15 at 15:50
  • For the first example (x=1 y="abc" ./cmd.sh), no, you are simply reordering the command. – michael Oct 3 '15 at 13:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.