Search code examples
bashcommand-promptpwdstring-substitution

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)]\$ '

Solution

  • Bash allows for default values:

    a=${b-`pwd`}
    

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