Technology / Programming

How to Craft Your First Linux Shell Script

To script or not to script? That is the question.

Linux-Shell-Scripting-Factors-Blog
Follow us
Published on September 12, 2023

Imagine scheduling your daily reports, system checks, and emails to land in your manager’s inbox before you even finish your first cup of coffee in the morning. With scripting, you can. 

Let’s look more at how you can learn this vital skill in Linux and the basics to start writing your own Linux shell scripts.

Why Learn Linux Shell Scripting?

When you script, you take manual processes and commands and turn them into automations. Then, once your scripts are paired with a scheduler like Linux’s Cron system, you end up with an automation that runs like clockwork without human assistance.

Scripting will make your life much easier if you have to perform repetitive tasks, saving time to work on more important things. Think of automation like cruise control for IT pros.

The Whole Shebang

When you build a script, you must start it with a line of code called a shebang (#!/bin/bash). All this line of text does is tell the Linux system that it needs to use a specific interpreter (a program to interpret and execute code command instructions) if it will run the script correctly because different interpreters differ quite a bit in how they operate. 

In our example, the value /bin/bash tells the system that the script should use the Bash shell to execute this script. Different shells like Korn or C shell require different shebangs like #!/bin/ksh or #!/bin/csh, respectively. 

Adding Comments to Your Scripts

Comments in shell scripting start with a #. The shell ignores anything following this symbol on a line. It is not executed, so you can type in just about anything, including messages to help others understand your code, called comments. 

Comments are a vital part of any script, as they allow you to leave notes and explanations about what your code is doing. This is especially useful for complex scripts or when others need to understand or maintain your code after you no longer work at the company where you wrote the script.

Executing Commands

Running scripts sometimes means you must have a command or two run at certain times of the day or when certain conditions are met on your system. Commands in shell scripts are the same as the ones you would use in the command line interface. One of the best examples of a command that you can run in Linux Bash scripting is echo

Echo is used to print out text or the value of variables, which is very useful when scripts run. Other useful commands are ls, which lists the contents of a directory, and cd, which changes the current directory. Each command should be on a new line or separated by a semicolon within your script so that the system knows multiple commands will be executed within the script.

Creating Your First Linux Shell Script

Follow these directions to create your first shell script.

  1. Open your favorite text editor or compiler, for example, VS Code for Linux or a notepad-like editor in Linux. Nano and VIM are also command-line text editors that you can use if you wish. The code looks like this:

#!/bin/bash
echo "Hello, world!"
  1.  Once you have the text in your document, save it as a .sh extension, with an easy-to-remember name like 'hello_world.sh'.

  2. Most Linux systems are locked down for security reasons, and depending on your user permissions, you might need to make some changes to the file before it runs. To make the script executable, run 'chmod +x hello_world.sh'.

  3.  Once that is done, you will be ready to run or execute your newly made script. Simply type './hello_world.sh' into the command line and watch it work.

  4. A simple ‘Hello, world!’ text message should appear, and you have written your first script!

Variables

Variables store data, like a placeholder that keeps a value for our script. 

They are declared by simply assigning a value to a name, and there should be no spaces around the = sign. To access the value of a variable, prepend the name with a $. Here is an example of a script that uses all the elements that we are covering in this article: shebang, comments, variables, and commands:

#!/bin/bash
# Ask the user for their name
echo "What is your name?"
read name # Capture user input
echo "Hello, $name!"

Control Structures

In your scripts, you may need to add the ability to make choices, which gives your script the power of decision-making. The most common of these control structures that you will start with is the if else statement. 

Consider this scenario: You need to determine if there is enough space on a hard drive. Your script checks a condition with if. When the if statement returns a false response, the else control kicks in, triggering that part of the script. 

Below, you’ll see a comment above every line in this script so you can see what each line of code is doing. (They are the green text comments with a hash symbol in front of them.) Here’s a simple example script below:

#!/bin/bash
#Let's check how much space there is on the hard drive and save it to a variable called space.
space=$(df / | grep / | awk '{ print $4 }')
#We then convert the value to GB and check if it's less than 10.
space=$(($space / 1024 / 1024)) 
#Let's start our conditional statements! 
#If the value of space is less than 10, we'll print a message saying that we're running low on space. 
if [ "$space" -lt 10 ]

then

#We'll use echo to print a message to the console.
    echo "Uh oh, we’re running low on space! Only $space GB left."
#Otherwise, we'll print a message saying that there's enough space.

else

#echo is short for echo message. It's how we print messages to the console.
    echo "We have enough space. We have $space GB left."
#fi is short for finish. It's how we end our conditional statements.

Simply save that script as a file with the .sh extension and then you can run it for yourself on a Linux system. These control structures follow a specific syntax and use keywords like if, then, else, elif, fi, for, do, done, while, and until.

Understanding the Command Line Interface (CLI)

To run Linux scripts, you must run them from the Command Line Interface (CLI) or the Terminal. Learning how to navigate the Linux Shell or Terminal is one of the most fundamental things for a Linux user to understand and is essential to use the Linux OS in a non-graphical mode. 

Linux shell scripting requires you to understand how file structures in Linux work, how to start and stop daemons (services), and how to execute and terminate commands, among other things. 

Almost everything you need for scripting revolves around the CLI, so you must ensure that your Linux knowledge is at a point of understanding before attempting to write any advanced scripts. 

Conclusion

Mastering Linux shell scripting is a journey that requires patience and consistent practice, and you are never really and truly done with learning on your scripting journey. Shell Scripting pays off by teaching you valuable automation skills and how the Linux system works via the command line interface. 

Remember, shell scripting might initially seem intimidating when you get started, but by breaking scripts down into manageable bite-sized sections, you can step through each part of your script and learn about the inner workings of each of your new creations.

Like any language, the key to mastering Linux shell scripting is practice and consistency. Ready to take your Linux skills to the next level? Take our Everything Linux Online Training online training. Or take this one to build your bash scripting skills. 

Not a CBT Nuggets subscriber? Create your account now.


Download

By submitting this form you agree to receive marketing emails from CBT Nuggets and that you have read, understood and are able to consent to our privacy policy.


Don't miss out!Get great content
delivered to your inbox.

By submitting this form you agree to receive marketing emails from CBT Nuggets and that you have read, understood and are able to consent to our privacy policy.

Get CBT Nuggets IT training news and resources

I have read and understood the privacy policy and am able to consent to it.

© 2024 CBT Nuggets. All rights reserved.Terms | Privacy Policy | Accessibility | Sitemap | 2850 Crescent Avenue, Eugene, OR 97408 | 541-284-5522