- 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
- Bash Script : what does #!/bin/bash mean? [duplicate]
- 3 Answers 3
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.
Bash Script : what does #!/bin/bash mean? [duplicate]
In bash script, what does #!/bin/bash at the 1st line mean ? UPDATE: Is there a difference between #!/bin/bash and #!/bin/sh ?
3 Answers 3
That is called a shebang, it tells the shell what program to interpret the script with, when executed.
In your example, the script is to be interpreted and run by the bash shell.
Some other example shebangs are:
#!/bin/sh — Execute the file using sh, the Bourne shell, or a compatible shell #!/bin/csh — Execute the file using csh, the C shell, or a compatible shell #!/usr/bin/perl -T — Execute using Perl with the option for taint checks #!/usr/bin/php — Execute the file using the PHP command line interpreter #!/usr/bin/python -O — Execute using Python with optimizations to code #!/usr/bin/ruby — Execute using Ruby
and a few additional ones I can think off the top of my head, such as:
In a script with the bash shebang, for example, you would write your code with bash syntax; whereas in a script with expect shebang, you would code it in expect syntax, and so on.
Response to updated portion:
It depends on what /bin/sh actually points to on your system. Often it is just a symlink to /bin/bash . Sometimes portable scripts are written with #!/bin/sh just to signify that it’s a shell script, but it uses whichever shell is referred to by /bin/sh on that particular system (maybe it points to /bin/bash , /bin/ksh or /bin/zsh )
@ShivanRaptor #!/bin/bash Means run this script in bash. #!/bin/sh means run this script in sh which is the default unix shell, which might be bash or any other variant like ksh, dash, zsh, etc
When bash is run as sh , it behaves differently (more POSIX-like) than when it is run as bash . Read the manual; it does cover that detail.
@KarthikT it doesn’t run the default shell, it runs bash in Bourne Shell mode. (as opposed to Bourne Again Shell, aka. bash) On some older systems it would run Bourne Shell itself.
In bash script, what does #!/bin/bash at the 1st line mean ?
In Linux system, we have shell which interprets our UNIX commands. Now there are a number of shell in Unix system. Among them, there is a shell called bash which is very very common Linux and it has a long history. This is a by default shell in Linux.
When you write a script (collection of unix commands and so on) you have a option to specify which shell it can be used. Generally you can specify which shell it wold be by using Shebang(Yes that’s what it’s name).
So if you #!/bin/bash in the top of your scripts then you are telling your system to use bash as a default shell.
Now coming to your second question :Is there a difference between #!/bin/bash and #!/bin/sh ?
The answer is Yes. When you tell #!/bin/bash then you are telling your environment/ os to use bash as a command interpreter. This is hard coded thing.
Every system has its own shell which the system will use to execute its own system scripts. This system shell can be vary from OS to OS(most of the time it will be bash. Ubuntu recently using dash as default system shell). When you specify #!/bin/sh then system will use it’s internal system shell to interpreting your shell scripts.
Visit this link for further information where I have explained this topic.
Hope this will eliminate your confusions. good luck.