问题描述
我刚刚得知在bash别名。我创建了一个像这样:
I just learned about aliases in bash. I created one like so:
别名为CD $目录
其中, $目录
是使用的输入。在另一个shell脚本,我可以启动一个子shell像这样:
where $directory
is from use input. In another shell script, I can launch a subshell like so:
(庆典)
这使我到子shell,在那里,如果我跑 CD
,我去了别名, CD $目录
。这是伟大的,它似乎是按预期工作。
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.
我要找的是当子shell启动时,CD自动发生,所以我尝试:
What I'm looking for is for when the subshell is launched, the cd happens automatically, so I tried:
(庆典| CD)
以为这将启动子shell和CD的用户输入 $目录
,但它不工作。我该如何去获得这个工作?我也试过(bash的-c 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.
感谢。
推荐答案
之所以(庆典| CD)
不工作是管道中的每个命令在一个单独的子shell中运行,因此(庆典| CD)
基本上等同于((庆典)|(CD))
(但后者甚至推出的更多的子shell,当然)。相反,你应该能够写:
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 )
(运行 CD
的前的运行庆典
),因为庆典
将继承它从启动子shell的执行环境的一个副本。
(which runs cd
before running bash
) since bash
will inherit a copy of the execution environment of the subshell it was launched from.
顺便说一句—你确定你想要创建 CD
作为别名这种方式?这似乎容易出错和混乱给我。我认为这将是更好地创建 CD
s到用户指定的目录下的shell函数:
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 )
这篇关于按预期别名“CD”与子shell不工作命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!