Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alias an export in bash

Tags:

alias

bash

export

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 file or directory

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

Thanks

like image 334
Sreeram Ravinoothala Avatar asked Oct 12 '11 23:10

Sreeram Ravinoothala


Video Answer


2 Answers

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"
like image 62
Keith Avatar answered Nov 03 '22 05:11

Keith


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'
like image 32
chown Avatar answered Nov 03 '22 07:11

chown