Learning Shell Scripting: A Guide from Newbies to System Administrator

If you’re starting your journey in the world of system administration or want to automate your tasks on Linux, then learning shell scripting is a must. Shell scripting is a powerful way to interact with the operating system and perform tasks quickly and efficiently.

This guide will walk you through everything you need to know, from absolute basics to more advanced scripting concepts that system administrators use every day.

What is Shell Scripting?

At its core, a shell script is a plain text file that contains a series of commands for the shell to execute, and a shell is a command-line interpreter that allows you to interact with the operating system.

In the context of Linux or Unix-like operating systems, the most common shells are Bash (Bourne Again Shell) and Zsh (Z Shell).

Shell scripting allows you to automate repetitive tasks, manage system resources, or even install and configure software. You can think of it as the bridge between the user and the computer’s operating system. When you type commands into the terminal, the shell processes those commands. In scripting, you can bundle those commands together to execute them all at once.

This article will guide you from beginner-level scripting to more advanced uses, specifically tailored for those aiming to eventually become system administrators.

1. The Basics of Shell Scripting

Before diving into writing your first script, it’s essential to understand the basics.

Writing Your First Script

To write a shell script, all you need is a text editor such as nano, vim, or gedit. The first line of every shell script is called the shebang line, which tells the system which interpreter to use to execute the script.

#!/bin/bash

Below the shebang, you can add any commands that you would normally run in the terminal.

For example, to display a message to the user:

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

Save the file with a .sh extension (for example, hello_world.sh).

To run the script, you need to make it executable.

chmod +x hello_world.sh

Once it’s executable, you can run the script with:

./hello_world.sh
Print Hello World
Print Hello World

Congratulations! You’ve just written and executed your first shell script, which is simple, but this is the foundation of all shell scripting.

2. Variables and Input in Shell Scripting

One of the most useful features in shell scripting is the ability to use variables, which store values that can be used later in the script. You can also accept user input and store it in variables.

Declaring Variables

Variables in shell scripting are simple to declare; there are no types like in other programming languages (i.e., integer, string). In scripting, everything is treated as a string by default.

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

This script declares a variable name and stores the value "Alice". The echo command will print “Hello, Alice!” to the terminal.

Declaring Variables in Scripting
Declaring Variables in Scripting

Taking Input from the User

To get input from the user, you can use the read command.

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

Here’s what’s happening:

  • The script prints the prompt “Enter your name:“.
  • The read command waits for user input and stores it in the variable name.
  • The script then prints "Hello, $name!", replacing $name with the input the user gave.
Taking User Input in Scripting
Taking User Input in Scripting

Using Command-Line Arguments

Shell scripts accept arguments from the command line, which are passed to the script when it is run.

#!/bin/bash
echo "Hello, $1!"

Here, $1 represents the first argument passed to the script.

./greet.sh Alice

Will output:

Hello, Alice!

You can access more arguments by using $2, $3, and so on. $0 refers to the script’s name.

3. Control Structures in Scripting

Control structures such as if, for, and while loops allow your scripts to make decisions and repeat tasks.

If Statements

The if statement is used to make decisions in scripts, such as checking whether a directory exists.

#!/bin/bash
echo "Enter a directory name:"
read dir

if [ -d "$dir" ]; then
  echo "The directory $dir exists."
else
  echo "The directory $dir does not exist."
fi

In this script:

  • The -d checks if the directory exists.
  • The script outputs different messages depending on whether the directory exists or not.
Using If Statements in Scripting
Using If Statements in Scripting

Using Loops

Loops are useful for repeating actions multiple times.

For Loop:

The following loop runs 5 times and prints the iteration number each time.

#!/bin/bash
for i in {1..5}
do
  echo "This is loop number $i"
done

While Loop

The while loop will continue running as long as the condition is true.

#!/bin/bash
counter=1
while [ $counter -le 5 ]
do
  echo "This is loop number $counter"
  ((counter++))
done
Using for Loops in Scripting
Using for Loops in Scripting

4. Working with Files and Directories

One of the most common uses of shell scripting is automating file and directory operations, such as creating files, moving files, or checking file permissions, making shell scripts extremely useful for handling these tasks.

Creating Files in Linux

You can use the touch command to create a new, empty file:

#!/bin/bash
touch newfile.txt

Moving and Renaming Files

To move or rename a file, you can use the mv command:

#!/bin/bash
mv newfile.txt oldfile.txt 

Checking File Permissions

You can check file permissions using the ls command:

#!/bin/bash
echo "Enter the filename:"
read file
ls -l $file

5. Advanced Concepts for System Administrators

As you become more experienced with shell scripting, you’ll start using more advanced concepts. These are particularly useful for system administrators who need to manage servers, configure services, and handle complex tasks.

Using Functions in Scripting

Functions in shell scripts allow you to group code together for reuse, making your scripts cleaner and easier to maintain.

#!/bin/bash

function greet {
  echo "Hello, $1!"
}

greet "Alice"
greet "Bob"

This script defines a function greet that takes one argument and prints a greeting. It’s called twice, once with “Alice” and once with “Bob.”

Error Handling in Scripting

Error handling is crucial for robust scripts, especially in a system administration context. You can check if a command was successful by checking the $? variable, which stores the exit status of the last command run.

#!/bin/bash

echo "Attempting to create a directory..."
mkdir /some/directory

if [ $? -eq 0 ]; then
  echo "Directory created successfully."
else
  echo "Failed to create directory."
fi

In this script:

  • The $? checks the success of the mkdir command.
  • If the command was successful ($? -eq 0), it prints a success message; otherwise, it prints an error message.
Using Advanced Concepts in Scripting
Using Advanced Concepts in Scripting

6. Scheduling Tasks with Cron

As a system administrator, you’ll often need to run scripts at scheduled times, and the cron utility allows you to automate this by running scripts at specific intervals; here’s how to set up a cron job:

Open your crontab file for editing by running:

crontab -e

Add a line specifying the schedule and the script to run every day at 3 AM.

0 3 * * * /path/to/your/script.sh

The syntax for cron jobs is:

minute hour day month weekday command

This command tells cron to run the script at 3:00 AM every day.

Conclusion

Shell scripting is an essential skill for anyone working with Unix-like systems, especially for those considering a career in system administration, as it allows you to automate tasks and simplify workflows by learning the basics such as variables, loops, conditionals, and file management – while also advancing to more complex topics like functions, error handling, and cron task scheduling.

Whether you’re managing a web server, automating backups, or writing system configuration scripts, mastering shell scripting will save you time, reduce errors, and make you a more efficient system administrator. So, keep experimenting, writing scripts, and most importantly, have fun with it!

Ravi Saive
I am an experienced GNU/Linux expert and a full-stack software developer with over a decade in the field of Linux and Open Source technologies

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

9 Comments

Leave a Reply
  1. Hi Team,

    I need to get the exact telnet output without any manual intervention

    -bash-4.2# echo exit | telnet localhost 22
    Trying ::1...
    Connected to localhost.
    Escape character is '^]'.
    Connection closed by foreign host.
    
    
    
    -bash-4.2#  telnet localhost 22
    Trying ::1...
    Connected to localhost.
    Escape character is '^]'.
    SSH-2.0-OpenSSH_7.4
    ^]==========
    

    Here when use telnet localhost 22 - SSH-2 OpenSSH_7.4 is showing , but in echo exit | telnet localhost 22 it's not showing

    Output : 
    bash-4.2# echo exit | telnet localhost 22
    Trying ::1...
    Connected to localhost.
    Escape character is '^]'.
    Connection closed by foreign host.
    telnet> quit
    Connection closed.
    -bash-4.2#
    
    Reply
  2. Hi, I have written a script with four commands. These four commands are taking backup of my servers. But when the script is running it’s taking so much RAM So that I want to RUN these commands one by one but the script file is one. is it possible?

    Reply
    • @Kundan,

      Instead using script, try to add individual commands to the cron jobs and run them specific time. This way you can keep your Linux server performance to stable..

      Reply
  3. Please think of this part of the title, “A Guide from Newbies to System Administrator.” Is this guide written by newbies for system administrators? I am sorry for bringing this to your notice, but I thought you might want to correct it.

    Reply

Got Something to Say? Join the Discussion...

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.