Bash Tips

Some bash one-liners:

echo ${!X*}

Will print all the names of variables whos name starts with X. To output the contents of a variable so it can be parsed by
bash

declare -p VARNAME

Pattern Matching

Operator: ${foo#t*is}

Function: deletes the shortest possible match from the left

Operator: ${foo##t*is}

Function: deletes the longest possible match from the left

Operator: ${foo%t*st}

Function: deletes the shortest possible match from the right

Operator: ${foo%%t*st}

Function: deletes the longest possible match from the right MNEMONIC: The # key is on the left side of the $ key and operates from the left. The % key is on the right of the $ key and operates from the right.

Substitution

Operator: ${foo:-bar}

Function: If $foo exists and is not null, return $foo. If it doesn't exist or is null, return bar.

Operator: ${foo:=bar}

Function: If $foo exists and is not null, return $foo. If it doesn't exist or is null, set $foo to bar and return bar.

Operator: ${foo:+bar}

Function: If $foo exists and is not null, return bar. If it doesn't exist or is null, return a null.

Operator: ${foo:?"error message"}

Function: If $foo exists and isn't null, return its value. If it doesn't exist or is null, print the error message. If no error message is given, it prints parameter null or not set. In a non-interactive shell, this aborts the current script. In an interactive shell, this simply prints the error message.

$$ for Subshell

When running a sub-shell in bash the $$ construct still returns the process id of the main shell. Use the following construct to determine the correct IP address:

mypid=$(sh -c 'echo $$PPID')

Yes, it looks nasty.