3. Bash
1. Getting Started
Bash (Bourne Again Shell) is a Unix shell and command language that is widely used in Linux and macOS systems for automating tasks and running scripts. Here’s how to get started with Bash on Ubuntu or any Linux system.
1.1 Check if Bash is Installed
Most Linux distributions, including Ubuntu, come with Bash pre-installed. You can check your current shell by running:
echo $SHELL
If the output is /bin/bash
, then Bash is installed and set as your default shell. To verify the version of Bash installed, run:
bash --version
1.2 Writing and Running Your First Bash Script
a. Create a New Bash Script
-
Open a terminal.
-
Create a new file called
hello.sh
using any text editor (likenano
orvim
):Terminal window nano hello.sh -
Write the following Bash code in the file:
#!/bin/bashecho "Hello, World!"#!/bin/bash
is called the “shebang” and tells the system that this script should be run using the Bash shell.echo
is a built-in command that outputs text to the terminal.
-
Save and exit the text editor.
b. Make the Script Executable
Before you can run the script, you need to give it execute permissions:
chmod +x hello.sh
c. Run the Script
Now, you can execute your Bash script:
./hello.sh
You should see the output: Hello, World!
1.3 Common Bash Commands
Here are some frequently used Bash commands:
-
ls
: Lists files and directories in the current directory.Terminal window ls -
cd
: Changes the current directory.Terminal window cd /path/to/directory -
pwd
: Prints the current working directory.Terminal window pwd -
touch
: Creates a new, empty file.Terminal window touch newfile.txt -
cat
: Displays the contents of a file.Terminal window cat hello.sh -
cp
: Copies files or directories.Terminal window cp source.txt destination.txt -
mv
: Moves or renames files or directories.Terminal window mv oldname.txt newname.txt -
rm
: Removes files or directories.Terminal window rm file.txt
2. Control Structures in Bash
Control structures in Bash help manage the flow of execution in a script.
2.1 Conditional Statements
-
if
,elif
,else
: These are used for conditional execution of code.Terminal window # Basic if-else structureif [ condition ]; then# Commands to run if condition is trueecho "Condition is true"elif [ another_condition ]; then# Commands if another condition is trueecho "Another condition is true"else# Commands to run if all conditions are falseecho "Condition is false"fi -
Example:
Terminal window age=18if [ $age -ge 18 ]; thenecho "You are an adult."elseecho "You are a minor."fi-ge
stands for “greater than or equal to.” Common conditional operators include:-eq
: Equal-ne
: Not equal-lt
: Less than-le
: Less than or equal to-gt
: Greater than-ge
: Greater than or equal to
2.2 Case Statement
-
A
case
statement is used to handle multiple conditions more cleanly than multipleif-else
branches.Terminal window case $variable inpattern1)# Commands if variable matches pattern1;;pattern2)# Commands if variable matches pattern2;;*)# Default commands if no pattern is matched;;esac -
Example:
Terminal window day="Monday"case $day in"Monday")echo "Start of the work week!";;"Friday")echo "It's almost weekend!";;*)echo "Just another day.";;esac
2.3 Loops
Bash supports different types of loops to iterate over a set of commands.
-
for
loop: Iterate over a list or a range of values.Terminal window for item in list; do# Commands to executeecho $itemdone-
Example:
Terminal window for num in {1..5}; doecho "Number: $num"doneThis loop iterates from 1 to 5, printing each number.
-
-
while
loop: Repeat commands while a condition is true.Terminal window while [ condition ]; do# Commands to executedone-
Example:
Terminal window count=1while [ $count -le 5 ]; doecho "Count: $count"count=$((count + 1))doneThis loop continues as long as
count
is less than or equal to 5.
-
-
until
loop: The opposite ofwhile
; it runs until a condition becomes true.Terminal window until [ condition ]; do# Commands to executedone-
Example:
Terminal window count=1until [ $count -gt 5 ]; doecho "Count: $count"count=$((count + 1))done
-
2.4 Loop Control Statements
-
break
: Exit the loop early.Terminal window for i in {1..10}; doif [ $i -eq 5 ]; thenbreakfiecho "Number: $i"done -
continue
: Skip to the next iteration of the loop.Terminal window for i in {1..5}; doif [ $i -eq 3 ]; thencontinuefiecho "Number: $i"done
2. Data Structures in Bash
Bash doesn’t have built-in advanced data structures like arrays or dictionaries found in higher-level programming languages, but you can simulate them using basic constructs.
2.1 Variables
-
Variables in Bash are simple containers for storing data (strings, integers, etc.). They are dynamically typed and do not require type declaration.
Terminal window name="Alice"age=25- Access the value of a variable using
$
.Terminal window echo "Name: $name"
- Access the value of a variable using
2.2 Arrays
-
Bash supports one-dimensional arrays.
Terminal window # Declare an arrayfruits=("apple" "banana" "cherry")# Access array elements (index starts at 0)echo ${fruits[0]} # Outputs: apple# Access all elementsecho ${fruits[@]}# Add a new element to the arrayfruits+=("orange")# Get the number of elements in the arrayecho ${#fruits[@]} # Outputs: 4-
Iterating over arrays:
Terminal window for fruit in "${fruits[@]}"; doecho $fruitdone
-
2.3 Associative Arrays (Hash Maps)
-
Bash version 4.0 and later supports associative arrays, which allow you to use strings as keys.
Terminal window # Declare an associative arraydeclare -A person# Assign valuesperson[name]="Alice"person[age]=25person[city]="New York"# Access valuesecho ${person[name]} # Outputs: Alice# Iterate over keys and valuesfor key in "${!person[@]}"; doecho "$key: ${person[$key]}"done
2.4 Strings
-
Strings are a basic data type in Bash and are easy to manipulate.
Terminal window greeting="Hello"name="Alice"message="$greeting, $name!"echo $message # Outputs: Hello, Alice!-
String Length:
Terminal window echo ${#name} # Outputs: 5 (length of "Alice") -
Substring Extraction:
Terminal window echo ${name:1:3} # Outputs: "lic" (substring from index 1, length 3) -
Concatenation:
Terminal window full_name="$greeting, $name"
-
2.5 File Descriptors
-
Bash allows working with input, output, and error streams using file descriptors.
-
Redirect output to a file:
Terminal window echo "Hello" > output.txt -
Redirect errors to a file:
Terminal window command 2> error.log -
Pipe commands:
Terminal window ls | grep ".txt"
-