在 bash 脚本中执行命令 [英] Execute a command in bash script
问题描述
当命令作为第一个参数传递给 shell 脚本时,我试图在 shell 脚本中执行命令(在我的情况下使用 sh
作为我的 shell).示例:
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
假设我在命令行中输入了上述内容,理想情况下我希望脚本查看第一个参数(在本例中为 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.
推荐答案
有两种方法可以做到这一点.一种方法是将您的 shell 脚本设置为
There are two ways you can do this. One way would be to set your shell script as
# File: command_execute.sh
$1
并像这样运行它:sh command_execute.sh 'ls -l'
(注意ls -l
周围的单引号).这将做的是将完整的字符串 ls -l
传递给您的脚本,并且由于它是脚本的第一个参数,因此脚本中的 $1
将有效替换为 ls -l
,然后该命令将被执行.
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
"$@"
在这种情况下,"$@"
是传递给脚本的所有参数.如果你运行像 sh command_execute.sh ls -l
这样的脚本(注意在这种情况下 ls -l
not 被引用),那么 ls
作为参数 1 传递给脚本,-l
作为参数 2 传递给脚本.然后 "$@"
是有效地替换为ls -l
,然后执行命令.
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.
这篇关于在 bash 脚本中执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!