5 Bash Coding Techniques That Every Programmer Should Know

Use these coding techniques to write fast and readable shell scripts

Shalitha Suranga
Level Up Coding
Published in
7 min readMar 22, 2023

--

Photo by Emile Perron on Unsplash, edited with Canva

Bash undoubtedly became every modern Unix-like or Unix-based operating system’s native, inbuilt automation solution. Programmers use Bash to automate their repetitive command-line tasks by creating shell scripts. The primary goal of Bash is to offer a minimal syntax to execute other programs and work with their exit codes and output. But, modern Bash interpreters come with a fully-featured command language that offers most general-purpose programming language features. So, we can write highly-readable shell scripts by including traditional command-line invocations and algorithmic code. Modern Bash versions introduced associative arrays and performance-related features like pass-by-reference support to make Bash competitive with other shell-scripting-ready languages.

In this story, I will explain some Bash coding techniques you can include in your shell scripts to make them modern, fast, and readable. With these techniques, you can use Bash to write general-purpose programming or algorithm implementations, such as algorithm prototyping, implementing utility programs, or even competitive programming!

Using arrays in shell scripts

A traditional Bash variable typically has no type, but you can process it as an integer, decimal, or string according to a particular processing context. We usually use Bash variables to store command outputs, algorithm parameters, and other temporary values. Bash also supports two array types: one-dimensional (numerically indexed) and associative (key-value structure). Working with Bash arrays is easy as with other popular dynamically-typed general-purpose languages, such as Python, PHP, or JavaScript. See how to create arrays in Bash:

#!/bin/bash

numbers=(2 4 5 2)

declare -a words
words[0]='Orange'
words[1]='Pineapple'

echo ${numbers[@]} ${words[@]}

The above code outputs array contents as follows:

You can check the declaration of each array reference with the declare built-in as follows:

--

--