Bash Shell

Understand Linux Shell and Basic Shell Scripting Language Tips – Part I

Understand Linux Shell and Basic Shell Scripting Language Tips &-8211; Part I &-8211; this Article or News was published on this date:2019-05-28 19:47:35 kindly share it with friends if you find it helpful

Picture speak more than words and the below picture says all about the working of Linux.

 

Understanding Linux ShellUnderstanding Linux Shell

Understanding Linux Shell

Read Also

  1. 5 Shell Scripts to Learn Shell Programming – Part II
  2. Sailing Through The World of Linux BASH Scripting – Part III

Understanding Linux Shell

  1. Shell: A Command-Line Interpretor that connects a user to Operating System and allows to execute the commands or by creating text script.
  2. Process: Any task that a user run in the system is called a process. A process is little more complex than just a task.
  3. File: It resides on hard disk (hdd) and contains data owned by a user.
  4. X-windows aka windows: A mode of Linux where screen (monitor) can be split in small “parts” called windows, that allow a user to do several things at the same time and/or switch from one task to another easily and view graphics in a nice way.
  5. Text terminal: A monitor that has only the capability of displaying text stuff, no graphics or a very basic graphics display.
  6. Session: Time between logging on and logging out of the system.

Types of Shell on a Standard Linux Distribution

Bourne shell : The Bourne shell was one of the major shells used in early versions and became a de facto standard. It was written by Stephen Bourne at Bell Labs. Every Unix-like system has at least one shell compatible with the Bourne shell. The Bourne shell program name is “sh” and it is typically located in the file system hierarchy at /bin/sh.

C shell: The C shell was developed by Bill Joy for the Berkeley Software Distribution. Its syntax is modelled after the C programming language. It is used primarily for interactive terminal use, but less frequently for scripting and operating system control. C shell has many interactive commands.

Beginning the Fun! (Linux Shell)

There exist thousands of commands for command-line user, how about remembering all of them? Hmmm! Simply you can not. The real power of computer is to ease the ease your work, you need to automate the process and hence you need scripts.

Scripts are collections of commands, stored in a file. The shell can read this file and act on the commands as if they were typed at the keyboard. The shell also provides a variety of useful programming features to make scripts truly powerful.

Basics of Shell Programming

  1. To get a Linux shell, you need to start a terminal.
  2. To see what shell you have, run: echo $SHELL.
  3. In Linux, the dollar sign ($) stands for a shell variable.
  4. The ‘echo‘ command just returns whatever you type in.
  5. The pipeline instruction (|) comes to rescue, when chaining several commands.
  6. Linux commands have their own syntax, Linux won’t forgive you whatsoever is the mistakes. If you get a command wrong, you won’t flunk or damage anything, but it won’t work.
  7. -!/bin/sh – It is called shebang. It is written at the top of a shell script and it passes the instruction to the program /bin/sh.

About shell Script

Shell script is just a simple text file with “.sh” extension, having executable permission.

Process of writing and executing a script

  1. Open terminal.
  2. Navigate to the place where you want to create script using ‘cd‘ command.
  3. Cd (enter) [This will bring the prompt at Your home Directory].
  4. touch hello.sh (Here we named the script as hello, remember the ‘.sh‘ extension is compulsory).
  5. vi hello.sh (nano hello.sh) [You can use your favourite editor, to edit the script].
  6. chmod 744 hello.sh (making the script executable).
  7. sh hello.sh or ./hello.sh (running the script)
Writing your First Script
-!/bin/bash
- My first script

echo "Hello World!"

Save the above lines on a text file, make it executable and run it, as described above.

Sample Output

Hello World!

In the above code.

-!/bin/bash (is the shebang.)
- My first script (is comment, anything following '-' is a comment)
echo “Hello World!” (is the main part of this script)
Writing your Second Script

OK time to move to the next script. This script will tell you, your’s “username” and list the running processes.

-! /bin/bash
echo "Hello $USER"
echo "Hey i am" $USER "and will be telling you about the current processes"
echo "Running processes List"
ps

Create a file with above codes, save it to anything you want, but with extension “.sh“, make it executable and run it, from you terminal.

Sample Output

Hello sfnews
Hey i am sfnews and will be telling you about the current processes
Running processes List
  PID TTY          TIME CMD
 1111 pts/0    00:00:00 bash
 1287 pts/0    00:00:00 sh
 1288 pts/0    00:00:00 ps

Was this cool? Writing script is as simple as getting an idea and writing pipelined commands. There are some restrictions, too. Shell scripts are excellent for concise filesystem operations and scripting the combination of existing functionality in filters and command line tools via pipes.

When your needs are greater – whether in functionality, robustness, performance, efficiency etc – then you can move to a more full-featured language.

If you already know C/Perl/Python programming language or any other programming language, learning the scripting language won’t be much difficult.

Writing your Third Script

Moving to, write our third and last script for this article. This script acts as an interactive script. Why don’t you, yourself execute this simple yet interactive script and tell us how you felt.

-! /bin/bash
echo "Hey what's Your First Name?";
read a;
echo "welcome Mr./Mrs. $a, would you like to tell us, Your Last Name";
read b;
echo "Thanks Mr./Mrs. $a $b for telling us your name";
echo "*******************"
echo "Mr./Mrs. $b, it's time to say you good bye"

Sample Output

Hey what's Your First Name?
Avishek
welcome Mr./Mrs. Avishek, would you like to tell us, Your Last Name
Kumar
Thanks Mr./Mrs. Avishek Kumar for telling us your name
******************************************************
Mr./Mrs. Kumar, it's time to say you good bye

Well this is not an end. We tried to bring a taste of scripting to you. In our future article we will elaborate this scripting language topic, rather a never ending scripting language topic, to be more perfect. Your valuable thoughts in comments is highly appreciated, Like and share us and help us to spread. Till then just chill, keep connected, stay tuned.

Read Also : 5 Shell Scripts to Learn Shell Programming – Part II

5 Shell Scripts for Linux Newbies to Learn Shell Programming – Part II

5 Shell Scripts for Linux Newbies to Learn Shell Programming &-8211; Part II &-8211; this Article or News was published on this date:2019-05-28 19:47:18 kindly share it with friends if you find it helpful

To Learn something you need to do it, without the fear of being unsuccessful. I believe in practicality and hence will be accompanying you to the practical world of Scripting Language.

Learn Basic Shell ScriptingLearn Basic Shell Scripting

Learn Basic Shell Scripting

This article is an extension of our First article Understand Linux Shell and Basic Shell Scripting – Part I, where we gave you a taste of Scripting, continuing that we won’t disappoint you in this article.

Script 1: Drawing a Special Pattern

-!/bin/bash
MAX_NO=0
echo -n "Enter Number between (5 to 9) : "
read MAX_NO
if ! [ $MAX_NO -ge 5 -a $MAX_NO -le 9 ] ; then
   echo "WTF... I ask to enter number between 5 and 9, Try Again"
   exit 1
fi
clear
for (( i=1; i=MAX_NO; i++ )) do     for (( s=MAX_NO; s>=i; s-- ))
    do
       echo -n " "
    done
    for (( j=1; j=i;  j++ ))     do      echo -n " ."      done     echo "" done ------ Second stage ---------------------- for (( i=MAX_NO; i>=1; i-- ))
do
    for (( s=i; s=MAX_NO; s++ ))
    do
       echo -n " "
    done
    for (( j=1; j=i;  j++ ))
    do
     echo -n " ."
    done
    echo ""
done
echo -e "nnttt Whenever you need help, sfnews.com is always there"

Most of the above ‘key words‘ would be known to you and most of them are self explanatory. e.g., MAX sets the maximum value of the variable, for is a loop and anything within the loop gets on executing again and again till the loop is valid for given value of input.

Sample Output
[[email protected] ~]- chmod 755 Special_Pattern.sh
[[email protected] ~]- ./Special_Pattern.sh
Enter Number between (5 to 9) : 6
       .
      . .
     . . .
    . . . .
   . . . . .
  . . . . . .
  . . . . . .
   . . . . .
    . . . .
     . . .
      . .
       .

                         Whenever you need help, sfnews.com is always there

If you are a little aware of any programming language, learning the above script is not difficult, even if you are new to computation, programming and Linux it is not going to be much difficult.

Download Special_Pattern.sh

Script 2: Creating Colorful Script

Who says, Linux is colorless and boring, save the codes below to anything [dot] sh, make it executable and Run it, don’t forget to tell me how it was, Think what you can achieve, implementing it somewhere.

-!/bin/bash
clear 
echo -e "33[1m Hello World"
- bold effect
echo -e "33[5m Blink"
- blink effect
echo -e "33[0m Hello World"
- back to normal
echo -e "33[31m Hello World"
- Red color
echo -e "33[32m Hello World"
- Green color
echo -e "33[33m Hello World"
- See remaining on screen
echo -e "33[34m Hello World"
echo -e "33[35m Hello World"
echo -e "33[36m Hello World"
echo -e -n "33[0m"
- back to normal
echo -e "33[41m Hello World"
echo -e "33[42m Hello World"
echo -e "33[43m Hello World"
echo -e "33[44m Hello World"
echo -e "33[45m Hello World"
echo -e "33[46m Hello World"
echo -e "33[0m Hello World"

Note: Don’t bother about the color code now, Those important to you will be at your tongue, gradually.

Warning: Your terminal might not have the facility of blinking.

Sample Output
[[email protected] ~]- chmod 755 Colorfull.sh
[[email protected] ~]- ./Colorfull.sh

Hello World
Blink
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

Download Colorfull.sh

Script 3: Encrypt a File/Directory

This script will encrypt a file (remember? directory/driver/…. everything is treated as file, in Linux). The current limitation of the above script is that it don’t support auto completion of name using TAB. Moreover, you need to place the script and file to be encrypted in the same folder. You may need to install “pinentry-gui”, using yum or apt the package, if required.

[[email protected] ~]- yum install pinentry-gui
[[email protected] ~]- apt-get install pinentry-gui

Crete a file called “Encrypt.sh” and place the following script, make it executable and run it as shown.

-!/bin/bash
echo "Welcome, I am ready to encrypt a file/folder for you"
echo "currently I have a limitation, Place me to thh same folder, where a file to be 
encrypted is present"
echo "Enter the Exact File Name with extension"
read file;
gpg -c $file
echo "I have encrypted the file successfully..."
echo "Now I will be removing the original file"
rm -rf $file

Sample Output

[[email protected] ~]- chmod 755 Encrypt.sh
[[email protected] ~]- ./Encrypt.sh

Welcome, I am ready to encrypt a file/folder for you
currently I have a limitation, Place me to the same folder, where a file to be

encrypted is present
Enter the Exact File Name with extension

package.xml

                                                   ┌─────────────────────────────────────────────────────┐
                                                   │ Enter passphrase                                    │
                                                   │                                                     │
                                                   │                                                     │
                                                   │ Passphrase *******_________________________________ │
                                                   │                                                     │
                                                   │       OK>                             Cancel>     │
                                                   └─────────────────────────────────────────────────────┘

Please re-enter this passphrase

                                                   ┌─────────────────────────────────────────────────────┐
                                                   │ Please re-enter this passphrase                     │
                                                   │                                                     │
                                                   │ Passphrase ********________________________________ │
                                                   │                                                     │
                                                   │       OK>                             Cancel>     │
                                                   └─────────────────────────────────────────────────────┘

I have encrypted the file successfully...
Now I will be removing the original file
/pre>

gpg -c : This will encrypt your file, using a passkey aka password. In this process of learning you would have never thought that the actual process of learning could be that much easy. So after encrypting a file what you need? Obviously! decrypting the file. And I want you – the learner, the reader to write the decryption script yourself, don’t worry I am not leaving you in the middle, I just want you to gain something out of this article.

Note: gpg -d filename.gpg > filename is what you need to implement in your decryption script. You may post you script in comment if successful, if not you may ask me to write it for you.

Download Encrypt.sh

Script 4: Checking Server Utilization

Checking the server utilization is one of the important task of an administrator, and a good administrator is one who knows how to automate his day to day task. Below is the script that will give many such information about your server. Check it yourself.

-!/bin/bash
    date;
    echo "uptime:"
    uptime
    echo "Currently connected:"
    w
    echo "--------------------"
    echo "Last logins:"
    last -a |head -3
    echo "--------------------"
    echo "Disk and memory usage:"
    df -h | xargs | awk '{print "Free/total disk: " $11 " / " $9}'
    free -m | xargs | awk '{print "Free/total memory: " $17 " / " $8 " MB"}'
    echo "--------------------"
    start_log=`head -1 /var/log/messages |cut -c 1-12`
    oom=`grep -ci kill /var/log/messages`
    echo -n "OOM errors since $start_log :" $oom
    echo ""
    echo "--------------------"
    echo "Utilization and most expensive processes:"
    top -b |head -3
    echo
	top -b |head -10 |tail -4
    echo "--------------------"
    echo "Open TCP ports:"
    nmap -p- -T4 127.0.0.1
    echo "--------------------"
    echo "Current connections:"
    ss -s
    echo "--------------------"
    echo "processes:"
    ps auxf --width=200
    echo "--------------------"
    echo "vmstat:"
    vmstat 1 5
Sample Output
[[email protected] ~]- chmod 755 Server-Health.sh
[[email protected] ~]- ./Server-Health.sh

Tue Jul 16 22:01:06 IST 2013
uptime:
 22:01:06 up 174 days,  4:42,  1 user,  load average: 0.36, 0.25, 0.18
Currently connected:
 22:01:06 up 174 days,  4:42,  1 user,  load average: 0.36, 0.25, 0.18
USER     TTY      FROM              [email protected]   IDLE   JCPU   PCPU WHAT
sfnews   pts/0    116.72.134.162   21:48    0.00s  0.03s  0.03s sshd: sfnews [priv]
--------------------
Last logins:
sfnews   pts/0        Tue Jul 16 21:48   still logged in    116.72.134.162
sfnews   pts/0        Tue Jul 16 21:24 - 21:43  (00:19)     116.72.134.162
--------------------
Disk and memory usage:
Free/total disk: 292G / 457G
Free/total memory: 3510 / 3838 MB
--------------------
OOM errors since Jul 14 03:37 : 0
--------------------
Utilization and most expensive processes:
top - 22:01:07 up 174 days,  4:42,  1 user,  load average: 0.36, 0.25, 0.18
Tasks: 149 total,   1 running, 148 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.1%us,  0.0%sy,  0.0%ni, 99.3%id,  0.6%wa,  0.0%hi,  0.0%si,  0.0%st

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
    1 root      20   0  3788 1128  932 S  0.0  0.0   0:32.94 init
    2 root      20   0     0    0    0 S  0.0  0.0   0:00.00 kthreadd
    3 root      RT   0     0    0    0 S  0.0  0.0   0:14.07 migration/0

Note: I have given you the script that gives the output in the terminal itself, how about getting the output in a file for future reference. Implement it using redirect operator.

  1. >‘ : the redirection operator causes a file creation, and if it does exist, the contents are overwritten.
  2. >>‘ : when you use >>, you are adding information, rather than replacing it.
  3. >>‘ is safe, as compared to ‘>

Download Server-Health.sh

Script 5: Check Disk Space and Sends an Email Alert

How about getting an email when disk use in partition PART is bigger than Maximum allowed, it is a life saver script for web administrators with little modification.

MAX=95
[email protected]
PART=sda1
USE=`df -h |grep $PART | awk '{ print $5 }' | cut -d'%' -f1`
if [ $USE -gt $MAX ]; then
  echo "Percent used: $USE" | mail -s "Running out of disk space" $EMAIL
fi

Note: Remove “USER” with your user name. You can check mail using using ‘mail‘ command.

Download Check-Disk-Space.sh

Script writing and programming is beyond boundaries, anything and everything could be implemented as required. That’s all for now, In my very next article I will be giving your some different flavors of scripting. Till then stay cool and tuned, enjoy.

Sailing Through The World of Linux BASH Scripting – Part III

Sailing Through The World of Linux BASH Scripting &-8211; Part III &-8211; this Article or News was published on this date:2019-05-28 19:47:10 kindly share it with friends if you find it helpful

The Previous following articles of ‘Shell Scripting‘ series were highly appreciated and hence I am writing this article to extend the never ending process of learning.

Basic Shell Scripting Part-3Basic Shell Scripting Part-3

Basic Shell Scripting Part-3

  1. Understand Basic Linux Shell Scripting Language Tips – Part I
  2. 5 Shell Scripts for Linux Newbies to Learn Shell Programming – Part II
Bash Keywords

A keyword is a word or symbol that has a special meaning to a computer language. The following symbols and words have special meanings to Bash when they are unquoted and the first word of a command.

! 			esac 			select 		} 
case 			fi 			then 		[[ 
do 			for 			until 		]] 
done 			function 		while 		elif
if 			time 			else 		in 		{

Unlike most computer languages, Bash allows keywords to be used as variable names even though this can make scripts difficult to read. To keep scripts understandable, key-words should not be used for variable names.

A command is implemented in shell as $(command). You might have to include the full path of command. e.g., $(/bin/date), for correct execution.

You may know the path of specific program using ‘whereis‘ command. e.g., whereis date

[[email protected] /]- whereis date
date: /bin/date /usr/share/man/man1/date.1.gz

That’s enough for now. We won’t be talking much about these theory now. Coming to Scripts.

Move Current Working Directory

Move from current working directory to any level up by just providing the numerical value at the end of script while executing.

-! /bin/bash 
LEVEL=$1 
for ((i = 1; i = LEVEL; i++)) 
do 
CDIR=../$CDIR 
done 
cd $CDIR 
echo "You are in: "$PWD 
exec /bin/bash

Save the above codes as “up.sh“, on your desktop. Make it executable (chmod 755 up.sh). Run:

./up.sh 2 (will Move the current working directory to two level up).
./up.sh 4 (will Move the current working directory to four level up).

Use and Area of Application

In larger scripts which contains folder inside folder inside… containing libraries, binaries, icons, executables, etc at different location, You as a developer can implement this script to move to the desired location in a very automated fashion.

Note: For is a loop in the above script and it will continue to execute till the values are true for the loop.

Sample Output
[[email protected] /]- chmod 755 up
[[email protected] /]- ./up.sh 2
You are in: /

[[email protected] /]- ./up.sh 4 
You are in: / 

[[email protected] /]-

Download up.sh

Create a Random File or Folder

Create a random file (folder) with no chance of duplication.

-! /bin/bash

echo "Hello $USER";
echo "$(uptime)" >> "$(date)".txt
echo "Your File is being saved to $(pwd)"

This is a Simple script but it’s working is not that much simple.

  1. echo‘ : Prints everything written within the quotes.
  2. $‘ : Is a shell variable.
  3. >>‘ : The output is redirected to the output of date command followed by txt extension.

We know the output of date command is date, and time in hour, minute, second along with year. Hence we could get output on an organised file name without the chance of filename duplication. It could be very much useful when user needs the file created with time stamp for future reference.

Sample Output
[[email protected] /]- ./randomfile.sh  
Hello server 
Your File is being saved to /home/server/Desktop

You can view the file which is created on desktop with Today’s Date and current time.

[[email protected] /]- nano Sat Jul 20 13:51:52 IST 2013.txt 
13:51:52 up  3:54,  1 user,  load average: 0.09, 0.12, 0.08

A more detailed implementation of the above script is given below, which works on the above principle and is very useful in gathering the network information of a Linux server.

Download randomfile.sh

Script to Collect Network Information

Gathers network information on a Linux server. The script is too large and it’s not possible to post the whole code and output of the script here. So, it’s better you can download the script using below download link and test it yourself.

Note: You might need to install lsb-core package and other required packages and dependency. Apt or Yum the required packages. Obviously you need to be root to run the script because most of the commands used here are configured to be run as root.

Sample Output
[[email protected] /]- ./collectnetworkinfo.sh  

The Network Configuration Info Written To network.20-07-13.info.txt. Please email this file to [email protected]_provider.com. ktop

You can change the above email address in your script to get it being mailed to you. The Automatically generated file can be viewed.

Download collectnetworkinfo.sh

Script to Converts UPPERCASE to lowercase

A script that converts UPPERCASE to lowercase and redirects the output to a text file “small.txt” which can be modified as required.

-!/bin/bash 

echo -n "Enter File Name : " 
read fileName 

if [ ! -f $fileName ]; then 
  echo "Filename $fileName does not exists" 
  exit 1 
fi 

tr '[A-Z]' '[a-z]'  $fileName >> small.txt

This above script can convert the case of a file of any length with a single click from uppercase to lowercase and vice-versa if required, with little modification.

Sample Output
[[email protected] /]- ./convertlowercase.sh  
Enter File Name : a.txt 

Initial File: 
A
B
C
D
E
F
G
H
I
J
K
...

New File (small.txt) output:

a
b
c
d
e
f
g
h
i
j
k
...

Download convertlowercase.sh

Simple Calculator Program

-! /bin/bash 
clear 
sum=0 
i="y" 

echo " Enter one no." 
read n1 
echo "Enter second no." 
read n2 
while [ $i = "y" ] 
do 
echo "1.Addition" 
echo "2.Subtraction" 
echo "3.Multiplication" 
echo "4.Division" 
echo "Enter your choice" 
read ch 
case $ch in 
    1)sum=`expr $n1 + $n2` 
     echo "Sum ="$sum;; 
        2)sum=`expr $n1 - $n2` 
     echo "Sub = "$sum;; 
    3)sum=`expr $n1 * $n2` 
     echo "Mul = "$sum;; 
    4)sum=`expr $n1 / $n2` 
     echo "Div = "$sum;; 
    *)echo "Invalid choice";; 
esac 
echo "Do u want to continue (y/n)) ?" 
read i 
if [ $i != "y" ] 
then 
    exit 
fi 
done
Sample Output
[[email protected] /]- ./simplecalc.sh 

Enter one no. 
12 
Enter second no. 
14 
1.Addition 
2.Subtraction 
3.Multiplication 
4.Division 
Enter your choice 
1 
Sum =26 
Do u want to continue (y/n)) ? 
y
1.Addition 
2.Subtraction 
3.Multiplication 
4.Division 
Enter your choice 
3 
mul = 14812
Do u want to continue (y/n)) ? 
n

Download simplecalc.sh

So did you saw how easy it was to create a powerful program as calculations such a simple way. Its’ not the end. We will be comping up with at least one more article of this series, covering broad perspective from administration view.

That’s all for now. Being the reader and the best critic don’t forget to tell us how much and what you enjoyed in this article and what you want to see in the future article. Any question is highly welcome in comment. Till then stay healthy, safe and tuned. Like and Share us and help us spread.

Mathematical Aspect of Linux Shell Programming – Part IV

Mathematical Aspect of Linux Shell Programming &-8211; Part IV &-8211; this Article or News was published on this date:2019-05-28 19:45:58 kindly share it with friends if you find it helpful

In this post I will be discussing the Scripts from the Mathematical and Number point of view. Although I have posted a more complex script (Simple Calculator) in the previous post, but on a user part it was difficult to understand and hence I thought to make you people learn the other useful side of learning in small packets.

Learn Shell Scripting Part 4Learn Shell Scripting Part 4

Shell Scripting Part 4

Prior to this article, three article of Shell Scripting Series are published and they are:

  1. Understand Linux Shell and Basic Shell Scripting – Part I
  2. 5 Shell Scripts to Learn Shell Programming – Part II
  3. Sailing Through The World of Linux BASH Scripting – Part III

Let’s start the further learning process with some new exciting scripts, start with Mathematics scripts:

Script 1: Additions

Create a file “Addition.sh” and chmod 755 to the script as described in previous post and run it.

-!/bin/bash
echo “Enter the First Number: ” 
read a 
echo “Enter the Second Number: ” 
read b 
x=$(expr "$a" + "$b") 
echo $a + $b = $x
Sample Output
[[email protected] ~]- vi Additions.sh
[[email protected] ~]- chmod 755 Additions.sh
[[email protected] ~]- ./Additions.sh

“Enter the First Number: ” 
12 
“Enter the Second Number: ” 
13 
12 + 13 = 25

Download Additions.sh

Script 2: Substraction

-!/bin/bash
echo “Enter the First Number: ” 
read a 
echo “Enter the Second Number: ” 
read b 
x=$(($a - $b)) 
echo $a - $b = $x

Note: Here we replaced the expr and let the mathematical calculation be performed in shell.

Sample Output
[[email protected] ~]- vi Substraction.sh
[[email protected] ~]- chmod 755 Substraction.sh
[[email protected] ~]- ./Substraction.sh

“Enter the First Number: ” 
13 
“Enter the Second Number: ” 
20 
13 - 20 = -7

Download Substraction.sh

Script 3: Multiplication

So far you would be enjoying a lot, learning scripts in such an easy way, so the next in chronological order is Multiplication.

-!/bin/bash
echo “Enter the First Number: ” 
read a 
echo “Enter the Second Number: ” 
read b 
echo "$a * $b = $(expr $a * $b)"

Note: Yup! Here we didn’t put the value of multiplication in a variable but performed it directly in output statement.

Sample Output
[[email protected] ~]- vi Multiplication.sh
[[email protected] ~]- chmod 755 Multiplication.sh
[[email protected] ~]- ./Multiplication.sh

“Enter the First Number: ” 
11 
“Enter the Second Number: ” 
11 
11 * 11 = 121

Download Multiplication.sh

Script 4: Division

Right! Next is Division, and again it is a very simple script. Check it Yourself.

-!/bin/bash
echo “Enter the First Number: ” 
read a 
echo “Enter the Second Number: ” 
read b 
echo "$a / $b = $(expr $a / $b)"
Sample Output
[[email protected] ~]- vi Division.sh
[[email protected] ~]- chmod 755 Division.sh
[[email protected] ~]- ./Division.sh

“Enter the First Number: ” 
12 
“Enter the Second Number: ” 
3 
12 / 3 = 4

Download Division.sh

Script 5: Table

Fine! What after these basic mathematical operation. Lets write a script that prints table of any number.

-!/bin/bash
echo “Enter The Number upto which you want to Print Table: ” 
read n 
i=1 
while [ $i -ne 10 ] 
do 
i=$(expr $i + 1) 
table=$(expr $i * $n) 
echo $table 
done
Sample Output
[[email protected] ~]- vi Table.sh
[[email protected] ~]- chmod 755 Table.sh
[[email protected] ~]- ./Table.sh

“Enter The Number upto which you want to Print Table: ” 
29 
58 
87 
116 
145 
174 
203 
232 
261 
290

Download Table.sh

Script 6: EvenOdd

We as a child always have carried out calculation to find if the number is odd or even. Won’t it be a good idea to implement it in script.

-!/bin/bash
echo "Enter The Number" 
read n 
num=$(expr $n % 2) 
if [ $num -eq 0 ] 
then 
echo "is a Even Number" 
else 
echo "is a Odd Number" 
fi
Sample Output
[[email protected] ~]- vi EvenOdd.sh
[[email protected] ~]- chmod 755 EvenOdd.sh
[[email protected] ~]- ./EvenOdd.sh

Enter The Number 
12 
is a Even Number
[[email protected] ~]- ./EvenOdd.sh

Enter The Number 
11 
is a Odd Number

Download EvenOdd.sh

Script 7: Factorial

Next is to find the Factorial.

-!/bin/bash 
echo "Enter The Number" 
read a 
fact=1 
while [ $a -ne 0 ] 
do 
fact=$(expr $fact * $a) 
a=$(expr $a - 1) 
done 
echo $fact
Sample Output
[[email protected] ~]- vi Factorial.sh
[[email protected] ~]- chmod 755 Factorial.sh
[[email protected] ~]- ./Factorial.sh

Enter The Number 
12 
479001600

You may now relax with a feeling that calculating 12*11*10*9*7*7*6*5*4*3*2*1 would be more difficult than a simple script as produced above. Think of the situation where you require to find 99! or something like that. Sure! This script will be very much handy in that situation.

Download Factorial.sh

Script 8: Armstrong

Armstrong Number! Ohhh You forget what an Armstrong Number is. Well an Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371.

-!/bin/bash 
echo "Enter A Number" 
read n 
arm=0 
temp=$n 
while [ $n -ne 0 ] 
do 
r=$(expr $n % 10) 
arm=$(expr $arm + $r * $r * $r) 
n=$(expr $n / 10) 
done 
echo $arm 
if [ $arm -eq $temp ] 
then 
echo "Armstrong" 
else 
echo "Not Armstrong" 
fi
Sample Output
[[email protected] ~]- vi Armstrong.sh
[[email protected] ~]- chmod 755 Armstrong.sh
[[email protected] ~]- ./Armstrong.sh

Enter A Number 
371 
371 
Armstrong
[[email protected] ~]- ./Armstrong.sh

Enter A Number 
123 
36 
Not Armstrong

Download Armstrong.sh

Script 9: Prime

The last script is to distinguish whether a number is prime or not.

-!/bin/bash 
echo “Enter Any Number”
read n
i=1
c=1
while [ $i -le $n ]
do
i=$(expr $i + 1)
r=$(expr $n % $i)
if [ $r -eq 0 ]
then
c=$(expr $c + 1)
fi
done
if [ $c -eq 2 ]
then
echo “Prime”
else
echo “Not Prime”
fi
Sample Output
[[email protected] ~]- vi Prime.sh
[[email protected] ~]- chmod 755 Prime.sh
[[email protected] ~]- ./Prime.sh

“Enter Any Number” 
12 

“Not Prime”

Download Prime.sh

That’s all for now. In our very next article we will be covering other mathematical programs in the shell Scripting programming language. Don’t forget to mention your views regarding article in the Comment section. Like and share us and help us spread. Come Visiting sfnews.com for News and articles relating to FOSS. Till then Stay tuned.

Calculating Mathematical Expressions in Shell Scripting Language – Part V

Calculating Mathematical Expressions in Shell Scripting Language &-8211; Part V &-8211; this Article or News was published on this date:2019-05-28 19:43:04 kindly share it with friends if you find it helpful

You People would be feeling comfortable, understanding Shell Scripts and writing them fluently, as per your need. This is the last post of this tutorial series, where we will be carrying out a bit complex Mathematical Operations using scripting language. The last four articles of Shell Scripting series which are chronologically.

Learn Shell ScriptingLearn Shell Scripting

Learn Shell Scripting Part – V

  1. Understand Basic Linux Shell Scripting Language Tips – Part I
  2. 5 Shell Scripts for Linux Newbies to Learn Shell Programming – Part II
  3. Sailing Through The World of Linux BASH Scripting – Part III
  4. Mathematical Aspect of Linux Shell Programming – Part IV

Lets start with Fibonacci Series

A pattern of numbers where each number is the sum of two preceding numbers. The series is 0, 1, 1, 2, 3, 5, 8…… By definition, the first two numbers in the Fibonccai sequence are 0 and 1.

Script 1: Fibonacci.sh
-!/bin/bash
echo "How many numbers do you want of Fibonacci series ?" 
  read total 
  x=0 
  y=1 
  i=2 
  echo "Fibonacci Series up to $total terms :: " 
  echo "$x" 
  echo "$y" 
  while [ $i -lt $total ] 
  do 
      i=`expr $i + 1 ` 
      z=`expr $x + $y ` 
      echo "$z" 
      x=$y 
      y=$z 
  done
Sample Output
[[email protected] ~]- chmod 755 Fibonacci.sh
[[email protected] ~]- ./Fibonacci.sh

How many numbers do you want of Fibonacci series ? 
10 
Fibonacci Series up to 10 terms :: 
0 
1 
1 
2 
3 
5 
8 
13 
21 
34

Download Fibonacci.sh

You are Familiar with the fact that computer understand only in the Binary Format, i.e., ‘0‘ and ‘1‘ and most of us have enjoyed learning the conversion of Decimal to Binary. How about writing a simple script for this complex operation.

Script 2: Decimal2Binary.sh
-!/bin/bash 

for ((i=32;i>=0;i--)); do 
        r=$(( 2**$i)) 
        Probablity+=( $r  ) 
done 

[[ $- -eq 0 ]] &echo -en "DecimalttBinaryn" 
for input_int in [email protected]; do 
s=0 
test ${-input_int} -gt 11 &printf "%-10st" "$input_int" 

        for n in ${Probablity[@]}; do 

                if [[ $input_int -lt ${n} ]]; then 
                        [[ $s = 1 ]] && printf "%d" 0 
                else 
                        printf "%d" 1 ; s=1 
                        input_int=$(( $input_int - ${n} )) 
                fi 
        done 
echo -e 
done
Sample Output
[[email protected] ~]- chmod 755 Decimal2Binary.sh
[[email protected] ~]- ./Decimal2Binary.sh 1121

Decimal		Binary 
1121      	10001100001

Note: The above script accept Input at run time, which obviously is an aid.

Download Decimal2Binary.sh

Well the inbuilt ‘bc‘ command can convert a decimal to binary in a script of single line. Run, at your terminal.

[[email protected] ~]- echo "obase=2; NUM" | bc

Replace ‘NUM‘ with the number, which you want to convert from Decimal to Binary. For example,

[[email protected] ~]- echo "obase=2; 121" | bc 

1111001

Next we will be writing a script which function just opposite of the above script, Converting Binary Values to Decimal.

Script 3: Binary2Decimal.sh
-!/bin/bash 
echo "Enter a number :" 
read Binary 
if [ $Binary -eq 0 ] 
then 
echo "Enter a valid number " 
else 
while [ $Binary -ne 0 ] 
do 
Bnumber=$Binary 
Decimal=0 
power=1 
while [ $Binary -ne 0 ] 
do 
rem=$(expr $Binary % 10 ) 
Decimal=$((Decimal+(rem*power))) 
power=$((power*2)) 
Binary=$(expr $Binary / 10) 
done 
echo  " $Decimal" 
done 
fi
Sample Output
[[email protected] ~]- chmod 755 Binary2Decimal.sh
[[email protected] ~]- ./Binary2Decimal.sh

Enter a number : 
11 
3

Note: The above function can be performed in terminal using ‘bc‘ command as.

[[email protected] ~]- echo "ibase=2; BINARY" | bc

Replace ‘BINARY‘ with the Binary number, viz.,

[[email protected] ~]- echo "ibase=2; 11010101" | bc 

213

Download Binary2Decimal.sh

Similarly you can write conversion from octal, hexadecimal to decimal and vice-versa yourself. Accomplishing the above result in terminal using ‘bc‘ command is.

Decimal to Octal
[[email protected] ~]- echo "obase=8; Decimal" | bc
Decimal to Hexadecimal
[[email protected] ~]- echo "obase=16; Decimal" | bc
Octal to Decimal
[[email protected] ~]- echo "ibase=8; Octal" | bc
Hexadecimal to Decimal
[[email protected] ~]- echo "ibase=16; Hexadecimal" | bc
Binary to Octal
[[email protected] ~]- echo "ibase=2;obase=8 Binary" | bc

Some of the Common Numeric tests used in shell scripting language with description is.

Test : INTEGER1 -eq INTEGER2
Meaning: INTEGER1 is equal to INTEGER2
Test : INTEGER1 -ge INTEGER2
Meaning: INTEGER1 is greater than or equal to INTEGER2
Test: INTEGER1 -gt INTEGER2
Meaning: INTEGER1 is greater than INTEGER2
Test:INTEGER1 -le INTEGER2
Meaning: INTEGER1 is less than or equal to INTEGER2
Test: INTEGER1 -lt INTEGER2
Meaning: INTEGER1 is less than INTEGER2
Test: INTEGER1 -ne INTEGER2
Meaning: INTEGER1 is not equal to INTEGER2

That’s all for this article, and the article series. This is the last article of Shell Script Series and it does not means that no article on Scripting language will be here again, it only means the shell scripting tutorial is over and whenever we find an interesting topic worth knowing or a query from you people, we will be happy to continue the series from here.

Stay healthy, tuned and connected to sfnews. Very soon I will be coming with another interesting topic, you people will love to read. Share your valuable thoughts in Comment Section.