从命令的结果更改目录

Changing directory from the result of a command

根据命令的输出,我在 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)来改变。

感谢任何对问题的解释或提前帮助。

波浪号扩展在引号中不起作用,通常应在脚本中避免使用。它仅供交互使用。来自 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/')"