Neural Nets

Bash Scripting

/ 5 min read

Download As PDF

Understanding Bash and How It Differs from Linux

Bash (Bourne Again SHell) is one of the most widely used command-line interfaces and scripting languages in Unix-like operating systems. While it is often associated with Linux, Bash is not synonymous with Linux itself. To clarify, Bash is a command processor that allows users to type commands and execute them. It is the default shell on most Linux distributions, but it can also run on other systems like macOS and Windows (via Windows Subsystem for Linux or Cygwin).

Key Differences Between Bash and Linux

  • Bash is a shell, Linux is a kernel: Linux is the core of an operating system, often referred to as a kernel, responsible for managing system resources and hardware. On the other hand, Bash is a shell, which is an interface between the user and the Linux kernel. Users issue commands through Bash to interact with the system.

  • Bash can run on various systems: While Linux is an operating system kernel, Bash is not tied to Linux. You can install and run Bash on various Unix-like systems (such as macOS), and even on Windows through compatibility layers.

  • Scripting capabilities: Bash is a fully-fledged scripting language that can be used to automate tasks and build complex scripts. Linux itself doesn’t have a built-in scripting language; instead, it relies on shells like Bash for scripting.

What is Bash Scripting?

Bash scripting involves writing a series of commands in a text file and executing them in sequence. Bash scripts allow users to automate repetitive tasks, perform system maintenance, manage files, and much more. This makes it extremely powerful for system administrators and power users.

Let’s start with some basic Bash scripting for beginners and progress towards more advanced examples.

Basic Bash Scripting for Beginners

1. Hello World Script

The simplest Bash script just prints “Hello, World” to the terminal.

#!/bin/bash
# This is a comment. Everything after # is ignored by Bash.
echo "Hello, World!"
  • #!/bin/bash: This is called a “shebang” and indicates that the script should be run using the Bash shell.
  • echo "Hello, World!": This command prints the text to the terminal.

2. Variables and User Input

Bash scripts can use variables to store data and perform tasks based on input.

#!/bin/bash
# Define a variable
name="John Doe"
# Print the variable
echo "Hello, $name!"
# Read input from the user
echo "Enter your name:"
read user_name
echo "Hello, $user_name!"

3. Conditional Statements (if-else)

Bash supports conditional statements to perform tasks based on conditions.

#!/bin/bash
echo "Enter a number:"
read num
if [ $num -gt 10 ]; then
echo "The number is greater than 10"
else
echo "The number is 10 or less"
fi
  • if [ $num -gt 10 ]: This checks if the value stored in num is greater than 10 (-gt stands for “greater than”).
  • fi: This ends the if block.

4. Loops in Bash

Loops allow you to repeat tasks multiple times.

#!/bin/bash
# For loop
for i in 1 2 3 4 5; do
echo "Iteration: $i"
done
# While loop
counter=1
while [ $counter -le 5 ]; do
echo "Counter: $counter"
((counter++)) # Increment counter
done
  • for i in 1 2 3 4 5: This loops over the numbers 1 through 5.
  • while [ $counter -le 5 ]: This repeats the loop as long as counter is less than or equal to 5.

Advanced Bash Scripting

Once you’re comfortable with the basics, you can begin to explore more advanced features of Bash scripting.

1. Using Functions

Functions allow you to encapsulate blocks of code that can be reused.

#!/bin/bash
# Define a function
greet_user() {
echo "Hello, $1!"
# $1 is the first argument passed to the function
}
# Call the function with an argument
greet_user "Alice"
greet_user "Bob"
  • greet_user() { ... }: Defines a function.
  • $1: Represents the first argument passed to the function.

2. File Manipulation

Bash scripts are often used for file manipulation tasks.

#!/bin/bash
# Create a new file and write to it
file="output.txt"
echo "This is a sample text" > $file
echo "Another line of text" >> $file
# Check if the file exists
if [ -f $file ]; then
echo "$file exists."
else
echo "$file does not exist."
fi
  • > $file: Redirects output to a file (overwrites the file).
  • >> $file: Appends output to the file.

3. Working with Arrays

Bash supports arrays, which can store multiple values.

#!/bin/bash
# Define an array
fruits=("apple" "banana" "cherry")
# Print all elements of the array
echo "All fruits: ${fruits[@]}"
# Access individual elements
echo "First fruit: ${fruits[0]}"
# Loop through the array
for fruit in "${fruits[@]}"; do
echo "I like $fruit"
done

4. Error Handling and Exit Codes

You can handle errors in Bash using exit codes. A non-zero exit code indicates that an error occurred.

#!/bin/bash
# Command that will succeed
ls /home
# Check the exit status of the last command
if [ $? -eq 0 ]; then
echo "Command succeeded."
else
echo "Command failed."
fi
# Exit the script with an error code
exit 1 # Exits with code 1 (error)
  • $?: Stores the exit status of the last command (0 for success, non-zero for failure).
  • exit 1: Exits the script with a custom error code.

5. Command Substitution

You can capture the output of a command and use it as a variable.

#!/bin/bash
# Command substitution
current_date=$(date)
echo "Today's date is: $current_date"
  • $(command): Executes command and stores its output in a variable.

6. Advanced Looping with Files

A script can process files line by line.

#!/bin/bash
# Loop through each line of a file
while IFS= read -r line; do
echo "Line: $line"
done < "file.txt"
  • IFS= read -r line: Reads each line from the file without trimming leading or trailing spaces.

Conclusion

Bash scripting is an essential skill for Linux users, allowing for automation, task management, and more efficient system administration. From simple tasks like printing messages to more advanced techniques like file manipulation, functions, and error handling, Bash scripting opens the door to many possibilities.