Bash Scripting | How to create and run Bash Script?



Bash Scripting is a powerful part of system administration and development used at an extreme level. It is used by the System Administrators, Network Engineers, Developers, Scientists, and everyone who use Linux/Unix operating system. They use Bash for system administration, data crunching, web application deployment, automated backups, creating custom scripts for various pages, etc.


A Bash Shell Script is a plain text file containing a set of various commands that we usually type in the command line. It is used to automate repetitive tasks on Linux filesystem. It might include a set of commands, or a single command, or it might contain the hallmarks of imperative programming like loops, functions, conditional constructs, etc. Effectively, a Bash script is a computer program written in the Bash programming language.



How to create and run a Bash Script?

  • To create an empty bash script, first, change the directory in which you want to save your script using cd command. Try to use text editor like gedit in which you want to type the shell commands.

  • Use touch command to create the zero bytes sized script.

touch file_name  
  • To open the script in the text editor (eg., gedit), type

gedit file_name.sh  

Here, .sh is suffixed as an extension that you have to provide for execution.

  • Type the shell commands for your bash script in the newly opened text window or the text editor. Before typing bash shell commands, first, look at the base of any bash script.


Each Bash based Linux script starts by the line-

#! /bin/bash  

Where #! is referred to as the shebang and rest of the line is the path to the interpreter specifying the location of bash shell in our operating system.


Advantages:

  1. The command and syntax are exactly the same as those directly entered in command line, so programmer do not need to switch to entirely different syntax