golb

Bash

Redirection

# override to FILE
cmd > FILE
# append to FILE
cmd >> FILE

# stdin
cmd < FILE
cmd <<< "string"

# redirect stdout and stderr to FILE
cmd &> FILE
# or
cmd >& FILE

# The standard output of cmd is connected via a pipe to the standard input of cmd2.
cmd | cmd2

# cmd's standard error, in addition to its standard output, is connected to cmd2's standard input through the pipe
cmd |& cmd2

Syntax

# multiple commands
CMD_1 ; CMD_2 ; CMD_3

# Background task
CMD &

# Conditional commands
CMD_1 && CMD_2
CMD_1 || CMD_2

test flags

Shell tricks

!! # last command
 ls # with a trailing space -> not in history

disown -a && exit # leave terminal but don't kill running processes

Basic command completion

_my_cmd(){
    local cur opts
    # Current word being completed
    cur="${COMP_WORDS[COMP_CWORD]}"

    # The words you want to complete
    opts='run copy $(ls)' # or however you want to list them

    # Fill COMPREPLY with matches
    COMPREPLY=( $(compgen -W "${opts}" -- "$cur") )
}

# some completion for my_cmd
if [[ -v BASH_VERSINFO && "$BASH" == */bash ]]; then
    complete -F _my_cmd my_cmd
fi

To enable physical path (vs logical) of symlinks you can set a bash option

set -o physical
# same as
set -P

Pipefail

set -euo pipefail
curl https://example.org | grep a
# if the pipe fails, the script will stop
echo "end of script"

Switch between background and foreground

command &
fg # change to foreground
# pause with CTRL+Z
bg # sent it to background

# list processes
jobs

# to kill a process
kill %1

# CTRL+Z # is SIGTSTP
# kill -STOP # is SIGSTOP