问题
I'm trying to execute a command inside a shell script (in my case using sh as my shell) when the command is passed as the first argument to the shell script. Example:
sh command_execute.sh ls -l
Let's say I enter the above on the command line, ideally I would like the script to look at the first argument (which in this case would be ls -l), and execute it.
回答1:
There are two ways you can do this. One way would be to set your shell script as
# File: command_execute.sh
$1
and run it like this: sh command_execute.sh 'ls -l' (notice the single quotes around ls -l). What this will do is the full string ls -l will be passed to your script, and since it is the first argument to the script, $1 in the script will be effectively replaced with ls -l, and then that command will be executed.
The other way would be to use this as your script:
# File: command_execute.sh
"$@"
In this case, "$@" is all the arguments that were passed to the script. If you run the script like sh command_execute.sh ls -l (note in this case the ls -l is not quoted), then ls is passed to the script as argument 1, and -l is passed to the script as argument 2. Then "$@" is effectively replaced with ls -l, and then the command is executed.
Which of these is best depends on your requirements.
来源:https://stackoverflow.com/questions/65226698/execute-a-command-in-bash-script