Wednesday, November 30, 2022

Make a duplicate copy of a specified file using bash shell script

 #!/usr/bin/bash

#if [ $# -lt 2 ] || [ $#  -gt 2 ]

#if test $# -lt 2 -o  $#  -gt 2

#if [[ $# -lt 2 ]] || [[  $#  -gt 2 ]]

if  (($# < 2)) || ((  $#  > 2 ))


then

echo invalid

exit

else

echo file to be copied : $1

echo new file name : $2

cp $1 $2

echo copy successful




fi

leap year program in bash shell script

#/usr/bin/bash

echo "Enter year"

read year

if [[ $(($year % 100)) -ne 0 ]]

#if (((year%100)!=0))

#if  [ $(($year % 100)) -ne 0 ]

then

if [ $(($year%4)) -eq 0 ]

then

echo "Leap Year"

else

echo "Not a leap year"

fi

else

if [ $(($year % 400)) -eq 0 ]

then

echo "Leap Year"

else

echo "Not a leap year"

fi

fi

Different ways to implement numerical comparisons using if else in bash

 #!/usr/bin/bash
echo "enter a number"
read num
if [[ $num -ge 1 ]] && [[ $num -lt 10 ]]
then
echo "A"
elif [[ $num -ge 10 ]] && [[ $num -lt 90 ]]
then
echo "B"
elif [[ $num -ge 90 ]] && [[ $num -lt 100 ]]
then
echo "C"
else
echo "D"
fi


#!/bin/bash
echo "enter a number"
read num
if (( num >= 1)) && ((num<10))
then
echo "sam"
elif ((num >= 10)) && ((num < 90 ))

then
echo "ram"
elif ((num >= 90)) && ((num  <100))
then
echo "rahim"
else
echo "tara"
fi

#!/bin/bash
echo "enter a number"
read num
if [ $num -ge 1 ] && [ $num -lt 10 ]
then
echo "A"
elif [ $num -ge 10 ] && [ $num -lt 90 ]
then
echo "B"
elif [ $num -ge 90 ] && [ $num -lt 100 ]
then
echo "C"
else
echo "D"
fi



Monday, November 28, 2022

Matching username from input with /etc/passwd without grep

 #/bin/bash

echo "enter username to check"

read username

match=0

for line in `cat /etc/passwd`

do


if test `echo $line | cut -d ":" -f 1| cut -d "," -f 1` == $username ;

then

#match=$(($match+1))

#let "match=match+1"

#let "match++"

((match++))

fi


done

if [ $match -gt 0 ];

then

echo "$username is valid because match is $match"

else

echo "$username is not valid because match is $match"

fi

Sunday, November 27, 2022

Get length of a string in bash shell script

#!/bin/bash

# Create a new string

mystring="lets count the length of this string"

i=${#mystring}

echo "Length: $i"


Source:https://www.hostinger.in/tutorials/bash-script-example

If else example in bash shell script,explanation on the difference ofusage of no bracket and single bracket after if

 #!/bin/bash

salary=1000

expenses=800

#Check if salary and expenses are equal

if test  $salary == $expenses ;

then

    echo "Salary and expenses are equal"

#Check if salary and expenses are not equal

elif test  $salary != $expenses ;

then

    echo "Salary and expenses are not equal"

fi



Now if we omit the single bracket [ after if we will encounter an error,the explanation is given below

[ is actually a command, equivalent (almost, see below) to the test command. It's not part of the shell syntax. (Both [ and test, depending on the shell, are often built-in commands as well, but that doesn't affect their behavior, except perhaps for performance.)

An if statement executes a command and executes the then part if the command succeeds, or the else part (if any) if it fails. (A command succeeds if it exits with a status ($?) of 0, fails if it exits with a non-zero status.)

In

if [ "$name" = 'Bob' ]; then ...

the command is

[ "$name" = 'Bob' ]

(You could execute that same command directly, without the if.)

In

if grep -q "$text" $file ; then ...

the command is

grep -q "$text" $file

man [ or man test for more information.

FOOTNOTE: Well, the [ command is almost equivalent to the test command. The difference is that [ requires ] as its last argument, and test does not -- and in fact doesn't allow it (more precisely, test doesn't treat a ] argument specially; for example it could be a valid file name). (It didn't have to be implemented that way, but a [ without a matching ] would have made a lot of people very very nervous.)


Source:https://stackoverflow.com/questions/8934012/when-are-square-brackets-required-in-a-bash-if-statement

Array example in bash shell script

 #!/bin/bash

# Create an indexed array

IndexedArray=(egg burger milk)

#Iterate over the array to get all the values

for i in "${IndexedArray[@]}";do echo "$i";done


Source:https://www.hostinger.in/tutorials/bash-script-example

Thursday, November 24, 2022

Create a file and write something to it using perl

 use strict;

use warnings;

$|=1;

sub main{

my $output='output.txt';

open(OUTPUT,'>'.$output)or die "Can't create $output.\n";

print OUTPUT "Hello\n";

close(OUTPUT);

}

main();


Read lines from a text file and print those lines based on condition using perl

 use strict;

use warnings;

#disabling output buffering

$|=1;


sub main{

#my @files=('./a.txt','./b.txt','./c.txt',);

my $file='./a.txt';

open(INPUT,$file) or die("Input file $file not found.\n");

while(my $line=<INPUT>)

{

if($line=~/abc/)

{


print $line;

}

}

close(INPUT);

}

main();


Check the existence of multiple files using array in perl

                                          

 use strict;

use warnings;

#disabling output buffering

$|=1;


sub main{

my @files=('./a.txt','./b.txt','./c.txt',);

#my $file='./a.txt';

foreach my $file(@files){

print "$file\n";


if(-f $file)

{

print "$file exists\n";


}

else

{


print "$file does not exist\n";


}

}

}

main();


else

{


print "$file does not exist\n";


}

}

}

main();

Check if a file exists using perl

 use strict;

use warnings;

sub main{

my $file='./a.txt';

if(-f $file)

{

print "$file exists\n";


}

else

{


print "$file does not exist\n";


}

}

main();

Find the files created in the guest machine in windows subsystem in linux (WSL2)

 In the guest terminal 

just enter:

explorer.exe .
 
Source:https://superuser.com/questions/1185033/what-is-the-home-directory-on-windows-subsystem-for-linux 

Check if an username is present in /etc/passwd using shell script

 #!/bin/bash
read -rep $'Please enter username\n' username
#echo "you have entered $username"
if [ `grep -c $username /etc/passwd` -eq 0 ]
then
echo "$username is invalid"
else
echo "$username is valid"
fi

Wednesday, November 23, 2022

Storing the source code of a webpage in a variable using lwp and perl

use strict;
use warnings;
use LWP::Simple;
sub main{
print "Downloading ... \n";
#print get("http://www.google.com/");
#getstore("http://www.google.com","./source.code.html");
#to receive the response just as string we need to use single quote
#getstore('https://en.wikipedia.org/wiki/Main_Page#/media/File:Kathryn_Sullivan,_PCAST_Member_(cropped).jpg','face.jpg'>
my $code=getstore('https://en.wikipedia.org/wiki/Main_Page#/media/File:Kathryn_Sullivan,_PCAST_Member_(cropped).jpg','f>if($code==200)
{
print "Success\n";
}
else{
print "Failed\n";
}


print "Finished\n";
}
main();

Downloading and storing the source code of a web page in a file using lwp and perl

 use strict;
use warnings;
use LWP::Simple;
sub main{
print "Downloading ... \n";
#print get("http://www.google.com/");
getstore("http://www.google.com","./source.code.html");

print "Finished\n";
}
main();

Downloading and printing html css code of a page using perl and lwp

 use strict;
use warnings;
use LWP::Simple;
sub main{
print "Downloading ... \n";
print get("http://www.google.com/");
print "Finished\n";
}
main();

Tuesday, November 22, 2022

Newline character inside read in bash

 

read -rep $'Please Enter a Message:\n' message

Find size of individual files of a particular extension in bash

 echo "enter extension"
read ext
for i in `find . -name "*.$ext" -type f`; do
   # echo "$i"
   echo `du -k "$i" | cut -f1`
done

Find files of a particular extension in bash

 echo "enter extension"
read ext
for i in `find . -name "*.$ext" -type f`; do
    echo "$i"
done

Find total size of files of an extension given as input in bash

 #!/bin/bash
echo "Please enter extension"
read ext
total=0
for i in $(pwd)/*.$ext

do

#filesize=$((`stat --printf="%s" $i`))
#filesize=$((`wc -c $i | awk '{print $1}'))
filesize=$((`wc -c $i | cut -d " " -f 1`))
total=$(($total+$filesize))
done

echo "The total size of $ext files in present directory is $total"

#alternate way


#!/usr/bin/bash
read -rep $'Please enter the extension\n' ext
total=0
for i in `ls`
do
if [[ "$i" == *"$ext"* ]]
then
#echo $i
total=$(($total + `du -k $i | cut -f 1`))
fi
done
echo "The total size of $ext files is $total"







Thursday, November 17, 2022

Some bash keyboard shortcuts and special characters

Some bash keyboard shortcuts


  • Esc + T: Swap the last two words before the cursor
  • Ctrl + H: Delete the letter starting at the cursor
  • Ctrl + W: Delete the word starting at the cursor
  • TAB: Auto-complete files, directory, command names and much more
  • Ctrl + R: To see the command history.
  • Ctrl + U: Clear the line
  • Ctrl + C: Cancel currently running commands.
  • Ctrl + L: Clear the screen
  • Ctrl + T: Swap the last two characters before the cursor

Some bash special characters

Characters Description
/ Directory separator, used to separate a string of directory names. Example: /home/projects/file
\ Escape character. If you want to reference a special character, you must “escape” it with a backslash first. Example: \n means newline; \v means vertical tab; \r means return
# Lines starting with # will not be executed. These lines are comments
. Current directory. When its the first character in a filename, it can also “hide” files
.. Returns the parent directory
~ Returns user’s home directory
~+ Returns the current working directory. It corresponds to the $PWD internal variable
~- Returns the previous working directory. It corresponds to the $OLDPWD internal variable
* Represents 0 or more characters in a filename, or by itself, it matches all files in a directory. Example: file*2019 can return: file2019, file_comp2019, fileMay2019
[] Can be used to represent a range of values, e.g. [0-9], [A-Z], etc. Example: file[3-5].txt represents file3.txt, file4.txt, file5.txt
| Known as “pipe". It redirects the output of the previous command into the input of the next command. Example: ls | less
< It redirects a file as an input to a program. Example: more < file.txt
> In script name >filename it will redirect the output of “script name” to “file filename”. Overwrite filename if it already exists. Example: ls > file.txt
>> Redirect and append the output of the command to the end of the file. Example: echo "To the end of file" >> file.txt
& Execute a job in the background and immediately get your shell back. Example: sleep 10 &
&& “AND logical operator”. It returns (success) only if both the linked test conditions are true. It would run the second command only if the first one ran without errors. Example: let "num = (( 0 && 1 ))"; cd/comp/projs && less messages
; “Command separator”. Allows you to execute multiple commands in a single line. Example: cd/comp/projs ; less messages
? This character serves as a single character in a filename. Example: file?.txt can represent file1.txt, file2.txt, file3.txt

 

Wednesday, November 16, 2022

Some loop examples in bash scripting for and while

 
for i in  1 2 3 4 5
do
echo "Maharshi"
done

for i in  {0..10..5}
do
echo -e "Maharshi\t$i"
done

for i in  {10..0..-5}
do
echo -e "Maharshi\t$i"
done

for i in {1..10}
do
printf "%s\n%s\n" "Galgotias" "UNiversity";
done


for i in $(seq 1 10)
do
printf "%s\n%s\n" "Galgotias" "UNiversity";
done


for i in $(seq 1 2 10)
do
printf "i is %d\n" "$i";
done

for i in $(seq 10 -2 1)
do
printf "i is %d\n" "$i";
done

for((i=4;i<10;i++))
do
echo "Maharshi";
done

echo "enter a number";
read number;
if (((number < 10))  &&  ((number > 1)))||(((number<100))&&((number>90)))
then
echo $number;
fi

i=0
while ((i < 5 ))
do
echo "maharshi";
i=$(($i+1));
done

arithmatic expansion

i=15;
i=$(($i*5));
echo $i;

Digonal number pattern in bash solved

  printf "Enter row number";
    read n;
    c=1
    for((i=1;i<=(n-1);i++))
    {
   
        for((j=1;j<=(n-1);j++))
        {
            if(((i==j)||(j==(n-i))))
            then
            printf $c ;
            else
            printf " ";
            fi
        }
        if ((c>=4))
        then
        ((c=c-1));
        else
        ((c=c+1));
        fi
        printf "\n";
    }

 

 


Monday, November 14, 2022

Set up cgi-perl in Debian 11

apt-get install apache2

/sbin/a2enmod cgid


systemctl restart apache2


cd /usr/lib/cgi-bin


nano /usr/lib/cgi-bin/test.pl


#!/usr/bin/perl

print "Content-Type: text/html\n\n";

print ("<h1>Perl is working!</h1>");

chmod 755 /usr/lib/cgi-bin/test.pl

http://172.31.8.195/cgi-bin/test.pl


Source: https://techexpert.tips/apache/perl-cgi-apache/

Some bash shell script examples for beginners

 even odd


echo "Please enter a number"
read num
if [ `expr $num % 2`  == 0 ]
then
echo "$num is even"
else
echo "$num is odd"
fi


largest of three numbers

echo "please enter 3 numbers"
read num1
read num2
read num3

if test $num1 -gt $num2 -a $num1 -gt $num3
then
echo "$num1 is the greatest"
elif test $num2 -gt $num3
then
echo "$num2 is the greatest"
else
echo "$num3 is the greatest"
fi


calculate net salary


echo "enter basic salary"
read bs
hra=`echo $bs*10/100 | bc`
ta=`echo $bs*15/100 | bc`
da=`echo $bs*2/100 | bc`
pf=`echo $bs*10/100 | bc`
tax=`echo $bs*5/100 | bc`

netsal=`echo $bs+$hra+$ta+$da-$pf-$tax | bc`
echo "net salary is $netsal"


calculate conditional discount and tax


echo  "please enter the amount that you want to buy"
read amount
if test  $amount -lt 1000
then
tax=`echo $amount \* 2/100 | bc`
discount=`echo $amount \* 10/100 | bc`
else
tax=`echo $amount \* 5/100 | bc`
discount=`echo $amount \* 20/100 | bc`
fi

totalcost=`echo $amount - $tax + $discount | bc`
echo  "total cost is $totalcost"