DEV Community

Cover image for BASH(Shell) Scripting 101
Prashant Pal
Prashant Pal

Posted on

3

BASH(Shell) Scripting 101

Let's Start 🚀

In this blog, I’ll be explain the basics of Bash scripting—a powerful tool for automating tasks and managing system operations. Well this is what I learned but I try my best to explain it here.📚

When we write commands in a file, and we use that file to execute, thus making it moveable that file is called shell script. It has .sh extension 📂.

Advantages Of Shell Scripting🌟

  1. You can avoid repetitive work.🔄
  2. You can keep history of configuration.📜
  3. Share the instructions.🤝
  4. You can handle logic and bulk operations.⚙️

There are different shell implementation:-

  1. sh:- Bourne Shell /bin/sh 🐚
  2. Bash:- Bourne again shell /bin/bash. Bash is a shell program. Bash is a programming language.💻

Shebang

Shebang line is used to tell which language you would use. You need to write it in your file in order to use it. Syntax to write shebang line :- #!/bin/bash for eg. here I use bash.📜

To run the file we use,

./filename.sh
Enter fullscreen mode Exit fullscreen mode

But this will not execute because you have no permission to execute, and now we will use our permission knowledge to give permission to that file. I have mentioned in my previous blog how to give permission to a file take a reference from there. And don't forgot to use sudo.🔑

Now make some variables. It is similarly to other programming languages. Here is the syntax:-

variable_name=value
Enter fullscreen mode Exit fullscreen mode

To use the variable type $variable_name. To store the output of a command in a variable use variable_name=$(command).📦

Conditionals⚖️

You all are familiar with conditional statements while learning programming language.

  1. if :- Syntax for using if [..built_in_commands..]
  2. else :- Syntax for using else ....

if statement

You see there is then when you write condition in if statement next step is to set instructions for that we use then then type something. After that we use else. And at the last we use fi to close the statement.

Operators⚙️

In bash there are different types of operators:-

  1. Arithmetic Operators:- Basic mathematics operators, similar to other programming languages (+,-,*,/ etc). I think its pretty basic.

  2. Relational Operators:- These are used for comparisons. There are various types:-

-eq Equal to
-ne Not equal to 
-lt Less than
-le Less than or equal to 
-gt Greater than
-ge Greater than or equal to
Enter fullscreen mode Exit fullscreen mode
  1. String Operators:- These are for strings.
= Equal
!= Not Equal 
-z String is null
-n String is not null
Enter fullscreen mode Exit fullscreen mode
  1. File Test Operators:- These are used to test various properties associated with a file.
-e Checks whether file exist or not 
-d Checks whether file is a directory
-f File is a regular file
-r Checks whether file is readable
-w Checks whether file is writable
Enter fullscreen mode Exit fullscreen mode

There are other operators too but I thinks these are the most common till now.

Passing Parameters📨

Well in simple words, when you type something in CLI then it can be used inside the bash scripts. And to make this possible we use $ sign.

$ sign:- So this starts from 0 to 9 and uses special character too.

$0 Basically used for naming
$1-$9 These are used to store the passed i/p at CLI
$@ Represent all the parameter passed to the script
$* Represent all the argument in a single string 
$# Represent total number of arguments provided
Enter fullscreen mode Exit fullscreen mode

There are other advance method too, you can learn them but its better when you need to use them.

Loops🔄

Similar to programming languages there are different types of loops. For example:- while, for, until, select.

1.For Loop:- Syntax of for loop:-

For Loop

Output

For Loop O/p

In syntax you notice do and done. Do indicates that execute the commands until the condition is satisfies, and done indicates that loop is over.

Note:- For arithmetic operators use double brackets (()). And while creating your .sh file don't forgot to give your file necessary permissions.🔑

2.While Loop:- Syntax of while loop:-

While loop

The do and done have the exact same function as in for loop.

3.Until Loop:- Opposite of while loop. Syntax of until loop:-

until [ condition ]; do
    # Commands to be executed
done

Enter fullscreen mode Exit fullscreen mode

4.Select Loop:- It creates a simple list from the given options. Syntax of select loop:-

select var in list; do
    # Commands to be executed
done

Enter fullscreen mode Exit fullscreen mode

Functions

We use functions in every programming languages, and here it is same work as in other languages. Better overview of codes, reuse code again, etc.

Syntax of functions:-

function name_function {
----logic----commands---
}
Enter fullscreen mode Exit fullscreen mode
name_function(){
---logic---commands---
}
Enter fullscreen mode Exit fullscreen mode

How to call a function, its simple type the function name for example:-

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

greet "Prashant"

Enter fullscreen mode Exit fullscreen mode

And the same example can be used to show how to pass the values to a function.

To return the value in a function we use $?, it holds the return value of the function or last executed command.

Resources📚

  1. Refer to this site to deepen your knowledge in bash. But as I say always don't learn whole at one go, learn as you grow/move.🌱https://www.javatpoint.com/bash-introduction

  2. For revision https://www.youtube.com/watch?v=I4EWvMFj37g.

  3. You can refer for more topics like AWK Arrays SED etc https://www.youtube.com/watch?v=tK9Oc6AEnR4

Note:- AWK is important just watch it.👀 I have seen some interviews where interviewer asks about AWK command. So just watch it. It is easy topic.

What I've Learned About Bash: A Beginner's Perspective🌟

Learning the basics of Bash scripting has been an exciting journey, and I hope this blog helps you on your own path. While there's always more to discover, mastering these fundamentals is a great start. 🚀

In my next blog, I’ll explore environment variables, how to create them, networking concepts, and SSH.🌐

Feel free to share your thoughts or questions in the comments—I’d love to hear about your experience!💬

This blog is also on hashnode, you can check it out.
https://prashantsdevlog.hashnode.dev/

Image of AssemblyAI tool

Transforming Interviews into Publishable Stories with AssemblyAI

Insightview is a modern web application that streamlines the interview workflow for journalists. By leveraging AssemblyAI's LeMUR and Universal-2 technology, it transforms raw interview recordings into structured, actionable content, dramatically reducing the time from recording to publication.

Key Features:
🎥 Audio/video file upload with real-time preview
🗣️ Advanced transcription with speaker identification
⭐ Automatic highlight extraction of key moments
✍️ AI-powered article draft generation
📤 Export interview's subtitles in VTT format

Read full post

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay