bashshelleval

eval: command not found


I have next script:

a.sh:

if [ $# -eq 1 ]; then
    eval "$@"
else
    eval '"$@"'
fi

b.sh:

echo "para1: $1"
echo "para2: $2"
echo "para3: $3"

When I do next, both with quote or without, they are ok:

$ ./a.sh "./b.sh '1 2' '' 3"
para1: 1 2
para2:
para3: 3
$ ./a.sh ./b.sh '1 2' '' 3
para1: 1 2
para2:
para3: 3

But when I change the command to next, the one which without quote reports error:

$ ./a.sh "A=1 ./b.sh '1 2' '' 3"
para1: 1 2
para2:
para3: 3
$ ./a.sh A=1 ./b.sh '1 2' '' 3
./a.sh: line 4: A=1: command not found

How can I manage it work for both?

Please note: I should let b.sh treat '1 2' as the first parameter, '' as the second, while 3 as the third parameter, this is the reason I add '' around $@ in a.sh.


Solution

  • How can I manage it work for both?

    Just:

    "$@"
    

    No eval no nothing. And then use env to set a variable:

    ./a.sh env A=1 ./b.sh '1 2' '' 3
    

    Or call shell when you want to execute shell, all 3 are equivalent:

    ./a.sh bash -c 'A=1 ./b.sh '\''1 2'\'' '\'\'' 3'
    ./a.sh bash -c "A=1 ./b.sh '1 2' '' 3"
    ./a.sh bash -c 'A=1 "$@"' -- ./b.sh '1 2' '' 3