LINUX BASH BASIC SHELL SCRIPTS

in #linux6 years ago (edited)

The simplest Hello World shell script – Echo command

Input:
$ echo '#!/bin/sh' > bscs.sh
$ echo 'echo Hello World' >> bscs.sh
$ chmod 755 bscs.sh
#755 means full permissions owner and read and execute permission for others.
$ ./my-script.sh

Output
Hello World

Summation of two integers

Input:
$ echo -n "Enter the first number: "
read num1
$ echo -n "Enter the second number: "
read num2
sum=expr $num1 + $num2
$ echo "Sum of two values is $sum"

Output:
Enter the first number: 23
Enter the second number: 45
Sum of two values is 68

Summation of two real numbers

Input
$ echo 'scale=10;57/43' | bc

Output
1.3255813953

To find out the biggest number in 3 numbers

Input:
$ echo "Enter the three numbers which are to be compared"
read var1 var2 var3
if [[ $var1 > $var2 ]] && [[ $var1 > $var3 ]];then
$ echo "$var1 is greatest of three numbers"
elif [[ $var2 > $var1 ]] && [[ $var2 > $var3 ]];then
$ echo "$var2 is greatest of three number"
elif [[ $var3 > $var1 ]] && [[ $var3 > $var2 ]];then
$ echo "$var3 is greater of three numbers"
else
$ echo " All the three numbers are equal"
fi

Output:
Enter the three numbers which are to be compared
10 15 16
16 is greater of three numbers

Operation (summation, subtraction, multiplication and division) of two numbers

Addition
$ echo "5+5" | bc
10

Subtraction
$ echo "10-3" | bc
7

Multiplication
$ echo "3*3" | bc
9

Division:
$ echo 'scale=10;57/43' | bc
1.3255813953

Script to reverse a given number

Input:
#!/bin/bash
clear
read -p "Enter a number: " num
$ echo $num | rev

Output:
Enter a number:
16
61

Calculating factorial of a given number

Input:
#!/bin/bash
fact=1
#input from user
$ echo -e "Enter a number"
read n
#if entered value is less than 0
if [ $n -le 0 ] ; then
$ echo "Number should not be less than zero"
exit
fi
#factorial logic
if [ $n -gt 0 ] ; then
for((i=$n;i>=1;i--))
do
fact=expr $fact \* $i
done
fi
$ echo "The factorial of $n is $fact"

Output:
Enter a number
5
The factorial of 5 is 120

Coin Marketplace

STEEM 0.20
TRX 0.16
JST 0.030
BTC 65792.18
ETH 2695.80
USDT 1.00
SBD 2.90