Mastering 5 Essential Bash Techniques for Programmers
Written on
Chapter 1: Introduction to Bash Programming
Bash has solidified its role as the primary automation tool for modern Unix-like and Unix-based operating systems. Programmers leverage Bash to streamline repetitive command-line tasks by crafting shell scripts. The main purpose of Bash is to provide a straightforward syntax to run other programs while managing their exit codes and outputs. However, current versions of Bash have evolved to include a comprehensive command language that incorporates features typical of general-purpose programming languages. This development enables the creation of highly readable shell scripts that blend conventional command-line usage with algorithmic logic. Recent updates have introduced associative arrays and performance enhancements like pass-by-reference support, positioning Bash alongside other popular scripting languages.
In this guide, I will outline several Bash coding techniques that can modernize your shell scripts, enhancing both speed and clarity. These methods will empower you to use Bash for various programming tasks, such as prototyping algorithms, developing utility applications, or even engaging in competitive programming!
Section 1.1: Utilizing Arrays in Shell Scripts
In Bash, a standard variable lacks a specific type, allowing it to be treated as an integer, decimal, or string based on the context. Typically, Bash variables store command outputs, algorithm parameters, and temporary values. Bash supports two types of arrays: one-dimensional (numerically indexed) and associative (key-value pairs). Manipulating Bash arrays is as intuitive as in other dynamically-typed languages like Python, PHP, or JavaScript. Here's 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[@]}
This code outputs the contents of both arrays as follows:
To check the declaration of each array, use the declare built-in command as shown below:
You can also manipulate arrays, adding or removing items, processing elements, or sorting them with concise syntax. For instance, the following script eliminates invalid score values and prints the top three scores:
#!/bin/bash
declare -a marks
marks+=(75 65 80 102 26) # class A marks
marks+=(103 68) # class B marks
# Remove invalid marks
for i in "${!marks[@]}"; do
if ((marks[i] > 100)); then
unset "marks[$i]"fi
done
# Sort all marks
marks_s=($(printf '%sn' "${marks[@]}" | sort -nr))
# Prints the top-3
echo ${marks_s[0]} ${marks_s[1]} ${marks_s[2]}
While the above script utilizes an external sort command, you can avoid this by implementing an efficient sorting algorithm directly in Bash.
Section 1.2: Creating Maps or Dictionaries
In certain coding situations, it's essential to store key-value pair data within your shell scripts. Key-value structures are commonly used to form dictionaries, maps, and caching containers via memoization. If you prefer Python for scripting, you might employ its built-in dictionary data structure. But how can you implement a similar concept in Bash?
Bash introduced associative arrays for key-value storage starting with version 4.0. Hereβs a simple example of how to use associative arrays in Bash:
#!/bin/bash
declare -A marks=([john]=75 [doe]=82 [ann]=83 [ava]=72)
for key in "${!marks[@]}"; do
printf "$key t ${marks[$key]} n"
done
This code snippet extracts all dictionary keys using the !mapvar[@] syntax for iteration, producing output like this:
Bash allows you to manipulate associative array data with minimal syntax, resembling the ease of working with Python dictionaries. Consider the following example:
#!/bin/bash
read -p "Enter coords (i.e., [x]=10 [y]=12): " coords
declare -A "coords=($coords)"
if [ ! -v "coords[x]" ]; then
coords[x]=5
fi
if [ ! -v "coords[y]" ]; then
coords[y]=10
fi
for key in "${!coords[@]}"; do
printf "$key = ${coords[$key]} n"
done
In this script, user input for x and y coordinates is requested, and default values are assigned for any missing entries, which are then displayed in the terminal.
Chapter 2: Advanced Bash Features
The first video titled "5 Bash Tricks to Make You a Cooler Programmer" provides an insightful exploration of effective Bash techniques that can elevate your scripting skills.
The second video, "You Don't Know Bash as Well as You Think," challenges common assumptions about Bash programming and encourages deeper understanding.
By implementing these advanced features and techniques, you can significantly enhance the performance and readability of your Bash scripts, making them not just functional but elegant as well.
Thanks for reading!
Level Up Coding
Thanks for being a part of our community! Before you go: π Clap for the story and follow the author ππ° View more content in the Level Up Coding publication π° Free coding interview course β View Course π Follow us: Twitter | LinkedIn | Newsletter ππ Join the Level Up talent collective and find an amazing job.