Featured image of post BASH in a Nutshell

BASH in a Nutshell

Intro to the Bash Shell

BASH in a Nutshell

Introduction

Bash (Bourne Again Shell) is one of the most widely used Unix shells.

Developed as a free software replacement for the Bourne Shell (sh), Bash has become the default shell for most Linux distributions and macOS.

A Brief History of Bash

Bash was created by Brian Fox in 1989 as part of the GNU Project.

Brian intended to create a free alternative to the proprietary Bourne Shell.

Bash was later maintained by Chet Ramey.

Over the years, Bash has evolved, introducing features from KornShell (ksh) and C Shell (csh), making it more powerful and user-friendly.

Bash history:

  • 1989: Initial release of Bash (version 1.0).
  • 1996: Bash 2.0 introduced command-line editing and improvements.
  • 2004: Bash 3.0 introduced arithmetic improvements and enhanced scripting capabilities.
  • 2009: Bash 4.0 added associative arrays and better programming constructs.
  • 2014: Bash 4.3 became infamous due to the Shellshock vulnerability.
  • 2019: Bash 5.0 introduced improved scripting features and performance enhancements.

Getting Started with Bash

Basic Commands

Fundamental Bash commands:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Print text to the terminal
echo "Hello, world!"

# List files in the current directory
ls -l

# Create a new directory
mkdir my_folder

# Change directory
cd my_folder

# Remove a file
rm myfile.txt

Writing a Simple Bash Script

Bash scripts are simple text files containing a sequence of commands. Here’s an example:

1
2
3
4
5
#!/bin/bash

echo "Welcome to Bash scripting!"
echo "Today's date is: $(date)"
echo "Your current directory is: $(pwd)"

Save this file as script.sh, then make it executable and run it:

1
2
chmod +x script.sh
./script.sh

Variables and Conditionals

Bash supports variables and conditional statements:

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

NAME="Alice"

if [ "$NAME" == "Alice" ]; then
    echo "Hello, Alice!"
else
    echo "Who are you?"
fi

Loops in Bash

Bash allows looping through commands:

1
2
3
4
5
6
#!/bin/bash

for i in $(seq 1 5)
do
    echo "Iteration $i"
done

Functions in Bash

Bash also supports functions:

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

greet() { 
    echo "Hello, $1!"
}

greet "Alice"
greet "Bob"

References