Bash:使用命令作为参数(特别是cd,dirname和find)

six*_*ude 2 unix parameters bash cd find

这个命令和输出:

% find . -name file.xml 2> /dev/null
./a/d/file.xml
%
Run Code Online (Sandbox Code Playgroud)

所以这个命令和输出:

% dirname `find . -name file.xml 2> /dev/null`
./a/d
%
Run Code Online (Sandbox Code Playgroud)

所以你会期望这个命令:

% cd `dirname `find . -name file.xml 2> /dev/null``
Run Code Online (Sandbox Code Playgroud)

将当前目录更改为./a/d.奇怪的是,这不起作用.当我输入cd ./a/d.目录更改有效.但是我不明白为什么以上不起作用......

for*_*ran 10

刚刚注意到反引号......请改用它:

cd $(dirname $(find . -name file.xml 2> /dev/null))
Run Code Online (Sandbox Code Playgroud)

编辑:引用的参数(如果它们包含空格):

cd "$(dirname "$(find . -name file.xml 2> /dev/null)")"
Run Code Online (Sandbox Code Playgroud)


gho*_*g74 5

你也可以使用find的选项-execdir

   -execdir command {} +
          Like  -exec,  but  the  specified  command  is run from the subdirectory containing the matched file, ....
Run Code Online (Sandbox Code Playgroud)

所以没有必要cd