从命令结果更改目录[重复]

问题描述 投票:0回答:1

在给定命令输出的情况下,我遇到了让cd更改目录的问题。

例如,以下内容不起作用:

# should be equivalent to "cd ~"
cd $(echo "~")
# should be equivalent to "cd ~/go"
cd $(echo "~/go")

两者都返回错误,如

cd: no such file or directory: ~
cd: no such file or directory: ~/go

但是,我可以指定绝对路径,例如

cd $(echo "/Users/olly")

这将成功将目录更改为该位置。更重要的是,如果我省略引号它将起作用。

cd $(echo ~)

目前,我有一个程序,jump-config,它将打印到终端的路径的字符串。

jump-config
// prints ~/go/src/gitlab.com/ollybritton/jump/jump-config

我正在尝试做

cd $(jump-config)

但是我收到了错误

cd: no such file or directory: ~/go/src/gitlab.com/ollybritton/jump/jump-config

我很乐意做cd $JUMP_CONFIG,但是,程序的输出不是固定的,我需要cd $(jump-config)来改变。

我很感激对此问题的任何解释或提前帮助。

bash echo cd
1个回答
1
投票

Tilde扩展在引号中不起作用,并且通常应该在脚本中避免。它仅供交互式使用。来自man bash/ *Tilde Expansion

If a word begins with an unquoted tilde character (`~'), all of the characters preceding the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible login name. If this login name is the null string, the tilde is replaced with the value of the shell parameter HOME. If HOME is unset, the home directory of the user executing the shell is substituted instead. Otherwise, the tilde-prefix is replaced with the home directory associated with the specified login name.

是否有可能修改jump-config输出$HOME代替~?如果没有,您可以尝试以下选项之一:

jump_config=$(jump-config); cd "${jump_config//\~/$HOME}"

要么

cd "$(jump-config |sed 's/~/$HOME/')"
© www.soinside.com 2019 - 2024. All rights reserved.