Classic shell scripting has been used as a basic platform for many years to automate tasks. This tutorial is an introduction into creating your own custom scripts, with Bash and the command line in mind.
The “linux shell script example” is a tutorial that will teach you how to write your own linux shell scripts. Shell scripts are the most basic and easiest way to automate tasks on Linux.
This Linux shell scripting lesson is for you if you’re using a Linux computer and need to automate Linux shell commands. You’ll learn all you need to know to turn Linux shell scripting into your bread-and-butter with automation in this course.
Let’s get started!
It is important to have a remote SSH host to follow along with this tutorial. This guide is written on an Ubuntu 18.04.5 LTS computer with sudo/administrative privileges.
What is the definition of a shell?
It’s important to know what shell is before diving into shell scripting. A shell is a command language interpreter that runs programs, creates files, and so on using commands received from a standard input device such as a keyboard or a file.
When a user accesses the terminal (a shell’s console), the shell displays a command prompt where you may enter your commands. When you press the Enter key, the input is further processed, and the output is shown on the terminal.
Throughout the shell script process, the kernel interacts with the hardware and software, as shown below.
Workflow using Shell Scripts
The following are the four main types of Unix shells:
- The Bourne Shell (sh) is a command-line shell interpreter for computer operating systems.
- C Shell: C Shell is a Unix shell with a language style that is similar to C.
- Korn Shell: The default shell on many UNIX systems is Korn Shell (aka ksh).
- Bourne-Again Shell: It’s Bourne All Over Again Shell, often known as Bash, is the successor to Bourne Shell, with extra features like as command-line completion, rudimentary debugging, and so on. For most GNU/Linux systems, bash is the default shell environment.
Perhaps you’d like to see a list of all the shells accessible on your Ubuntu system. To do so, open a terminal and type the cat command shown below.
The cat command displays the contents of the /etc/shells file in the example below.
Multiple shells are available, as seen in the output below. You’ll learn how to specify which shell to use when executing a script later.
Viewing All Available Shells
How to Make a Shell Script
You won’t really get what a shell is until you’ve seen a shell script in action. Let’s get started on writing your first shell script. You may start with a simple script that prints messages to the console.
1. Log into your Ubuntu VM with your preferred SSH client or, if you’re already on a Linux system, open a terminal.
2. Use the echo “$SHELL” command to locate the currently active shell.
The output in the picture below says /bin/Bash, which shows that Bash is executing.
Getting a View of the Current Shell
3. Change to the /opt directory and perform the following commands to create a shell script file called my first shell script.sh.
It is suggested that you execute or install your applications or programs within the opt directory due to security considerations.
# Change to the /opt directory using cd opt # Using the vi editor, create a text file called my first shell script.sh.
4. Now save the file my first shell script.sh by copying and pasting the code below.
The shebang (#!) is written in the first line of the script in the script below. The shebang is a string of characters that notifies the kernel which shell to utilize to run the script; in this example, Bash (/bin/bash).
#!/bin/bash echo “Hello World” # Displays the message “Hello World.”
Setting File Permissions to Make a Script Executable
By default, you only have read and write access to the script file when it is created. Only scripts with executable permission will be executed by a shell. As a result, before executing the script you developed, you must first make it executable. If you don’t, you’ll receive an error message that says “Permission refused” when you execute the script.
Users and File Permissions: A Windows Guy in a Linux World
The chmod command below allows you to provide all users (a) executing the script (my first shell script.sh) execute (x) rights.
my first shell script.sh chmod a+x
After you’ve saved your script, you may launch it using any of the ways listed below:
- /bin/bash script.sh or bash script.sh – Specifies the shell to use and runs the script from the current directory.
- By supplying the script’s complete path, bash /$HOME/script.sh– Indicates the shell to use and run the script.
- ./script.sh — Script execution from the current directory
To execute your script in this example, use the command below, assuming your script is in the working directory.
./my first shell script.sh
The script displayed the words Hello World in the console, as seen below.
Printing “Hello World” using a Shell Script
Using Variables Defined by the User
Let’s look at defining variables now that you know how to write and execute a script. Variables are an integral part of any programming language. There are other types of variables in Linux shell scripting, but for this example, we’ll focus on user-defined variables.
Perhaps you don’t want to write the same text or value in a script over and over again. Declaring a user-defined variable saves a value in memory that may be used to replace a string or other value.
The fundamental syntax for defining a user-defined variable is shown below. There should be no spaces before or after the equal (=) operator; otherwise, an error will occur. Why? Because variable name is interpreted by the shell as a command rather than a variable.
The variable name command is not found, as seen in the error message below.
command for variable name not found
Let’s look at how to use variables to replace string outputs.
Copy and paste the script below into a script file, set the script’s executable property like you did before, and execute it.
The year and sitename variables are declared in the code below to contain various sorts of data. It then produces a message in which the year and sitename variables are used to replace strings.
#!/bin/bash # #!/bin/bash # #!/bin/bash year=2020 # Declaring a variable with a numerical value sitename=”adamtheautomator.com” # Declaring a variable with a string value echo “The $sitename website was launched in the year $year.” Printing a string message with the year and sitename variables substituted echo “The $sitename website was launched in the year $year.”
Output from a Shell Script with User-Defined Variables
Working with Variables in the Environment
Environment variables, unlike user-defined variables, may be set system-wide. All shells then have access to the environment variables. For example, a log-generating program may get access to your USERNAME and $HOME directories.
You may establish your own environment variable just like any other variable, but preset environment variables are already set in the Unix shell. By using the env command, you may see a list of preset environment variables and their values.
You’ll see that all of the variables are specified in the variable=values format in the figure below.
The Predefined Environment Variables are listed below.
Let’s have a look at how environment variables are used in scripts.
Create a script file called variables.sh in the /opt directory, then copy and paste the code below into it. Set the script to executable mode and execute it.
You can see how you’re replacing a string with the $PWD environment variable, which points to the current working directory, in the example below.
echo #!/bin/bash “This script is being run from the $PWD Location.”
The script runs from the /opt directory, as seen below.
The script runs in the /opt directory.
Changing the Environment Variable on Your Own
You may also customize your surroundings with your own settings. By default, only the current shell session has access to your own environment variables. However, using the techniques below, you may make environment variables available outside of the current shell session.
Changing the Current Shell’s Environment Variables
Environment variables are only available inside the same shell session in which they were declared by default. Use The export command is a command that allows you to send data to generate a session-specific environment variable, as illustrated below.
The command below creates a VARNAME environment variable with the value of my value.
VARNAME=”my value” is an export variable.
Using.bashrc to Change Environment Variables
The variable will not be exposed to any other script if you only use The export command is a command that allows you to send data within a script like this. Declare an environment variable in your $HOME directory’s.bashrc file to make it accessible globally.
For each session produced, the.bashrc file includes numerous shell configuration parameters. Setting up or enabling coloring, completion, shell history, command aliases, and other features are among the configuration options available.
Open a text editor and type the variable below into the.bashrc file to create global environment variables.
VARNAME=”my value” is an export variable.
To apply the modifications you made to the.bashrc file, use the source command to execute the contents of the file. Then, to output the variable name and value, use the printenv command piped with the grep command.
# source./bashrc Make the modifications to the.bashrc file and save it. grep | printenv # VARNAME Print the value of the environment variable.
Changes to the.bashrc file should be applied, and the Environment Variable’s value should be printed.
Using /etc/environment to Change Environment Variables
The file /etc/environment may also be used to specify system-wide environment variables. The file /etc/environment is designed for system-wide settings, such as the one you’re going to make for yourself.
1. Open The file /etc/environment in your favourite text editor to make changes to the /env/environment file. The nano text editor is used in the example below.
/etc/environment sudo -H nano
2. Set the variable’s value in the /env/environment file as shown below, save it, and you’re done! The variable (VARNAME) is now available to all users and processes at any time.
3. Run The file /etc/environment and observe that the VARNAME variable is there and will be accessible in all future sessions.
source /etc/environment # Update The file /etc/environment with your modifications. grep | printenv VARNAME # Print the value of the environment variable VARNAME.
Changes to /etc/environment should be applied. Save and print the value of the Environment Variable.
Below, you can see a comparison table to understand better the scope of Changing the Environment Variable on Your Owns.
|The export command is a command that allows you to send data||Only the current user in the current shell and processes has access to the environment variable.|
|The.bashrc configuration file||In all subsequent Base sessions and processes, the current user has permanent access to the environment variable.|
|The file /etc/environment||In all Bash sessions and processes, the environment variable is permanently available to all users.|
Special Variables: An Overview
Special variables are similar to regular variables, with the exception that they cannot be assigned values since they are reserved for special purposes. Perhaps you’re attempting to replace strings in a specified sequence. Use specific positional variables to set the location of the strings in such scenario.
Let’s put the positional variables to the test in a script. Copy and paste the script below into a variable.sh script file, make it executable, and execute it.
The code below defines a variable whose value is a string. The string value is then printed, followed by two more strings depending on the specified positional variable.
#!/bin/bash # #!/bin/bash # #!/bin/bash Declares a string value for a variable, then positional variables ($1 and $2). $$$$$$$$$$$$$$$ # with the following strings replacing the positional variables, prints out the string value from fullname variable. $fullname is echoed. Mendiratta Shanky
Using a Variable Position to Print a Substituted String
Check out a couple more unique variables and their functions below.
- $! – Returns the PID of the most recently executed background command.
- $ – Returns the ****PID of the Bash shell itself.
- $1, $2, $3, etc. – Indicates how many positional arguments were supplied in the script.
- $0 – Provides the name of the shell script. specifies the shell script’s name.
- $n – This value corresponds to the parameters used to call a script.
- $? – Displays the ****exit status of the most recently executed command and determines whether or not your Bash script was successfully completed.
- $ – Returns the absolute file name of the shell or Bash script that is being run according to the parameter list.
Using a Shell Script to Get and Set Exit Codes
In Linux, every process terminates with a unique code known as an exit code. Exit codes are numbers that indicate whether a procedure was successful or unsuccessful in some way. You may modify the default exit codes in Bash and create your own.
Exit codes can be read and custom exit codes may be defined in a Bash script. First, let’s look at an exit code. To accomplish so, use the echo command to read the value of the special variable $?
The cat command in the following example attempts to read the contents of a file (myfile.txt) that does not exist. The exit status of the cat command is then printed using the echo command.
#!/bin/bash # #!/bin/bash # #!/bin/bash cat myfile.txt echo myfile.txt myfile.txt myfile.txt myfile.txt myfile.txt myfile.txt myfile.txt myfile.tx #? $? Get the status of the command you just ran.
The returned error message stating that the myfile.txt file does not exist, as well as the exit code, are shown below (1).
Obtaining the Exit Code for the cat Command
Let’s look at how to utilize exit codes to determine if a command executed properly or not with a condition.
The code below attempts to create a directory called mydir but fails due to an error in the command. The $? will not have a success exit value of 0 since the command is invalid. The if statement can be seen checking for an exit code and taking action based on the value of the $? special variable.
#!/bin/bash mdkdhd mydir # If [$? -eq 0], create a directory called mydir. # If the preceding command’s exit status equals 0, then continue. # If the exit status is 0, display the following message: echo “Successfully created mydir directory” exit 0 # Sets the exit code 0 – no further problems discovered # If the exit status is not zero, display the following message: echo “Failed to create directory mydir” exit 127 # Sets the exit code 127 to indicate that a command was not found.
The script failed, as seen below, and provided an error message that reads, “Failed creating mydir directory.”
The mdkdhd command was not found, hence an error message was returned.
Other exit numbers to mention when receiving or altering an exit status are as follows:
- 1 – Detects all common faults.
- 2 – Inappropriate usage of shell built-ins
- 126 – The command that was invoked could not be executed.
- 128 – An invalid argument has been supplied.
- Control-C ended the script at 130.
Using a Shell Function to Execute a Sequence of Commands
You now know how to use the exit status to discover script issues. Let’s write a function in your script without fear of running into problems.
Perhaps you’ve noticed that you’re repeating instructions in your script. In this scenario, a shell function may help you save time and improve the efficiency of your script. A function is a section of code that only runs when it is invoked from inside your shell script.
A shell function’s fundamental code block is shown below. It’s worth noting that you must first specify the function name before writing the set of instructions in curly brackets.
Command 1 # Series of commands Command 2….. function Name of the function () # Declaring the function name
Let’s have a look at a shell function in action.
In the opt directory, create a shell script named Shell function demo.sh, and then copy and paste the script below into it. Set the script to executable mode and execute it.
The script below invokes a function that prints first and last name strings depending on the positional arguments ($1 and $2) replaced values.
newfunction #!/bin/bash function () echo “My First Name is $1,” echo “My Last Name is $2,” echo “My Middle Name is $1,” echo “My Middle Name is $2,” echo “My Middle Name is $1,” echo “My Middle Name is $2 newfunction Adam Candy is a character in the film Adam and
You’ll see that the function produced two separate echo statements with the replaced positional arguments after executing the script.
Shell Function Execution
Using a For Loop to View File Names and Sizes
A for loop, like the function described before, is a code block that performs certain tasks but iterates across a group of objects. The for loop, for example, will execute until it reaches the final file in a directory.
You may want to double-check the size of each file in your working directory. If this is the case, a simple script with a for loop will work.
Let’s look at an example of examining the size of each file in the working directory. To do so, create a script file called looping over file.sh, then copy and paste the code below into it. Set the script to executable mode and execute it.
The following code scans each file in the current directory and outputs its name and size in bytes until all files have been examined.
For filenames in *, use #!/bin/bash. wc -c $filename scans all files (*) in the current directory # Each newline produces a list of file names and a byte count.
Each file size is mentioned below, followed by the name of the file.
Using a For Loop to View All Files and File Size
In a running shell script, requiring user input
So far, you’ve just learnt commands and variables-focused scripts. Advanced projects, on the other hand, often demand users to enter data during runtime. User input data might be anything, such as a username and password in an application that asks for security information.
Let’s look at how to make the shell script demand user input while it’s running.
Create a new script file called user input.sh in the /opt directory, then copy and paste the code below into the user input.sh file. After that, make the script executable and execute it.
The script below prompts the user for a username and password before printing a confirmation message.
#!/bin/Bash # #!/bin/Bash # #!/bin/Bash Prints a message requesting the user’s username and password echo Please fill out the form below. # # (-p) prompts the user for a username to be placed in the uservar variable. uservar # read -p ‘Username:’ # (-sp) silent prompt, characters are not shown Requires a user input for a password stored in the passvar variable ‘ read -sp ‘ passvar #”””” ‘ Echoes a ‘thank you’ message. Thank you for giving your login credentials, $uservar.
As you can see below, the username input is visible, but the password input is not.
In a running script, requiring user input
When a condition is true, you may run code.
A while loop, unlike the for loop, executes code while a condition is true. Maybe you’re building code to output a series of integers that keep increasing. A while loop would be appropriate for running the code in this scenario.
Let’s look at an example to see how the while loop works.
First, open your chosen text editor and create a script file called while loop.sh. To demonstrate how the while loop iterates, print incrementing numbers, save the code below to the script file and execute it.
The code below defines a variable (a) with a value of 100 as its initial value, then increments it by two while the current value is less than 110.
a=100 #!/bin/bash #!/bin/bash #!/bin/bash #!/bin/b Declaring an initial value in a variable # Establishes a condition for running commands within the while loop # when the value is less than 110, do echo $a while [$a -lt 110] do echo $a # Prints the current value a=’expr $a + 2’# Do a two-fold increase in the value.
The numbers are displayed and increased by two once the script is executed, as seen below. Because the condition provided to the while loop raises the value when less than 110 ([$a -lt 110]), the displayed numbers only reached 108.
Printing Incrementing Numbers using a While Loop
Using a Shell Script to Print Colored Output
You’ve probably memorized a few scripts by now. Let’s look at how to adjust the color of a script’s printed output this time.
Maybe you need certain output, like usernames, password prompts, or mistakes, to stand out so you can see them fast. Let’s look at how to use a shell script to modify the color of an output.
Copy and paste the code below into the colored output.sh script file in the /opt directory. Make sure the file is set to executable mode and execute it to watch how the colorful outputs turn out.
The string values in the script below start in e[0;00m format to set the color and conclude in e[0m format to return the color to default.
#!/bin/bash # -e: allows backslash echo -e -e -e -e -e -e -e -e -e -e -e – “e[0;31m e[0;31m e[0;31m e[0m] is red text.” # Prints a red output echo “Using the default color” # Prints a red output echo “Using the default color” echo -e # Prints a default colored output “e[0;33m e[0;33m e[0;33m This is the e[0m yellow text.” # echo -e prints a yellow-colored output “e[0;34m e[0;34m e[0;34m e[0m] is blue text.” # Produces a blue-hued output.
Following the execution of the script, several colored outputs can be seen below.
To view the colorful output, run the script.
If the colors used in the guide aren’t your style, you may simply switch them out for something else, as seen below.
Colors are denoted by color codes, which are as follows:
Brown/Orange 0;33 Yellow 1;33 Blue 0;34 Light Blue 1;34 Purple 0;35 Light Purple 1;35 Cyan 0;36 Light Cyan 1;36 Light Gray 0;37 White 1;37 Red 0;31 Light Red 1;31 Green 0;32 Light Green 1;32 Brown/Orange 0;33 Yellow 1;33 Blue 0;34 Light Blue 1;34 Purple 0;35 Light Purple 1;35 Cyan 0;36 Light
Characters on the Run
String values were encased in double quotes (” “), single (‘ ‘) quotes, and left quotes in the prior scripts (). These quotations are crucial when developing a shell script, however if they are inserted wrong, the script will not operate as intended.
In your string output, you may wish to use double quotation marks. Using the backslash sign in a string to escape a character will work. Except for the or! symbols and variables, the contents of quotations are treated as a string.
Let’s look at how to produce a string using double quotes.
In the /opt directory, create a script file called doublequotes.sh, then copy and paste the script below into it. Set the script to executable mode and execute it.
The code below displays string values using escaped double quotation marks and a value from a variable in the script below.
#!/bin/bash # Declare a variable str1=”Hello, this ATA Blog Site” # Prints the string value from the str1 variable echo $str1 # Declare a string variable str2=”Hello this ATA “Blog Site”” with escaped double quotation marks. # echo $str2 $str2 $str2 $str2 $str2 $str2 $str2 $s # Declare a variable called owner with the string value owner=”Adam” # Declare a string variable str3=”Hello this ATA “Blog Site” by $owner” # Prints the string value from the str3 variable echo $str3
Double quotes are included in the second and third outputs, as you can see below.
Using double quotes to execute the shell script
Using Single Quotes to Print Special Characters in a String
When you use double-quotes to introduce special characters in a string, Bash interprets them and returns their value. But what if you want to use special characters or quotations inside a string? Use single-quotes instead of double-quotes.
If you need to add escape characters or variables in the string, use single quotes to specify them.
Let’s look at how single quotes operate with string values. Save the following code to a single quotes.sh script file and execute it.
In the code below, everything enclosed by a single quotation is considered a string.
#!/bin/bash # #!/bin/bash # #!/bin/bash str1=’Hello this ATA Blog Site’ echo $str1 # Declares a string variable called str1. # Prints the value of the string str1 variable. str2=’Hello this ATA “Blog Site”‘ echo $str2 # Declares a string variable named str2 # with the escape character () as the string str2=’Hello this ATA “Blog Site”‘ The string value from the str2 variable is printed. # Declares owner owner=”Adam” as a string variable. str3=’Hello this ATA “Blog Site” by $owner’ declares a string variable called str3 # with the escape character () and the $owner variable as a string str3=’Hello this ATA “Blog Site” by $owner’ $str3 $echo $echo $echo $echo $echo $ The string value from the str3 variable is printed.
You’ll see that the $owner variable and the escape character () are now written as strings after executing the script.
Using single quotes to run the shell script
Using Left Quotes in a String to Run a Command
Now that you know how to print string values in double and single quotes, you can go on to the next step. Let’s have a look at how left quotes function. Left quotes, unlike double and single quotes, are exclusively used to declare a command inside a string.
You may need to use the date command to print out today’s date as part of a string. In such scenario, printing the date with left quotes is the best choice, regardless of which quotations surround the string value. Let’s have a look at how to put left quotes within a string value.
The date command is included in the script below, and the code defines two variables with strings contained in single and double quotes.
‘Today’s date is’date”, str1=’Today’s date is’date”, str2=’Today’ $str1 $echo $echo $echo $echo $e echo $str1=”Today’s date is ‘date’” str2=”Today’s date is ‘date’”
As you can see in the screenshot below, both string variables had the same result.
Using backticks to execute the shell script
This Linux shell scripting lesson has taught you all you need to know about shell scripting, from the fundamentals through loop execution. You’ve also learned how shell scripts may automate a variety of processes, saving time and making the life of developers considerably simpler.
Now, take your shell scripting talents to the next level by integrating each of the scripts you built in this course to build your own project.
Shell scripting is a programming language that uses the command line to execute commands. In this tutorial, you will learn how to use shell scripting with examples. Reference: in shell scripting.
- bash scripting tutorial pdf
- learn shell scripting in 24 hours pdf
- shell script first line
- linux shell scripting tutorial vivek gite pdf
- shell script if “-s”