Bash script

Basics

The first line of the script is

#!/bin/bash

If the script is in the $PATH (e.g. /usr/bin), we can just type my.sh instead of ./my.sh to run it.

# add current working directory to path
PATH=$PATH:$PWD

Best practice to increase portability:

# instead of
#!/usr/local/bin/python3
# use
#!/usr/bin/env python3

Differences between shell functions and other scripts (e.g. python scripts)

Functions are executed in the current shell environment whereas scripts execute in their own process. Thus, functions can modify environment variables, e.g. change your current directory, whereas scripts can’t. Scripts will be passed by value environment variables that have been exported using export

Variables

a=Hello # no spaces!
# a = Hello means run a with = and Hello as arguments

echo $a # Hello
echo "$a" # Hello
echo '$a' # $a
echo a # a

# add attributes to variables
declare -i d=123 # d is an integer
declare -r e=456 # e is read-only
declare -l f="LOLCats" # f is lolcats
declare -u g="LOLCats" # g is LOLCATS

# Built-in varibles
# $HOME $PWD $MACHTYPE $HOSTNAME $RANDOM
# $BASH_VERSION related: bash --version
# $0 name of the script
# $SECONDS time since this bash session had run / since the script started
# env: shows all environment variables

d=$(pwd) # run pwd and put the result in d.

# Arithmetic (only integers are supported)
val=$((expression))
# operators: **, %, +-*/%

e=5
e+=2 # string concatenation
((e+=2)) # arithmetic

Command substitution

Process substitution

Comparisons

Strings

Reading and Writing Text Files

Control Structures

if

note that when expression succeeds (return value is 0), then clause runs. (not like JavaScript, hwere 0 is falsey)

while/until

for loop

Case (switch in C)

Array

Functions

Arguments

Anything with space in it needs quotes.

  • $0: name of the script

  • $1: first argument

  • $#: the number of arguments

  • $@: the arguments array

  • $?: return code of previous command

  • $$: PID of current script

  • $_: last argument of previous command

Interact with the User

Working with flags

Get input during execution

Ensuring a response

What if user just press enter?

Date and Printf

Advanced Topics

Debug Mode

Brace Expansion

ANSI escape codes: e.g. -e can enable escape sequences (start + string to print + end).

Start: '\033[number1;number2m'. Number1 and number 2 are foreground and background colors. m indicates the end of sequence. A style number (followed by ;) before number1 is optional.

End: usually it's '\033[0m', to clear all the formatting.

Color

Foreground

Background

Black

30

40

Red

31

41

Green

32

42

Yellow

33

43

Blue

34

44

Magenta

35

45

Cyan

36

46

White

37

47

Style table

Style

Value

No Style

0

Bold

1

Low Intensity

2

Underline

4

Blinking

5

Reverse

7

Invisible

8

Alternative: use tput.

Here Documents

References

Last updated

Was this helpful?