Linux Shell Scripting is not as hard as the way people have viewed it. Linux provides lots of substantial shells with powerful functionality. What do we understand by shell scripting? This term simply means scripting in any sort of shell.

These shells include Bash, Zsh, Tcsh, and Ksh, etc. One good thing about these subsets of shell scripting is that they are all relatively easy to program. The article we will be looking at here will definitely make familiar and a great user of Linux.

Bash shell is the most common Linux shell scripting. This article will contain a higher percentage of bash compared to other varieties of shell scripting. And the reason for this is because bash is more popular and it is more used compared to others. If you are looking For a Linux distro for the programming consider Reading the best Linux distro for programming article.

What do you understand by the term bash? Bash simply means Bourne Again SHell. It is just one of the many known Unix Shells. It is an upgrade on the Bourne shell (sh).

The examples that will be given here will definitely help you understand shell scripting better. They are relatively not difficult. Stay connected to us as we give you some really nice Linux script examples.

1. Hello World

Any beginner in the programming niche is first taught how to code out the “Hello World” with any language.

#!/bin/bash
echo "Hello World"

The above code will only run if you insert the code below.

$ chmod a+x hello-world.sh

Features:

  • It is one of the simplest programs known
  • You can easily try it out with vim or the nano editor

2. The use of echo to Print

You can easily use the bash command to print out the information you want in bash.

#!/bin/bash
echo "Printing text"
echo -n "Printing text without newline"
echo -e "\nRemoving \t special \t characters\n"

Features:

  • It does the same function as the “printf” in C programming language
  • It can also provide escape sequence and redirection

3. The use of Comments

Any coder will surely be familiar with comments and how important they are. We majorly use comments for documentation.

#!/bin/bash

# The addition of two numbers 
((sum=45+45))

#Print the result
echo $sum

Features:

  • The above script will output 90 as the result
  • You can simply use the #(hash) character to comment out a line

4. Multi-line Comments

It is not difficult to use the multi-line comments to document your shell scripts.

#!/bin/bash
: '
This script will output
the square of 10.
'
((area=10*10))
echo $area

Features:

  • It is cool for a nice coding experience
  • You must always remember to place your comments inside :’ and ‘ as we have done in the example above

5. The While Loop

You can always trust the while loop for coding an instruction for numerous times.

while [ condition ]
do
commands 1
commands n
done

Features:

  • The exact way of going about While loop is given above
  • Always remember to keep the space in the square bracket as it is kept in the picture above

6. The For Loop

For efficient iteration of codes without any problems, you can simply use the for loop because it is a bash shell construct.

#!/bin/bash

for (( Subtract=1; Subtract<=10; Subtract-- ))
do
echo -n "$Subtract "
done

printf "\n"

Features:

  • You can easily use “./for.sh” to run the code
  • It is a commonly used bash shell construct

7. Receiving Input from Users

It is important to get the inputs of users to enable them to comfortably interact with our scripts.

#!/bin/bash

echo -n "Enter Something:"
read something

echo "You Entered: $something"

Features:

  • A shell script example for receiving user input within a shell program
  • You can easily use the $ sign to have access to the input stored

8. The If Statement

The If Statement is one of the most popular conditional constructs found in Unix shell scripting.

if CONDITION 
then
STATEMENTS
fi

Features:

  • The above shows how to write the If Statement
  • The fi keyboard is used to put an end to an If Statement

9. The use of If Else

The If-Else construct can be implemented for better control over the logic of a script.

#!/bin/bash

read n
if [ $n -lt 10 ];
then
echo "It is a one digit number"
else
echo "It is a two digit number"
fi

Features:

  • You must always remember that else part must come after the action part of if but fi

10. The use of the AND Operator

The AND Operator does the work of checking if multiple conditions are met at a time or not.

#!/bin/bash

echo -n "Enter Number:"
read num

if [[ ( $num -lt 10 ) && ( $num%2 -eq 0 ) ]]; then
echo "Even Number"
else
echo "Odd Number"
fi

Features:

  • The “&&” is used to denote the AND Operator
  • The statements between the AND Operator must be true

11. The Use of the OR Operator

This is slightly different from the AND Operator in the sense that it returns true so far as one of the operands is true.

#!/bin/bash

echo -n "Enter any number:"
read n

if [[ ( $n -eq 15 || $n -eq 45 ) ]]
then
echo "Congratulations! It seems you have won"
else
echo "Try Again!"
fi

Features:

  • You can easily use it for implementing complex, strong programming logic in your scripts

12. The Use of the Elif Statement

The Elif statement is the short form of Else If.

#!/bin/bash

echo -n "Enter a number: "
read num

if [[ $num -gt 10 ]]
then
echo "Number is greater than 10."
elif [[ $num -eq 10 ]]
then
echo "Number is equal to 10."
else
echo "Number is less than 10."
fi

Features:

  • It is easily used to implement chain logic

13. The Switch Command

The switch command is a strong Linux bash script feature. It is used in places that there is a need for nested conditions.

#!/bin/bash

echo -n "Enter a number: "
read num

case $num in
100)
echo "Hundred!!" ;;
200)
echo "Double Hundred!!" ;;
*)
echo "Neither 100 nor 200" ;;
esac

Features:

  • It is a good alternative for the complex if-else-elif chains.

14. Command Line Arguments

It will be of great definite if you can get arguments from the command shell.

#!/bin/bash
echo "Total arguments : $#"
echo "First Argument = $3"
echo "Second Argument = $4"

Features:

  • You can name it whatever you wish to name it
  • You can use $3″ to access the first argument
  • Use $4″ to access the second argument
  • $#” is used to know the overall number of arguments

15. Getting Arguments with Names

You are going to be shown how to get command line arguments with their names here.

#!/bin/bash

for arg in "[email protected]"
do
index=$(echo $arg | cut -f1 -d=)
val=$(echo $arg | cut -f2 -d=)
case $index in
X) x=$val;;
Y) y=$val;;
*)
esac
done
((result=x+y))
echo "X+Y=$result"

Features:

  • Arguments can be inputted inside “[email protected]” in the place and you are able to get them using the Linux cut command
  • All you need do to the above script is to name and call it numbers of your choice

16. Concatenating Strings

Lots of advanced bash scripts take full advantage of string processing.

#!/bin/bash

string1="Ubuntu"
string2="Pit"
string=$string1$string2
echo "$string is a great resource for Linux beginners."

Features:

  • Concatenating strings in bash doesn’t look a difficult task to do

17. Slicing Strings

The slicing of a string in bash is done without the provision of an in-built function.

#!/bin/bash
Str="Dunebook will be teaching you bash commands"
subStr=${VAR_NAME:S:L}
echo $subStr

Features:

  • The S represents the starting position while L denotes the length

18. The Addition of two Values

Performing arithmetic operations in Linux shell script can be very easy as you can ever think of.

#!/bin/bash
echo -n "Enter first number:"
read x
echo -n "Enter second number:"
read y
(( sum=x+y ))
echo "The result of addition=$sum"

Features:

  • The addition of two numbers in Linux script is straightforward

19. Multiplying Numbers

Just as we have said for adding values together above, multiplying numbers in Linux shell script doesn’t appear difficult.

#!/bin/bash
sum=0
for (( counter=1; counter<5; counter++ ))
do
echo -n "Enter Your Number:"
read n
(( sum+=n ))
#echo -n "$counter "
done
printf "\n"
echo "Result is: $sum"

Features:

  • It can also be straightforward

20. The use of Cut to Extract Substrings

It is possible to use Linux Cut Command inside a script to “cut” some parts of the string.

#!/bin/bash
Str="Dunebook will be teaching you bash commands"
#subStr=${Str:0:15}

subStr=$(echo $Str| cut -d ' ' -f 1-3)
echo $subStr

Features:

  • The use of cut to extract substrings

21. Functions in Bash

A function is very important in Linux shell scripting just the way it is with every other programming languages.

#!/bin/bash
function Subtract()
{
echo -n "Enter a Number: "
read x
echo -n "Enter another Number: "
read y
echo "Subtraction is: $(( x-y ))"
}

Subtract

Features:

  • It allows you to develop custom code blocks for regular usage.

22. Functions with Return Values

It is convenient to pass data from one function to another.

#!/bin/bash

function Welcoming() {

str="Hello $name, what have you come to do on dunebook.com?"
echo $str
}

echo "-> can we know your name?"
read name

val=$(Welcoming)
echo -e "-> $val"

Features:

  • It can be very useful in many areas

23. Creating Directories from Bash Scripts

You are very likely to become more productive when you use shell scripts to execute system commands.

#!/bin/bash
echo -n "Enter directory name ->"
read newdir
cmd="mkdir $newdir"
eval $cmd
#!/bin/bash
echo -n "Enter directory name ->"
read newdir
cmd="mkdir $newdir"
eval $cmd

Features:

  • The example in the picture above shows how to use shell script to back up a directory in Linux

24. Create a Directory after Confirming Existence

This program in this segment of the article will scan if there is an existing folder named $dir and it will create one if none exists.

#!/bin/bash
echo -n "Enter directory name ->"
read dir
if [ -d "$dir" ]
then
echo "Directory exists"
else
`mkdir $dir`
echo "Directory created"
fi

Features:

  • You can use eval to increase your bash shell scripting while writing this program

25. Reading Files

It is easy and convenient to use bash scripts to read files. Create a file named ide.txt with the contents given below

1. Visual Studio Code 
2. Code::Blocks 
3. Eclipse 

This script will give out the above 3 lines as an output

#!/bin/bash
file='editors.txt'
while read line; do
echo $line
done < $file

Features:

  • It is good for reading files

26. Deleting Files

You will be asked to input the filename and it will help you delete it when it exists.

#!/bin/bash
echo -n "Enter filename ->"
read name
rm -i $name

Features:

  • You can use the rmdir command and the rm command to delete the specified empty directories and folders in Linux but the one you have used above is the rm command

27. Appending to Files

You can easily use the bash scripts to append data to any file on your filesystem.

#!/bin/bash
echo "Before appending the file"
cat ides.txt
echo "6. ++" Netbeans>> ides.txt
echo "After appending the file"
cat ides.txt

Features:

  • It is relatively not difficult to do

28. Test File Existence

The existence of a file can also be checked too. The image below explains how it can be done.

#!/bin/bash
filename=$300
if [ -f "$filename" ]; then
echo "Yes, the file exists"
else
echo "No, the file does not exist"
fi

29. Send Mails from Shell Scripts

Sending emails from bash scripts can be very simple and clear.

#!/bin/bash
recipient=”[email protected]”
subject=”Welcoming”
message=”We sincerely welcome you to Dunebook”
`mail -s $subject $recipient <<< $message`

Features:

  • One of the very possible ways of doing this is shown in the commands above

30. Parsing Date and Time

The handling of date and time using bash scripts looks easy to achieve. The Linux date command can be very helpful in getting started with this.

#!/bin/bash
year=`date +%Y`
month=`date +%m`
day=`date +%d`
hour=`date +%H`
minute=`date +%M`
second=`date +%S`
echo `date`
echo "Current Date is: $day-$month-$year"
echo "Current Time is: $hour:$minute:$second"

Features:

  • You can easily try it out by following the instructions above

31. The Sleep Command

You can easily use the Sleep command to make a break between instructions.

#!/bin/bash
echo "When am I going to continue?"
read time
sleep $time
echo "Waited for $time seconds!"

Features:

  • The $time seconds shown in the script above will be provided by the user to pause the program

32. The Wait Command

You can always trust the Wait Command to help you pause system processes from Linux bash scripts.

#!/bin/bash
echo "We are trying out the wait command"
sleep 5 &
kod=$!
kill $kod
wait $kod
echo $kod was terminated.

Features:

  • Try out the above program out now to see it executes

33. How to display the last updated file

There are some instances you will need to check for the last updated file. We will show you how to use the awk command here.

#!/bin/bash

ls -lrt | grep ^- | awk 'END{print $NF}'

Features:

  • It is simple to implement. Try it out now!

34. How to Add the Batch Extension

The script below will serve as a guide in showing you how to apply the custom extension to every file in a directory.

#!/bin/bash
dir=$1
for file in `ls $1/*`
do
mv $file $file.UP
done

Features:

  • As you can see above, you can simply program your script to add (.UP) to every file at the end

35. Print Number of Files or Directories

For finding the number of files or folders present within a directory, try out the following script below.

#!/bin/bash

if [ -d "[email protected]" ]; then
echo "Files found: $(find "[email protected]" -type f | wc -l)"
echo "Folders found: $(find "[email protected]" -type d | wc -l)"
else
echo "[ERROR] Please retry with another folder."
exit 1
fi

Features:

  • It make use of Linux find to perform this.

36. Cleaning the Log files

You can simply use this particular script to delete every log file present in your var/log directory.

#!/bin/bash
LOG_DIR=/var/log
cd $LOG_DIR

cat /dev/null > messages
cat /dev/null > wtmp
echo "Logs cleaned up."

Features:

  • It is possible for users to change the variable that holds this directory for cleaning up other logs.

37. The Use of Bash to Backup Scripts

There is a way you can simply use bash to back up your Linux shell scripts presented in your files and directories.

#!/bin/bash

BACKUPFILE=backup-$(date +%m-%d-%Y)
archive=${1:-$BACKUPFILE}

find . -mtime -1 -type f -print0 | xargs -0 tar rvf "$archive.tar"
echo "Directory $PWD backed up in archive file \"$archive.tar.gz\"."
exit 0

Features:

  • You can achieve this using the find command

38. How to check if a person is root or not

Bash scripts can be used to tell if a user is root or not.

#!/bin/bash
ROOT_UID=0

if [ "$UID" -eq "$ROOT_UID" ]
then
echo "Yes, you are root."
else
echo "No, you are not root"
fi
exit 0

Features:

  • The result of this program depends heavily on whoever is running it

39. How to remove duplicated lines from a file

It is never easy to search and find duplicated lines in a file. It becomes more tedious if you have to look into a very large file to see whether there are duplicated lines or not. To save time and energy, try out the following program below.

#! /bin/sh

echo -n "Enter Filename-> "
read filename
if [ -f "$filename" ]; then
sort $filename | uniq | tee sorted.txt
else
echo "No $filename in $pwd...try again"
fi
exit 0

Features:

  • The shell script will carefully scan through every line in your files to search and find out duplicated lines

40. System Maintenance

The Linux shell script will be given below help teach you how you can easily upgrade your system without going through the stressful manual way.

#!/bin/bash

echo -e "\n$(date "+%d-%m-%Y --- %T") --- Starting work\n"

apt-get update
apt-get -y upgrade

apt-get -y autoremove
apt-get autoclean

echo -e "\n$(date "+%T") \t Script Terminated"

Features:

  • You need to use Sudo to make the program run better and more efficiently

41. Trying to use the If Statement together with the AND Logic

You can also try out using any logical conditions in an If Statement that has more than one condition.

!/bin/bash

echo "Enter username"
read username
echo "Enter password"
read password

if [[ ( $username == "admin" && $password == "secret" ) ]]; then
echo "valid user"
else
echo "invalid user"
fi

Features:

  • You can name the above code “if_with_AND.sh” to check it out
  • &&” is used to add the AND logic in an If Statement

42. The use of the OR condition with the If Statement

Any OR condition in an If statement is represented using “||“.

#!/bin/bash

echo "Enter any number"
read n

if [[ ( $n -eq 20 || $n  -eq 60 ) ]]
then
echo "Congratulations! You are the winner of the game"
else
echo "Oops, you have just lost, try again!"
fi

Features:

  • Name the file “if_with_OR.sh” to try this out

43. Case Statement

You are allowed to try this statement out if you are looking for an alternative for if-elseif-else statement.

#!/bin/bash

echo "Enter your lucky number"
read n
case $n in
101)
echo echo "You got 1st prize" ;;
510)
echo "You got 2nd prize" ;;
999)
echo "You got 3rd prize" ;;
*)
echo "Sorry, try for the next time" ;;
esac

Features:

  • Give the name of the file “case_example.sh
  • Use “case” to this statement
  • Use “esac” to end the statement

44. Combining String Variables

Check the program below to see how you can comfortably combine string variables together in a bash shell script.

#!/bin/bash

string1="Dunebook"
string2="will give you"
echo "$string1$string2"
string3=$string1+$string2
string3+=" the content you ever desire"
echo $string3

Features:

  • Open a new file and name it “string_combine.sh” to try out the above code

45. Counting the only files that is yours

The shell script below will show you an example of how you can count the only files you own.

#!/bin/bash
# Counting the number of lines in a list of files
# for loop over arguments
# count only those files I am owner of

if [ $# -lt 1 ]
then
  echo "Usage: $0 file ..."
  exit 1
fi

echo "$0 counts the lines of code" 
l=0
n=0
s=0
for f in $*
do
  if [ -O $f ] # checks whether file owner is running the script
  then 
      l=`wc -l $f | sed 's/^\([0-9]*\).*$/\1/'`
      echo "$f: $l"
      n=$[ $n + 1 ]
      s=$[ $s + $l ]
  else
      continue
  fi
done

echo "$n files in total, with $s lines in total"

Conclusion

The extent to which you can use Linux shell scripts doesn’t have an end. The following famous Linux script examples we have given in this article are very good to start with if you are just coming into the game. They are very easy to understand and utilize if you are really interested in knowing about Linux shell scripting.