将“whereis”命令的输出传递给“cd”以一步更改目录

Vic*_*Dev 4 command-line bash cd-command command-substitution

我找不到whereiscd命令的输出传递给同一行中的命令的方法,因此我不必cd在第二步中执行此操作。

我试过像下面这样传递:

cd $(whereis node_modules)
Run Code Online (Sandbox Code Playgroud)

或者

cd "`dirname $(whereis node_modules)`"
Run Code Online (Sandbox Code Playgroud)

cd "$(whereis node_modules)"
Run Code Online (Sandbox Code Playgroud)

但上述方法均无效。

有人能找到上面代码中应该有什么问题吗?

Dop*_*oti 6

这似乎可以解决问题:

cd "$(dirname "$(whereis node_modules)")"
Run Code Online (Sandbox Code Playgroud)

如果根据您的评论,您想进入目标(如果它是一个目录):

location=$(whereis node_modules)
if [[ -d "$location" ]]; then
    cd "$location"
else
    cd "$(dirname "$location" )"
fi
Run Code Online (Sandbox Code Playgroud)

上述内容可以很容易地在您的.bash_profile.


Rah*_*hul 5

你可以这样做,

cd "`which node_modules`"
Run Code Online (Sandbox Code Playgroud)

随着dirname获得的目录:

cd "$(dirname "$(which node_modules)" )"
Run Code Online (Sandbox Code Playgroud)

正如您在评论中提到的,我希望在一个步骤中执行此操作并假设nod_module是一个目录,因此您可以使用以下命令执行此操作:

cd $(whereis node_modules | cut -d ' ' -f2)
Run Code Online (Sandbox Code Playgroud)

(请注意,后一个命令假定使用的是 Linux whereis,而不是 BSD,并且路径不包含任何空格。)

正如@Dani_I 所建议的,你可以看看这个Why not use "which"?那用什么?,这可能更有用。

  • @Rahul 是的,我希望安装了`which`。我没有安装 node_modules 但我尝试了你的 firefox 命令:`cd $(which firefox | xargs dirname)` __并且它工作正常__。当我用一个错误的名字尝试它时,说 `cd $(which firefoxx | xargs dirname)` 然后它返回 `missing operation`,这与 VickyDev 报告的错误相同。 (2认同)
  • 你应该用 `command -v` 替换 `which` 并查看 http://unix.stackexchange.com/questions/85249/why-not-use-which-what-to-use-then (2认同)