Posts

Showing posts with the label bash

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. 

Bash coolness

There is a clever feature in bash, in that you can do a lot of manipulations while accessing a variable. Note that I always use "clever" in a pejorative sense, but while this is clever (argh) it is also helpful to me. I find that I, like all users, will tolerate a little cleverness if it gets my work done. In this case, it's the substitution features that get my attention. For variables: ${VAR:-zzz} returns $VAR, or "zzz" if $VAR is empty ${VAR//x/y} returns $VAR after replacing all "x" with "y" ${VAR:=zzz} returns $VAR or "zzz" if VAR is unset, and assigns VAR (ick) And of course the coolest version is the $() operator (AKA: command substitution), which used to be done with ugly backticks. This runs a command and returns the output of the command into a variable: $(echo $fname| cut -d. -f1) $(echo $(basename $fname) | cut -d -f1) Which leads to this kind of "clever" coding: dest=${DESTDIR:-/tmp}/$(echo $(basename ${sourc...