12

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)]\$ '
ma11hew28
  • 121,420
  • 116
  • 450
  • 651

3 Answers3

20

Bash allows for default values:

a=${b-`pwd`}

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

Manny D
  • 20,310
  • 2
  • 29
  • 31
  • More often, I see another form: `${PWD:-\`pwd\`}` I wonder if they are equivalent – GregT Jul 14 '15 at 23:38
  • 2
    @GregT if `b` is unset, they will behave the same. If `b` is set to an empty string, however, then `${b-\`pwd\`}` will result in an empty string, but `${b:-\`pwd\`}` will result in the working directory. – Jun-Dai Bates-Kobashigawa Aug 25 '15 at 14:52
2

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

[ -n $PWD ] || PWD=`pwd`
user456584
  • 86,427
  • 15
  • 75
  • 107
  • While I like the style, if MyVar is set to a zero length string it will not be set to 'value' in this example, whereas using bash "default values" a la @Manny D, above, would work arguably correctly, as in: `MyVar=${MyVar-'value'} – malcook May 15 '15 at 22:14
2

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

PS1='\w '   # Using \W will provide just basename
grok12
  • 3,526
  • 6
  • 26
  • 27