问题
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 $directory
but 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 cd
s 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