Execute a command in bash script [closed]

筅森魡賤 提交于 2021-01-07 06:31:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!