DEV Community

Cover image for Introduction to Bash Scripting
Meghana N
Meghana N

Posted on

Introduction to Bash Scripting

Bash scripting is a powerful tool for automating tasks in Unix-based systems like Linux and macOS. Whether you're a beginner or an experienced developer, learning Bash can help you streamline repetitive tasks and enhance your command-line productivity.This is a foundational guide that offers a glimpse into a vast and intricate ocean of BASH SCRIPTING!

  1. Getting Started with Bash Scripting

1.1 What is Bash?

Bash (Bourne Again Shell) is a command-line interpreter that allows users to interact with the operating system through commands and scripts. A Bash script is simply a file containing a series of commands.

1.2 Creating and Running a Bash Script

Open a terminal and create a new file:

nano myscript.sh

Add the following lines:

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

#!/bin/bash is the shebang, which tells the system to use Bash for execution.

echo prints text to the terminal.

Save and exit (CTRL + X, then Y, then Enter).

Make the script executable:

chmod +x myscript.sh

Run the script:

./myscript.sh

Output:

Hello, World!

  1. Variables and User Input

2.1 Using Variables

#!/bin/bash
name="John"
echo "Hello, $name!"

Variables store data (name="John").

$name accesses the value.

2.2 Reading User Input

#!/bin/bash
echo "Enter your name:"
read user_name
echo "Hello, $user_name!"

read gets user input.

str1="Harry"
echo ${str1^} - prints everything in lower case
echo ${str1^^} - prints everything in upper case

#for single line comment
: ' --lines ' multiline comment

args=("$@") #for unlimited input

  1. Conditionals and Loops

3.1 If Statements

#!/bin/bash
echo "Enter a number:"
read num
if [ $num -gt 10 ]; then
echo "Number is greater than 10"
else
echo "Number is 10 or less"
fi

-gt means greater than.

3.2 Loops

For Loop

#!/bin/bash
for i in {1..5}; do
echo "Number $i"
done

While Loop

#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done

  1. Functions in Bash

#!/bin/bash
greet() {
echo "Hello, $1!"
}

greet "Adam"

$1 is the first argument (Adam).

  1. File Handling

5.1 Writing to a File

#!/bin/bash
echo "This is a test" > output.txt

writes to output.txt.

5.2 Reading a File

#!/bin/bash
cat output.txt

cat displays the file contents.

  1. Advanced Bash Scripting Techniques

6.1 Command-Line Arguments

#!/bin/bash
echo "Script Name: $0"
echo "First Argument: $1"

Run:

./script.sh hello

Output:

Script Name: script.sh
First Argument: hello

6.2 Error Handling
#!/bin/bash
if [ ! -f myfile.txt ]; then
echo "Error: File does not exist!"
exit 1
fi
exit 1 exits with an error code.

  1. Additional Resources

For more in-depth learning, check out these resources:
Bash Official Documentation - http://www.gnu.org/software/bash/

Linux Command Line Basics - https://www.linux.org/forums/#linux-tutorials

Top comments (0)