bash bash脚本更改目录并使用参数执行命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8369411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:16:57  来源:igfitidea点击:

bash script to change directory and execute command with arguments

bash

提问by frodo

I am trying to do the following task: write a shell script called changedirwhich takes a directory name, a command name and (optionally) some additional arguments. The script will then change into the directory indicated, and executes the command indicated with the arguments provided.

我正在尝试执行以下任务:编写一个名为的 shell 脚本changedir,它接受一个目录名、一个命令名和(可选)一些附加参数。然后脚本将切换到指定的目录,并执行使用提供的参数指定的命令。

Here an example:

这里有一个例子:

$ sh changedir /etc ls -al

This should change into the /etcdirectory and run the command ls -al.

这应该更改为/etc目录并运行命令ls -al

So far I have:

到目前为止,我有:

#!/bin/sh
directory=; shift
command=; shift
args=; shift
cd $directory
$command

If I run the above like sh changedir /etc lsit changes and lists the directory. But if I add arguments to the lsit does not work. What do I need to do to correct it?

如果我像上面一样运行sh changedir /etc ls它会更改并列出目录。但是如果我向ls它添加参数,它就不起作用。我需要做什么来纠正它?

回答by CB Bailey

You seemed to be ignoring the remainder of the arguments to your command.

您似乎忽略了命令的其余参数。

If I understand correctly you need to do something like this:

如果我理解正确,你需要做这样的事情:

#!/bin/sh
cd ""         # change to directory specified by arg 1
shift           # drop arg 1
cmd=""        # grab command from next argument
shift           # drop next argument
"$cmd" "$@"     # expand remaining arguments, retaining original word separations

A simpler and safer variant would be:

一个更简单、更安全的变体是:

#!/bin/sh
cd "" && shift && "$@"

回答by dgasper

Since there can probably be more than a single argument to a command, i would recommend using quotation marks. Something like this:

由于命令的参数可能不止一个,我建议使用引号。像这样的东西:

sh changedir.sh /etc "ls -lsah"

Your code would be much more readable if you ommited the 'shift':

如果您省略“shift”,您的代码将更具可读性:

directory=;
command=;
cd $directory
$command

or simply

或者干脆

cd DIRECTORY_HERE; COMMAND_WITH_ARGS_HERE