This post will guide you how to run shell scripts from the command line in your Linux operating systems. How to create and execute a simple shell or bash script in Linux.
What is Shell Script
A shell script is a computer program designed to be run by the Unix shell, a command line interpreter. The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file manipulation, program execution, and printing text.
Create a Simple Shell Script
You need to create a shell script with your vi/vim text editor, then you need to add some commands and echo statements into the file. For example, you want to create a shell script named myshell.sh in your current working directory, you type the following command:
$ sudo vim myshell.sh
Then adding the following shell codes:
#! /bin/bash echo "this is the first bash shell script\n" df -h
save and close the file.
Note: the first line is called a shebang or a bang line in shell script. when a text file with a shebang is used as if it is an executable, the program loader mechanism parses the rest of the file’s initial line as an interpreter directive.
Executing Shell Script
To run the above shell script myshell.sh file, and you need to navigate to the directory where the file you just saved. and you need to set executable permission to your shell script file with the following chmod command, type:
$ sudo chmod u+x myshell.sh
then you can execute your shell scripts with the following command:
$ sudo ./myshell.sh
or
$ bash myshell.sh
Outputs:
[devops@mydevops ~]$ sudo chmod u+x myshell.sh [devops@mydevops ~]$ sudo ./myshell.sh this is the first bash shell script\n Filesystem Size Used Avail Use% Mounted on devtmpfs 648M 0 648M 0% /dev tmpfs 663M 0 663M 0% /dev/shm tmpfs 663M 9.4M 654M 2% /run tmpfs 663M 0 663M 0% /sys/fs/cgroup /dev/mapper/cl_mydevops-root 41G 4.5G 36G 12% / /dev/mapper/cl_mydevops-home 20G 299M 20G 2% /home /dev/sda1 976M 133M 777M 15% /boot tmpfs 133M 28K 133M 1% /run/user/42 tmpfs 133M 3.5M 130M 3% /run/user/1000 [devops@mydevops ~]$ bash myshell.sh this is the first bash shell script\n Filesystem Size Used Avail Use% Mounted on devtmpfs 648M 0 648M 0% /dev tmpfs 663M 0 663M 0% /dev/shm tmpfs 663M 9.4M 654M 2% /run tmpfs 663M 0 663M 0% /sys/fs/cgroup /dev/mapper/cl_mydevops-root 41G 4.5G 36G 12% / /dev/mapper/cl_mydevops-home 20G 299M 20G 2% /home /dev/sda1 976M 133M 777M 15% /boot tmpfs 133M 28K 133M 1% /run/user/42 tmpfs 133M 3.5M 130M 3% /run/user/1000 [devops@mydevops ~]$
Conclusion
You should know that how to create and run a shell script from the command line on your CentOS or RHEL Linux system.