# `bash` tips/tricks/HOWTOs ## HOWTO: Read exit status You can just do things like: if cp $1 $2 ; then echo succeeded else echo failed fi Alternatively, $? holds the exit status of the most recently executed command. ## TIP: Command substitution `command` or $(command) ## TIP: Redirection To redirect stdout to /dev/null, and stderr to the tty: $ tidy index.html 2>/dev/stdout 1>/dev/null ## TIP: Parameter expansion ${foo} or $foo ## TIP: `$FUNCNAME` contains the current function name The `$FUNCNAME` variable is set to the name of the function while the function is executing. (i.e. like `$0`, except the name of the function, rather than the name of the script.) ## TIP: `$BASH_SOURCE` contains the current filename If you want to discover the real path of the current filename (i.e. after resolving symbolic links), use `readlink`: echo $(readlink $BASH_SOURCE) Note that `$BASH_SOURCE` is actually an array, but when treated as a scalar, it returns the first element of the array. ## HOWTO: Perform conditional variable assignment If `$1` exists, assign `$CONFIGROOT` its value, otherwise set `$CONFIGROOT` to `$HOME/.config`: CONFIGROOT=${1:-$HOME/.config} ## TIP: `sudo !!` Repeats the last command under `sudo`. ## HOWTO: In a shell script, ensure a temporary file is deleted TEMPFILE=$(mktemp) trap "rm -rf $TEMPFILE" EXIT `$TEMPFILE` will be removed in almost all circumstances when the shell exits, including Ctrl-C. ## HOWTO: Display current/existing keybindings bind -P The escape sequences are defined as follows: \C- control prefix \M- meta prefix \e an escape character \\ backslash \" literal " \' literal ' You can also use `TAB` for the tab character. (May or may not be the same as `\t`, below. In addition to the GNU Emacs style escape sequences, a second set of backslash escapes is available: \a alert (bell) \b backspace \d delete \f form feed \n newline \r carriage return \t horizontal tab \v vertical tab \nnn the eight-bit character whose value is the octal value nnn (one to three digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits)