Bash Scripting Fundamentals (original) (raw)

Last Updated : 7 May, 2026

Bash scripting is the process of writing a sequence of commands in a file and executing them together to perform tasks automatically. Instead of running commands one by one in the terminal, a script allows you to execute them in a single step.

Writing Your First Bash Script

A Bash script is a simple text file containing commands that the shell can execute. Creating and running a script allows you to automate tasks instead of typing commands manually.

Step 1: Create a Script File

Open the terminal and create a file, this creates a file named hello.sh.

**Command:

nano hello.sh

Step 2: Add Script Code

Add the following lines to the file:

**Command:

#!/bin/bash
echo "Hello, World!"

sample-scr

Step 3: Save and Exit (Nano Editor)

After typing the code:

Step 4: Make the Script Executable

By default, scripts do not have execute permission.

**Command:

chmod +x hello.sh

Step 5: Run the Script

Execute the script using

**Command:

./hello.sh

**Output:

sample-scr-op

Variables in bash

Variables in Bash are used to store data that can be reused throughout a script. They make scripts flexible and allow dynamic behavior based on stored values.

**Example Script:

#!/bin/bash

Name="Sahil Kamali"
Age=23

echo "The name is NameandageisName and age is NameandageisAge"

ex-2-scr

**Output:

ex-2-scr-op

Global and Local Variables in Bash

In Bash scripting, variables can be global or local depending on where they are declared and where they can be accessed.

Global Variables

A global variable is declared outside any function and can be accessed anywhere in the script, including inside functions.

**Example Script:

#!/bin/bash

total=100 # global variable

showTotal() {
echo "Total inside function: $total"
}

echo "Total outside function: $total"
showTotal

ex-3-scr

**Output:

ex-3-scr-op

Local Variables

A local variable is declared inside a function using the local keyword and is only accessible within that function.

**Example:

#!/bin/bash

showValue() {
local value=50
echo "Value inside function: $value"
}

showValue
echo "Value outside function: $value"

ex-4-scr

**Output:

ex-4-scr-op

Decision Making in Bash

Decision making allows a Bash script to execute different blocks of code based on conditions. This helps scripts behave dynamically instead of running the same commands every time. Conditional statements are essential for automation, validation and logical operations in scripts.

1. If–Else Statement

The if statement evaluates a condition. If the condition is true, a block of code executes. Otherwise, an alternate block runs (if defined).

**Types of If Statements:

**Example: Simple If–Else Script

#!/bin/bash

Age=17

if [ "$Age" -ge 18 ]; then
echo "You can vote"
else
echo "You cannot vote"
fi

ex-1-scr

**Output:

ex-1-scr-op

2. Case Statement

The case statement is used when checking multiple possible values of a variable. It works similar to a switch statement in other programming languages. It is cleaner and more readable than multiple if conditions when handling many cases.

**Example: Case Statement Script

#!/bin/bash

Name="Sahil"

case "$Name" in
"Gulfam") echo "Profession : Software Engineer" ;;
"Sujal") echo "Profession : Web Developer" ;;
"Sahil") echo "Profession : Technical Content Writer Linux" ;;
esac

case-ex-scr

**Output:

case-ex-op

Input and Output in Bash

Input and Output (I/O) are fundamental concepts in Bash scripting. A script can accept input from users, files or other programs and produce output to the terminal or files. Understanding I/O helps in building interactive and automated scripts.

Taking User Input

Bash uses the read command to accept input from the user.

**Example: Reading Input and Handling Files

#!/bin/bash

echo "Enter filename"
read filename

if [ -e "$filename" ]
then
echo "$filename exists in the directory"
cat "$filename"
else
cat > "$filename"
echo "File created"
fi

file-han-scr

**Note: Quotes around "$filename" prevent errors if the filename contains spaces.

**First Execution Output (File Does Not Exist):

file-han-scr-op

**Note:

**Second Execution Output (File Exists)

file-han-scr-op-2

Output Redirection Operators

Bash allows redirecting output using special operators, these operators are useful for logging and error handling in automation scripts.

Functions in Bash

A function in Bash is a reusable block of commands that performs a specific task. Instead of writing the same code multiple times, you can define it once and call it whenever needed. Functions improve script organization, readability and maintainability.

**Example:

#!/bin/bash

myFunction() {
echo "Hello World from GeeksforGeeks"
}

myFunction

fun-ex-scr

**Output:

fun-ex-scr-op

Function Syntax

function_name() {
commands
}

function_name

String and Numeric Comparisons in Bash

Comparisons allow Bash scripts to evaluate conditions and make decisions. Bash supports both string comparisons and numeric comparisons, which are commonly used in conditional statements. Understanding comparison operators is essential for validating input, checking values and controlling script flow.

String Comparison Operators

String comparisons are used to compare text values.

**Example: String Comparison

#!/bin/bash

name="Geeks"

if [ "$name" == "Geeks" ]; then
echo "Strings match"
else
echo "Strings do not match"
fi

str-com-scr

**Output:

str-com-scr-op

**Note: Quotes around variables prevent errors when strings contain spaces.

Numeric Comparison Operators

Numeric comparisons evaluate integer values.

**Example: Numeric Comparison

#!/bin/bash

num=15

if [ "$num" -eq 10 ]; then
echo "Numbers are equal"
else
echo "Numbers are not Equal"
fi

num-com-scr

**Expected Output:

num-com-scr-op

**Combined Example:

#!/bin/bash

if [ 10 -eq 10 ]; then
echo "Equal"
fi

if [ "Geeks" == "Geeks" ]; then
echo "same"
else
echo "not same"
fi

num-str-com-scr

**Expected Output:

num-str-com-scr-op

File Names and Permissions in Bash

When creating a Bash script, proper file naming and execution permissions are essential. Without execute permission, the script cannot run directly from the terminal. Understanding file naming conventions and permissions ensures scripts work correctly and securely.

Script File Naming Convention

A Bash script can technically have any filename. However, by convention, scripts use the .sh extension to indicate that the file contains shell commands. Using standard naming conventions makes scripts easier to identify, maintain and manage especially in large projects or shared environments.

**Recommended Naming Styles

**Note: Using .sh does not make the script executable automatically, it only helps identify the file type.

Execute Permission

In Linux, files must have execute permission to run as programs. When you create a new script file, it is treated as a regular text file and does not have execution rights by default.

If you try to execute it directly:

**Command:

./myscript.sh

You may see:

**Output:

Permission denied

**Note: Linux enforces this behavior for security reasons not every file should be allowed to run as a program.

Giving Execute Permission

To allow the script to run, you must manually grant execute permission using the chmod command.

**Command:

chmod +x myscript.sh

After adding permission, you can execute the script:

**Command:

./myscript.sh

Also Read