Shell scripting template

Once every week or so, I’ve to quickly write up some script(s) to automate something, have more control over a workflow, write a tool, etc. There is a common theme that emerges:

  • Just write all the commands I need to run line by line in the script
  • Wrap the above logic with conditionals or other logic based on the what I need to get done
  • Handle error management gracefully i.e. throw meaningful error messages and/or redirect to a log file or something.

So in this blog post, I’ll write a simple script that does all of this.

main.sh

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/bin/bash

echo "Running main script"

# Import library functions
source lib.sh

# Run script 1 and script 2, and report errors if any
# Showing different ways to throw errors in case something goes wrong
./script1.sh &&
(./script2.sh || error_exit "Script 2 failed") &&
echo "Main script ran successfully"

exit 0

scrip1.sh

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/bin/bash

echo "Running script 1"

# Import library functions
source lib.sh

if true; then
    echo "Script 1 has no error"
else
    error_exit "Script 1 has error"
fi

exit 0

script2.sh

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/bin/bash

echo "Running script 2"

# Import library functions
source lib.sh

if false; then
    echo "Script 2 has no error"
else
    exit 1
fi

exit 0

lib.sh

1
2
3
4
5
6
7
8
9
#!/bin/bash

# An error exit function

error_exit()
{
    echo "$1" 1>&2
    exit 1
}

Here’s what happens when I run main.sh:

1
2
3
4
5
6
[spraza@spraza-do2:~/code/play/shell-script]$ ./main.sh
Running main script
Running script 1
Script 1 has no error
Running script 2
Script 2 failed

All the code is here.

Some key takeaways:

  • Always use exit codes (0 for success). This is fairly common in unix systems and in C to communicate success/failure across different components
  • Use library functions and import if possible
  • Use error management and AND/OR operators to exit early (if that’s what you need)

You can read more about writing shell scripts here.