开发者

How to alias an export in bash

I am trying to set an env variable which I can use to do relative directory chains. I am trying to do it the following way but cant get it to work. How do I do it?

alias sroot="export SROOT="$PWD""
alias drumit="cd $SROOT/abc/def/drumit"

If I type sroot, it takes the alias but when i type drumit, it gives me an error saying

bash: cd: /abc/def/drumit: No such f开发者_StackOverflow社区ile or directory

Looks like when the shell was launched it takes $SROOT as . Appreciate any help.

Thanks


Your $PWD and $SROOT variables are being expanded at the time you define the aliases, not when you are using them. Put a \ in front of them to escape them while they are defined.

alias sroot="export SROOT="\$PWD""
alias drumit="cd \$SROOT/abc/def/drumit"


When you initially set the alias, it expands $PWD instead of keeping it as the variable form. Try using function instead like this:

$ function sroot {
> export SROOT="$PWD"
> }
$ export -f sroot
$ function drumit {
> cd $SROOT/cron
> }
$ export -f drumit
$ declare -f sroot
sroot()
{ 
    export SROOT="$PWD"
}
$ declare -f drumit
drumit ()
{
    cd $SROOT/abc/def/drumit
}

This is what is currently happening when you alias like in your question (variable expanding):

$ alias sroot="export SROOT="$PWD""
$ alias drumit="cd $SROOT/abc/def/drumit"
$ alias
alias SROOT='/home/jon'
alias drumit='cd /home/jon/abc/def/drumit'
alias sroot='export SROOT=/home/jon'

Escaping would work too:

$ alias sroot="export SROOT="\$PWD""
$ alias drumit="cd \$SROOT/abc/def/drumit"
$ alias
alias drumit='cd $SROOT/abc/def/drumit'
alias sroot='export SROOT=$PWD'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜