Bash - The quick guide

September 1, 2023 Shell
Quickly find recipes to resolve shell tasks.

BASH is an acronym for Bourne Again Shell. It is the default shell in most Linux distributions. So use it well can be a time-saving skill.

For full reference, check GNU Bash Manual.

Command line interaction

Moving

  • Control+A Go to the beginning of the line you are currently typing on.

  • Control+E Go to the end of the line you are currently typing on.

  • Control+F Move forward a character.

  • Control+B Move back a character.

  • Meta+F Move cursor forward one word on the current line.

  • Meta+B Move cursor backward one word on the current line.

  • Control+C Kill whatever you are running.

  • Control+D Exit the current shell.

Editing

  • Tab Auto-complete files and folder names.

  • Control+W Delete the word before the cursor.

  • Control+K Clear the line after the cursor.

  • Control+T Swap the last two characters before the cursor.

  • Meta+T Swap the last two words before the cursor.

  • Control+L Clears the Screen, similar to the clear command.

  • Control+U Clears the line before the cursor position. If you are at the end of the line, clears the entire line.

  • Control+H Same as backspace.

  • Control+Z Puts whatever you are running into a suspended background process. fg restores it.

Searching in the history

  • Control+R Searches backworkd through the history.

  • Control+S Searches forward through the history.

Scripting

Check Cheatsheet for syntax,

More detailed tutorial:

Font colors

Common colors

Black        0;30     Dark Gray    1;30
Red          0;31     Light Red    1;31
Green        0;32     Light Green  1;32
Brown/Orange 0;33     Yellow       1;33
Blue         0;34     Light Blue   1;34
Purple       0;35     Light Purple 1;35
Cyan         0;36     Light Cyan   1;36
Light Gray   0;37     White        1;37

No Color     0

Bold Red           1;31
High Intensity Red 0;91

Print RED in shell

printf "\033[0;91mRED\033[0m\n"

Read file line by line

IFS stands for internal field separator or input field separator. The default value is a space, a tab, a newline feed.

while IFS="" read -r line; do
    echo $line
done < README.txt

Generate random string

Random string with 12 length

dd if=/dev/urandom count=1 2> /dev/null | base64 -i - | cut -c -12 -

Here doc for arbitrary text

cat <<EOF | tee file.txt
line 1
line 2
EOF

Keep runing after logging off

The & symbol at the end send it to the background.

nohup [CMD] > nohup.out &

Unlike nohup, disown is used after you started a process.

disown [PID]

Parse CLI arguments

The following snippet implements CLI arguments parsing. Options usually start with a dash, but arguments is position based. It should be useful for most scenarios.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# usage: script.sh -o1 abc xyz
opts_count=0
args_count=0
args=()
dry_run=0

# define options here
opt1=''

while :; do
  case "${1-}" in
  -h | --help)
    echo 'help message'
    exit 0
    ;;

  # parse options
  --dry-run)
    dry_run=1
    ;;

  -o1 | --opt1)
    opt1="${2-}"

    (( opts_count += 1 ))
    shift
    ;;

  -?*)
    echo "unrecognized option"
    exit 0
    ;;

  *)
    args+=("${1-}")

    if [[ -z "${1-}" ]]; then
      break
    fi
    ;;
  esac

  if [[ -n "${1-}" ]]; then
    shift
  fi
done

# default value for arguments
arg1=''

# parse args
for arg in "${args[@]}"; do
  if [[ -n "$arg" ]]; then
    (( args_count += 1 ))

    # define positional arguments here
    if (( args_count == 1 )); then
      arg1="$arg"
    fi
  fi
done

if (( opts_count == 0 && args_count == 0 )); then
  echo "no options or aguments"
fi

FAQ

Single quotes or double quotes?

echo string can be included using single quotes or double quotes. But double quotes is preferred, because single quotes can’t match end of file. When echo string using single quotes, there must be a semicolon at the end echo 'Little King';

Single square brackets or double square brackets?

Please refer to Greg’s Wiki

Can I do a spinner in Bash?

Please refer to Greg’s Wiki.