Bash Scripting Basics

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Bash, short for “Bourne Again SHell,” is a widely used command-line interpreter and scripting language in the Unix and Linux environments. Shell scripts written in Bash can perform a wide range of tasks, such as file manipulation, system administration, data processing, and more. The scripting capabilities of Bash make it a valuable tool for both system administrators and casual users looking to streamline their workflows. From this writing, you will learn the Basics of Bash scripting.

What is Bash script?

A bash script is essentially a text file containing a series of commands. Thus, bash scripting is the process of creating and running scripts using the Bourne Again Shell (Bash) programming language. Any series of terminal commands can be organized into a Bash script in a text file with a .sh extension, then executed in that order. The shell executes the commands in the scripts sequentially.

Check out more about Bash Scripts from ‘What is Bash Scripting’.

Why Need Bash Scripting?

Bash scripting is a valuable skill for system administrators, developers, and basically anyone working with Unix-like systems. As, it can be used in automation, customization, scheduling and cron Jobs, file and data manipulation, etc. For example, if a user intended to create a file 100 times using a modular naming convention, doing so manually would take longer. Writing a script can save time in this situation because it can be executed quickly and finish the job.

Now that you know what is a Bash script. Next, check out the following writing on how you can write, execute & run any bash script file:

1. Writing a Bash Script

To begin writing a Bash script, open a text editor and create a new file with the “.sh” extension. This extension is commonly used to indicate that the file contains a Bash script. At the start of your script, it is important to include the “shebang” line.

Below read out each of these steps of writing a Bash script in a little more detail:

To learn more about writing a Bash script, please go through ‘Writing Bash Script’.

A. Choose a Preferable Text Editor

To write a Bash script, first, you have to select a text editor. Then write your intended code utilizing proper syntax on the text editor. Now, there are plenty of text editors for Bash scripting.

Some available text editors for Bash script writing are Nano, Vim, and GNU Emacs.

B. Add ‘Shebang’ as First Script Line

Shebang (#!) is used in a Bash script of the Linux operating system to specify the interpreter that should be used to execute the script. It is always the first line of the script and has the following format:

#! /bin/bash

Learn everything about shebang from ‘An Ultimate Guide to Bin Bash Script and Shebang’.

C. Naming Convention in Bash

The naming convention in Bash scripts is not strictly enforced, but following a consistent naming convention can make your scripts more readable and maintainable. For that, Bash scripts typically use the “.sh” extension to indicate that they are shell scripts. For example, ‘script.sh’.

D. Save the Bash Script File

After successfully writing a bash script with shebang as the first line & setting the perfect name for the bash file (script_name.sh), next, save the file in a chosen directory. Make sure to save it in a location from where you intend to run it from.

2. Executing a Bash Script

Enabling the execution of Bash script files is a necessary step for running your Bash programs effectively as they aren’t executable by default. Below read out each of these steps of executing a Bash script in a little more detail:

To learn more about executing a Bash script, please go through ‘Executing Bash Script’.

A. Add Executive Permission

By default, when you create a file in Bash, it does not have the executable permission set. So as the initial step to execute a script or program, you must make it executable by adding executable permission. Otherwise, attempting to execute a non-executable file will result in a “permission denied” error.

Now, the command that is used to add any kind of permissions to any files is the chmod command, & that is no exception for the bash scripts too. And to add the executable permission for a user for any bash script file, use the general command syntax:

chmod u+x script.sh

B. Run the Bash Script File

Running an executable Bash script file is the final process of getting the desired work done through Bash scripts. And for that, Bash provides various methods to run executable scripts, offering convenience to users. You can run a Bash script by using both GUI & CLI.

With the graphical interface, you can run an executable script file just by right-clicking on it & selecting ‘Run as a Program’ from the context menu.

For the command line interface, you can use several commands such as sh, bash, source (or, dot (.)) to execute or source a script. Moreover, you can also run a script just by specifying its path location.

Learn each of the methods, to run a bash script from ‘How to Run a Bash Script’.

3. Bash Script Applications

A powerful scripting language Bash allows you to interact with the operating system, automate tasks, and perform various system-related operations. Bash script applications are numerous and they can be used in performing various tasks. Check out the following application types:

To learn more Bash script practical applications, please go through ‘Bash Script Examples’.

Types of Bash Script Applications

Here are some common types of tasks that you can perform by executing bash scripts:

  1. Automation You can automate recurring tasks and processes using bash scripting. By doing this, users can save time while lowering the possibility of manual error. For example, you can write scripts for sending out an email, printing out your system’s date & time every hour, or clearing out history every 15 days automatically.
  2. File & Text Processing Bash scripts allow you to manipulate files, read from files, search for patterns, and perform various text-related operations.  Such as reading & writing files, text searching & filtering, counting & summarizing, copying & pasting texts, sorting & formatting, file comparison, moving to a different location, etc.
  3. System Administration In order to update and configure systems, monitor running systems, and distribute software patches and updates, administrators rely on the Bash script. We can use Bash scripts to list system users, read system passwords from a user, check the Ubuntu version, update software, and many more.
  4. Troubleshooting Bash scripting can be used to troubleshoot systems by inspecting system configurations and network connections.
  5. Data Processing It is handy in processing and manipulating data, such as parsing CSV files, extracting information from structured text, performing calculations, and generating reports.
  6. Log Analysis Bash scripting provides powerful tools for parsing and analyzing log files. Scripts can extract relevant information, generate reports, and alert administrators about specific events or errors. Such as we can create bash scripts to output errors saved to a file.
  7. Backup & Restore Commands like cron can be used to schedule tasks like creating reports or running system backups that need to be done on a regular basis.

Sample Bash Script Example

Here, I will give a sample Bash script example (from writing to executing) for you to understand the entire Bash script basics clearly. Please go through the following steps:

Steps to Follow >

➊ At first, open your Ubuntu Terminal application.

➋ Now, go to any of your text editors. Here, I will open my nano editor just by typing the below command:

nano

Open nano editor➌ After that, the nano editor will pop up. There write your script lines. Here, I will write a simple script just to show you. You can also copy my script:

#! /bin/bash

echo “Hello World!”

EXPLANATION
The first line, ‘#! /bin/bash’ starts with shebang or hashbang (#!). It indicates the interpreter to be used for executing the script, in this case, it’s bash. Next, the echo command holds a message, ‘Hello World!’, which will later be displayed upon the execution of the script.
Scripting a basic bash script ➍ Then, press CTRL+O to write out the file name with ‘.sh’ extension (let’s name our script test.sh) & save the file. And press CTRL+X to exit the nano editor.Saving the bash script ➎ Next, write the following command & press ENTER to add executable permission to your script.

chmod u+x test.sh

EXPLANATION
  • chmod: Changes the permission of files and directories.
  • u+x: Argument with chmod command to add the executable permission for the user.
  • sh: File which you want to make executable.
Adding executive permission to the bash script ➏ Now that, I have added the permission, now let’s run the script using the following command:

./test.sh

NOTE: Here, I am running the script just by specifying its path (‘./’ is indicating the script is in the current directory). You can also run the script by command syntaxes, ‘sh test.sh’, ‘bash test.sh’, ‘source test.sh’, etc.
Executing the basic bash scripting example The script runs successfully & displays the output message (Hello!).

Conclusion

To sum up, Bash Scripting is a powerful scripting language for users to automate tasks, and handle systems more efficiently. By learning this language, users can enhance productivity and skillfully use the potential of the command-line interface. Hope you can get the basics of Bash scripting with this article!

People Also Ask

How can I learn bash scripting?
To learn Bash scripting, first understand the basics of Bash, such as commands, variables, loops, functions, etc. After that, use online tutorials & resources, read Bash GNU Manual, and finally set the Unix-based operating system (Ubuntu, Fedora, etc.) to start practicing.

What is bash basics?
Bash, short for “Bourne Again SHell,” is a widely used command-line interpreter and scripting language in the Unix and Linux environments. Shell scripts written in Bash can perform a wide range of tasks, such as file manipulation, system administration, data processing, and more.

What is basic Bash script format?
The basic Bash script format consists of a series of commands and statements written in a text file, which can be executed in the Bash shell. The first line of a Bash script always starts with a shebang (#!). After that, comes comments, statements, variables, defined functions & finally the exit status. 

What is the basics of scripting?
Scripting is the process of writing computer programs or scripts that automate tasks, perform specific functions, or solve problems. Scripting is typically done using scripting languages, which are high-level programming languages for ease of use and quick development. Some of these languages are Bash, Python, JavaScript, Powershell, etc.

Related Articles


<< Go Back to Bash Scripting Tutorial

5/5 - (1 vote)
Monira Akter Munny

Hello!! This is Monira Akter Munny. I'm a Linux content developer executive here, at SOFTEKO company. I have completed my B.Sc. in Engineering from Rajshahi University of Engineering & Technology in the Electrical & Electronics department. I'm more of an online gaming person who also loves to read blogs & write. As an open-minded person ready to learn & adapt to new territory, I'm always excited to explore the Linux world & share it with you! Read Full Bio

Leave a Comment