- How to write simple shell scripts in Linux
- Table of contents
- Introduction to Shell
- Use different interpreter in script file
- How to provide permission to run script file
- Variables
- Loop statements in bash script
- Condition statements in bash script
- Functions
- Some necessary operators
- Installing packages in Ubuntu
- Wrapping up
- Shell Scripting Tutorial: How to Create Shell Script in Linux/Unix
- What is Shell?
- Types of Shell
- How to Write Shell Script in Linux/Unix
- Adding shell comments
- What are Shell Variables?
- Summary:
How to write simple shell scripts in Linux
In this article, we will learn the most basic knowledge to program with bash script. Understanding them makes us strong into shell scripting.
Table of contents
Introduction to Shell
A Shell is a program that works between us and the Linux system, enabling us to enter commands for the OS to execute.
In Linux, the standard shell is bash — the GNU Bourne-Again SHell, from the GNU suite of tools, is installed in the /bin/sh. In the most Linux distributions, the program /bin/sh, the default shell, is actually a link to the program /bin/bash.
Belows are some shell programs that we can use.
Shell Name | history |
---|---|
sh (Bourne) | The original shell from early version of UNIX |
csh, tcsh, zsh | The C shell, and its derivatives, originally created by Bill Joy of Berkeley UNIX fame. The C Shell is probably the third most popular type of shell after bash and the Korn shell |
ksh, pdksh | The Korn shell and its public domain cousin. Written by David Korn, this is the default shell on many commercial UNIX versions. |
bash | The Linux staple shell from the GNU project. bash, or Bourne Again SHell, has the advantage that the source code is freely available, and even if it’s not currently running on our UNIX system, it has probably been ported to it. bash has many similarities to the Korn shell. |
Use different interpreter in script file
#!/bin/bash echo "Hello, world!" echo "User - $USER, Directory - $HOME"
The #! characters tell the system that the argument that follows on the line is the program to be used to execute this file.
#!/bin/bash or #!/usr/bin/python is known as hash bang, or shebang. Basically, it just tells the shell which interpreter to use to run the commands inside the script.
How to provide permission to run script file
To run our script file, there are two ways:
- Invoke the shell with the name of the script file as a parameter For example, /bin/sh hello-world.sh
- Running our script file by calling its name Before doing it, we need to change the file mode to make the file executable for all users by using the chmod command.
Variables
- The declaration of variables In Linux, we do not need to declare variables in the shell before using them. The easiest way is that when we want to use them, create them such as assigning an initial value to them. By default, all variables are stored as strings, even when they are assigned numeric values. The shell and some utilities will convert numeric strings to their values in order to operate on them as required.
- Access their value To get the the variables’s value, we insert $ symbol before their name. For example:
strHelloWorld="hello world" echo $strHelloWorld
- The behavior of variables inside quotes depends on the type of quotes we use.
- If we enclose a $ variable expression in double quotes, then it’s replaced with its value when the line is executed.
- If we enclose it in single quotes, then no substitution takes place.
- We can remove the special meaning of the $ symbol by prefacing it with a **.
#!/bin/sh str="Hello, world!" echo $str echo "$str" echo '$str' echo \$str
Loop statements in bash script
while [ condition ] do commands done
#!/bin/bash valid=true count=1 while [ $valid ] do echo $count if [ $count -eq 10 ]; then break # continue fi ((count++)) done
for var in do commands done
#!/bin/bash names='Obama Trump Clinton' for name in $names do echo $name done echo 'Done.'
until [ condition ] do commands done
#!/bin/bash counter=1 until [ $counter -gt 5 ] do echo $counter ((counter++)) done
for value in 1..5> do echo $value done
Condition statements in bash script
if [ conditionals ]; then commands fi
if [ conditionals ]; then commands elif [ conditionals ]; then commands else commands fi
#!/bin/bash # $1 means the first command line argument if [ $1 -gt 100 ]; then echo 'Your number is greater than one hundred.' pwd fi date
#!/bin/bash if [ "$1" -gt 100 ]; then echo Hey that\'s a large number if (( $1 % 2 == 0 )) then echo And is also an even number fi fi
#!/bin/bash # use && or || to express boolean operations if [ -r $1 ] && [ -s $1 ] then echo 'This file is existed and can be read.' fi
case in ) commands ;; ) commands ;; esac
case $1 in start) echo 'starting' ;; stop) echo 'stopping' ;; restart) echo 'restarting' ;; *) # * represents any number of any characters. echo 'do not know' ;; esac
Functions
function_name() commands > # or function function_name commands >
- Parameter variables If no parameters are passed, the environment variable $# exists but has a value of 0. Belows are some parameter variables that we need to know.
Parameter variable Description $1, $2, … The parameters given to the script $* A list of all the parameters, in a single variable, seperated by the first character in the environment variable IFS. If IFS is modified, then the way $* seperates the command line into parameters will change. $@ A subtle variation on $*; it does not use the IFS environment variable, so parameters are not run together even if IFS is empty - Pass arguments and return value to function We supply the arguments directly after the function name. In function, we can access the value of arguments by using $1 , $2 , … We will use keyword return to return our something.
print_value() echo "Hello $1" return 10 > print_value world # Use #? contains the return status of the previously run command or function. echo "The returned value from above function is $?" # or value=$( print_value VietNam )
#!/bin/bash calc_tax() local tax_percent=0.1 return $1 * tax_percent > calc_tax 100
Some necessary operators
- Comparation opertor = = used to compare two string != = used to compare two string -eq = check whether the value is equal to something. -ne = not equal -gt = greater than -ge = greater than or equal -lt = less than -n STRING = The length of STRING is greater than zero. -z STRING = The length of STRING is zero. = is slightly different to -eq . [ 001 = 1 ] will return false as = does a string comparison (ie. character for character the same) whereas -eq does a numerical comparison meaning [ 001 -eq 1 ] will return true.
- File operator -d FILE = FILE exists and is a directory -e FILE = FILE exists -r FILE = FILE exists and the read permission is granted. -s FILE = FILE exists and its size is greater than zero -w FILE = FILE exists and the write permission is granted. -x FILE = FILE exists and the execute permission is granted. When we refer to FILE above we are actually meaning a path. Remember that a path may be absolute or relative and may refer to a file or a directory.
Installing packages in Ubuntu
#!/bin/bash # Install Apache if it's not already present if [ -f /usr/sbin/apache2 ]; then sudo apt install -y apache2 sudo apt install -y libapache2-mod-php7.2 sudo a2enmod php sudo systemctl restart apache2 fi
- Check for existence of the apache2 library Use -f option specifies that we’re looking for a file. If we want to check for existence of a directory, use -d option. ! operator — exclamation mark is an inverse, it means we’re checking if something is not present.
- Install packages We can use -y option to omit some confirmation that process’s installing package is required.
- if statement We should close out if statement with the word fi backward — fi . If we forgot to do this, the script will fail.
Wrapping up
- Understanding some basic statements and operators in Bash script.
- Split function into smaller function to help us easily maintainable and readable code.
Shell Scripting Tutorial: How to Create Shell Script in Linux/Unix
Shell Scripting is an open-source computer program designed to be run by the Unix/Linux shell. Shell Scripting is a program to write a series of commands for the shell to execute. It can combine lengthy and repetitive sequences of commands into a single and simple script that can be stored and executed anytime which, reduces programming efforts.
This Shell Scripting tutorial helps to learn a basic understanding of the Linux/Unix shell scripting program to advanced concepts of Shell Scripting. This Shell Script tutorial designed for beginners and professionals who want to learn What is Shell Scripting? How shell scripting works, types of shell, and more.
What is Shell?
Shell is a UNIX term for an interface between a user and an operating system service. Shell provides users with an interface and accepts human-readable commands into the system and executes those commands which can run automatically and give the program’s output in a shell script.
An Operating is made of many components, but its two prime components are –
- Kernel
- Shell
A Kernel is at the nucleus of a computer. It makes the communication between the hardware and software possible. While the Kernel is the innermost part of an operating system, a shell is the outermost one.
A shell in a Linux operating system takes input from you in the form of commands, processes it, and then gives an output. It is the interface through which a user works on the programs, commands, and scripts. A shell is accessed by a terminal which runs it.
When you run the terminal, the Shell issues a command prompt (usually $), where you can type your input, which is then executed when you hit the Enter key. The output or the result is thereafter displayed on the terminal.
The Shell wraps around the delicate interior of an Operating system protecting it from accidental damage. Hence the name Shell.
This Unix/Linux Shell Script tutorial helps understand shell scripting basics to advanced levels.
In this Shell Script tutorial, you will learn-
Click here if the video is not accessible
Types of Shell
There are two main shells in Linux:
1. The Bourne Shell: The prompt for this shell is $ and its derivatives are listed below:
- POSIX shell also is known as sh
- Korn Shell also knew as sh
- Bourne Again SHell also knew as bash (most popular)
2. The C shell: The prompt for this shell is %, and its subcategories are:
We will discuss bash shell based shell scripting in this tutorial.
How to Write Shell Script in Linux/Unix
Shell Scripts are written using text editors. On your Linux system, open a text editor program, open a new file to begin typing a shell script or shell programming, then give the shell permission to execute your shell script and put your script at the location from where the shell can find it.
Let us understand the steps in creating a Shell Script:
- Create a fileusing a vi editor(or any other editor). Name script file with extension .sh
- Start the script with #! /bin/sh
- Write some code.
- Save the script file as filename.sh
- For executing the script type bash filename.sh
“#!” is an operator called shebang which directs the script to the interpreter location. So, if we use”#! /bin/sh” the script gets directed to the bourne-shell.
Let’s create a small script –
Let’s see the steps to create Shell Script Programs in Linux/Unix –
Command ‘ls’ is executed when we execute the scrip sample.sh file.
Adding shell comments
Commenting is important in any program. In Shell programming, the syntax to add a comment is
Let understand this with an example.
What are Shell Variables?
As discussed earlier, Variables store data in the form of characters and numbers. Similarly, Shell variables are used to store information and they can by the shell only.
For example, the following creates a shell variable and then prints it:
variable ="Hello" echo $variable
Below is a small script which will use a variable.
#!/bin/sh echo "what is your name?" read name echo "How do you do, $name?" read remark echo "I am $remark too!"
Let’s understand, the steps to create and execute the script
As you see, the program picked the value of the variable ‘name’ as Joy and ‘remark’ as excellent.
This is a simple script. You can develop advanced scripts which contain conditional statements, loops, and functions. Shell scripting will make your life easy and Linux administration a breeze.
Summary:
- Kernel is the nucleus of the operating systems, and it communicates between hardware and software
- Shell is a program which interprets user commands through CLI like Terminal
- The Bourne shell and the C shell are the most used shells in Linux
- Linux Shell scripting is writing a series of command for the shell to execute
- Shell variables store the value of a string or a number for the shell to read
- Shell scripting in Linux can help you create complex programs containing conditional statements, loops, and functions
- Basic Shell Scripting Commands in Linux: cat, more, less, head, tail, mkdir, cp, mv, rm, touch, grep, sort, wc, cut and, more.