Bash Variable Expansion

This is one of those things that just doesn't stick in my head, so I'm dropping this note to remind myself. 

I often have trouble recalling cryptic variable names in bash, make, and perl. For my own sake, I thought I'd make a quick list of favorites and refer some sources. 

 Maybe you'll find this useful too. 

  • Variable value, but exit if no such variable: ${var:?"error message"}
  • Use default if variable isn't set: ${var:="default"}
  • Get a substring: ${var: start: length} 
  • Length: ${#var} 
  • Uppercase: ${var@U}
  • Lowercase: ${var@L}

 

The first one is quite helpful when you expect a particular set of parameters and don't want to write if/then logic about each of them. 

#/bin/env bash

directory=${1:? You must provide a directory to search}
pattern=${2:? You must provide a search term for filenames}

find ${directory} -name ${pattern}

 

See more at the gnu shell expansion page. 

Comments

Popular posts from this blog

Programming Is Mostly Thinking

Is It My Fault You Can't Handle The Truth?

Preplanning Poker: Is This Story Even Possible?