# bash

shortcuts

alt-backspace   # delete left word
ctrl-t          # swap last two chars, readline emacs mode
alt + .         # cylcle through last arguments

special parameters

$?    # last exit code
$!    # pid of last background proc
!!    # last/previous command
!$    # first of last arguments
!*    # all last arguments
~-    # previous directory

history

!!          # execute last command in history
^foo^bar    # execute last command after replacing foo w/ bar
!abc        # execute last command in history beginning w/ 'abc'
!abc:p      # print last command in history beginning w/ 'abc'
ctrl-r      # search in history
ctrl-g      # exit history search

redirection

connect stdout or stdout and stderr of command1 to stdin of command2 with

command1 | command2
command1 |& command2    # shorthand for:
command1 2>&1 | command2

predefined 0 stdin, 1 stdout, 2 stderr.

command 2>/dev/null
command 1>&2
command >/dev/null 2>&1

> overwrites while >> appends to file. process substitution puts output in named fifo which can be used like a file by other process: cat <( echo hello ). doesn't work w/ source before bash 3.2, workaround: . /dev/stdin <<<"$( echo 'PS1=yep' )".

path expansion

additional to globbing there's extended globbing (shopt extglob).

# match all files w/o `.` in their filenames
ls +([^.])

parameter expansion

remove matching pre/suffix

${a#pattern}    # prefix
${a##pattern}   # greedy
${a%pattern}    # suffix

case modification

${a,,pattern}   # lowercase all chars in `$a` that match pattern
${a,,}          # same as `${a,,?}`
${a,pattern}    # lowercase only first matching char
${a^pattern}    # uppercase

variables

By convention, environment variables (PAGER, EDITOR, ...) and internal shell variables (SHELL, BASH_VERSION, ...) are capitalized. All other variable names should be lower case. If it's your variable, lowercase it. If you export it, uppercase it.

builtins

help [name]
command -v <name>   # like `which` w/o error message
type [name]         # display information about command type, includes function body
declare -F [name]   # display declared function names
declare -f [name]   # display declared function including body
read var            # read one line from stdin into `var`
typeset             # (deprecated?) synonym for `declare`

includes

. is the Bourne and POSIX shell command while source is the C-Shell command.

unsorted

dollar sign before string triggers special char evaluation, f.e.: $'\n'

create sequence w/ {3..9}

figure out running shell session:

[[ $- == *i* ]] && echo 'Interactive' || echo 'Not interactive'
[[ -o login ]] && echo 'Login shell' || echo 'Not login shell'

function return value w/ declare

[0] $ function marius () { declare -n var=$1; var='xxx'; }
16:05:07 heiko@bonn:~
[0] $ msg=
16:05:19 heiko@bonn:~
[0] $ marius msg
16:05:28 heiko@bonn:~
[0] $ echo $msg
xxx