简体   繁体   中英

Running a shell command from a variable in a shell script

I am programming a game using Linux.

I have shell script:

//run.sh    
A="string1"
B="string2"
C="string3"

COMMAND_LINE="python ../file.py \"$A\" \"$B\" --flag1 ../file.txt --flag2 $C"
echo "$COMMAND_LINE"
$COMMAND_LINE

//note the ' \\" ' are intentionally

I want shell to run the command in COMMAND_LINE. for some reason the command does not work, but if i take the string that was created and stored in COMMAND_LINE(the string that was echoed) and run it through the shell, the program works fine.

any suggestions?

Thank You

The embedded quotes in COMMAND_LINE are treated as literal characters; they do not quote the value of $A when $COMMAND_LINE is expanded. There really isn't a good, safe way to execute the value of a variable as a command in a POSIX shell.

If you are using bash or another shell that supports arrays, you can try

options=( ../file.py "$A" "$B" --flag1 ../file.txt --flag2 $C )
echo "python ${options[@]}"
python "${options[@]}"

You'd pretty much have to use one of:

eval $COMMAND_LINE
sh -c "$COMMAND_LINE"

but in general, that's a fraught and dangerous process. If you're in charge of the complete string in $COMMAND_LINE (no input from the user), and with the values shown, it is safe enough. If the user can introduce their own shell script notation into any of the variables ( $A , $B or $C , for example), then you are in for a world of hurt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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