Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
bash脚本以更改目录并使用参数执行命令_Bash - Fatal编程技术网

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

bash脚本以更改目录并使用参数执行命令,bash,Bash,我正在尝试执行以下任务: 编写一个名为changedir的shell脚本 接受目录名、命令名和(可选)一些附加参数。 然后,脚本将更改为指定的目录,并且 执行用提供的参数指示的命令 这里有一个例子: $ sh changedir /etc ls -al 这应更改为/etc目录,并运行命令ls-al 到目前为止,我已经: #!/bin/sh directory=$1; shift command=$1; shift args=$1; shift cd $directory $command 如

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

这里有一个例子:

$ sh changedir /etc ls -al
这应更改为
/etc
目录,并运行命令
ls-al

到目前为止,我已经:

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

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

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

如果我理解正确,您需要这样做:

#!/bin/sh
cd "$1"         # change to directory specified by arg 1
shift           # drop arg 1
cmd="$1"        # grab command from next argument
shift           # drop next argument
"$cmd" "$@"     # expand remaining arguments, retaining original word separations
sh changedir.sh /etc "ls -lsah"
一种更简单、更安全的变体是:

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

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

#!/bin/sh
cd "$1"         # change to directory specified by arg 1
shift           # drop arg 1
cmd="$1"        # grab command from next argument
shift           # drop next argument
"$cmd" "$@"     # expand remaining arguments, retaining original word separations
sh changedir.sh /etc "ls -lsah"
如果您使用“shift”,代码的可读性会更高:

directory=$1;
command=$2;
cd $directory
$command
或者干脆

cd DIRECTORY_HERE; COMMAND_WITH_ARGS_HERE

谢谢Charles…我将上面的最后一行改为“$cmd”“$@”,使“参数”成为命令的可选选项,即如果我运行“/changedir/etc/ls”,它将正常工作,“/indir/etc/ls-al”也将正常工作,对吗ok@frodo:是的,你说得对<代码>“$@”更好,因为它在传递参数时保留参数。这是我的意思,但不是我写的@查尔斯·贝利(Charles Bailey)的方法更清晰地处理参数。的确,处理更复杂的命令可能会很麻烦,但对于这里提到的简单情况,它应该足够了。目录部分和命令部分是什么也更清楚,因为参数实际上属于命令,它们本身没有任何意义。