8 Bash Script Tips for Automation Projects | by Shinichi Okada | Towards Data Science

Using Bash script, I have automated Backpack for Laravel modules for installation/uninstallation. From this project, I selected eight practical tips that you can apply to any Bash scripting project.
Laravel is the most popular PHP framework. Backpack for Laravel is a collection of Laravel packages that help you build custom administration panels. It has eight modules including core, permission manager, page manager, menu, and file manager.
Here is my backpack_install repo on Github.
You need to know Bash scripting basics and have some experience in writing basic Bash scripts.
These articles are also helpful to get you started:
betterprogramming.pub
betterprogramming.pub
Shellman is not only a shell scripting snippet extension for VS Code, but it also provides a free ebook with numerous useful snippets and tips for Bash scripting.
The book suggests the following structure.
1. shebang2. summary3. handler functions4. event handers5. functions6. argument parsing7. setting default variable values8. rest of code (main body)
Often you need to declare variables and functions before their usage. I come up with a structure that works for me. Having argument parsing and setting default variable values after functions were not options.
This is the structure I ended up with:
1. shebang2. summary3. default variable values4. arguments parsing (including usage function which uses variables from 3.)5. importing files (otherwise the file becomes too long.)6. functions (using variables and functions from 3, 4 & 5.)7. event functions (Ctrl+C event using a function from 5 & 6.)8. check-command function (checking if the system has commands.)9. read standard input10. main body (using functions from 5 & 6.)
I declare default variable values, parse arguments, and import files before functions so that I can use variables for function parameters.
The script needs to install eight modules, so I divided each installation into separate files.
I could use source ./lib/file_name or . ./lib/file_name to import files to the main script but Shellman provides an alternative import function.
I created a lib directory and stored all files to be imported in this directory. Add Shellman’s import function in the main script:
Line 2: You can add .sh after ${1} if your file has the extension.
Line 0: You don’t need to add #!/usr/bin/env bash at the beginning of files nor make the files executable. If you do, make the text editor use the formatting and syntax highlighting.
The files in the lib directory must have a function(s) if you want to use function arguments. For example, the functions in the lib/banners file uses three parameters.
The lib/bp_pagemanager file uses the source command to read a file and one of the functions:
Line 5: Sourcing the banners file.
Line 14: Using bannerColor function with three arguments.
A banner is a useful way to tell users what your script is doing. If you use plain text, users won’t notice it.
Import the lib/banners file and use the bannerColor function as in the following examples.
It requires three parameters, banner content, color, and symbol.
Examples:
bannerColor 'Installing CRUD.' "blue" "*"
bannerColor "Happy Coding!" "magenta" "*"
bannerColor "Uninstalling ..." "red" "*"
bannerColor 'Running php artisan optimize:clear' "yellow" "*"
Choose a color from black, red, green, yellow, blue, magenta, cyan, and white.
Use any symbol(s) like ***, >>, ^^^.
When a shell receives a signal, for example Ctrl-C termination, the trap command traps the signal and executes a command.
The trap command has the structure of trap func signal(s).
You can define a func according to your need and use a signal name(s) that the function reacts to. In our case I used SIGINT which is for the Ctrl-C interruption.
Example:
To find signal names in Linux, run trap -l.
macOS uses ZSH as a default shell, so you need to change the shell to bash. Use bash command then trap -l, or run chsh -s /bin/bash to change the shell, open a new tab, and then run trap -l:
You need to run a bunch of composer remove commands to uninstall packages, find --delete command to remove migration files, php artisan optimize:clear and composer dump-autoload to clear all caches.
Line 22: Use git rev-parse --git-dir to detect if the directory is a Git directory or not. If it is, use the script reset and clean the git repo.
Use the check_cmd function to check if the user’s system has required commands. I keep the check_cmd function in the lib/utils file.
Example:
Line 2: Use $(command -v "$1") to check if the user’s system has the required command. If not, exit with exit code 1.
When you read the user’s standard input, you can select the first letter, cut -c 1-1 and transfer it to an upper case letter, tr "[:lower:]" "[:upper:]".
Example:
Use if-statement and exit if the input is not Y.
The Shellman’s option function is an alternative to the read function. Users select an option using an up/down key. I keep the inputChoice functions in the lib/utils file.
When you use it, define the options variable first:
options=("one" "two" "three");inputChoice "Choose:" 0 "${options[@]}";choice=$?; echo "${options[$choice]}"
The first parameter for the inputChoice function is a text you want to display. The second parameter is the default choice. 0 selects the first option. The third parameter requires options, ${options[@]}.
Example:
In the above code, if the -u flag is given, reconfirm the user’s intention using the options function.
When you learn new methods, I recommend implementing them in your existing projects. I hope you can use some of these tips in your project.
If you are repeating lines of code, it is time to automate them. Bash scripting is one of the best choices.
Happy coding.
If you like my article and would like to receive newsletters, please sign up.
Get full access to every story on Medium by becoming a member.