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.
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:(which runs
cdbefore runningbash) sincebashwill inherit a copy of the execution environment of the subshell it was launched from.By the way — are you sure you want to create
cdas an alias this way? That seems error-prone and confusing to me. I think it would be better to create a shell function thatcds to the user-specified directory: