Alias to 'cd' Command with Subshell Not Working as Expected

我的未来我决定 提交于 2020-01-04 15:13:33

问题


I just learned about aliases in bash. I created one like so:

alias="cd $directory"

where $directory is from use input. In another shell script, I can launch a subshell like so:

( bash )

which brings me to the subshell, where, if I run cd, I go to the alias, cd $directory. This is great and it seems to be working as expected.

What I'm looking for is for when the subshell is launched, the cd happens automatically, so I tried:

( bash | cd )

thinking it would launch the subshell and cd to the user-entered $directorybut it's not working. How can I go about getting this to work? I also tried ( bash -c cd) to no avail.

Thanks.


回答1:


The reason that ( bash | cd ) doesn't work is that each command in a pipeline is run in a separate subshell, so ( bash | cd ) is essentially equivalent to ( ( bash ) | ( cd ) ) (except that the latter launches even more subshells, of course). Instead, you should be able to write:

( cd ; bash )

(which runs cd before running bash) since bash will inherit a copy of the execution environment of the subshell it was launched from.

By the way — are you sure you want to create cd as an alias this way? That seems error-prone and confusing to me. I think it would be better to create a shell function that cds to the user-specified directory:

function cd_user () { cd "$directory" ; }

( cd_user ; bash )


来源:https://stackoverflow.com/questions/9780624/alias-to-cd-command-with-subshell-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!