Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash or-equals ||= like Ruby

Does Bash have something like ||= ?

I.e., is there a better way to do the following:

if [ -z $PWD ]; then PWD=`pwd`; fi

I'm asking because I get this error:

$ echo ${`pwd`/$HOME/'~'}
-bash: ${`pwd`/$HOME/'~'}: bad substitution

So, my plan is to do:

if [ -z $PWD ]; then PWD=`pwd`; fi
echo ${PWD/$HOME/'~'}

My real question is: "Is there a better way to do the following?"

# ~/.bash_profile

# Set prompt to RVM gemset, abbr. of current directory & (git branch).
PROMPT_COMMAND='CUR_DIR=`pwd|sed -e "s!$HOME!~!"|sed -E "s!([^/])[^/]+/!\1/!g"`'
PS1='$(~/.rvm/bin/rvm-prompt g) [$CUR_DIR$(__git_ps1)]\$ '
like image 923
ma11hew28 Avatar asked Jul 28 '11 13:07

ma11hew28


3 Answers

Bash allows for default values:

a=${b-`pwd`}

If $b is undefined, then pwd is used instead in assigning $a.

like image 94
Manny D Avatar answered Nov 20 '22 01:11

Manny D


You can set your prompt to be the working directory with this:

PS1='\w '   # Using \W will provide just basename
like image 21
grok12 Avatar answered Nov 20 '22 02:11

grok12


Another solution (which is more akin to Ruby's or-equals in my opinion) would be:

[ -n $PWD ] || PWD=`pwd`
like image 2
user456584 Avatar answered Nov 20 '22 02:11

user456584