Difference between revisions of "Chapter 5 answers"

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to navigation Jump to search
m (Text replacement - "</source>" to "</syntaxhighlight>")
 
(14 intermediate revisions by 4 users not shown)
Line 15: Line 15:
  
 
* Write a menu driven script using the select statement to print calories for food items such as pizza, burger, Salad, Pasta etc.
 
* Write a menu driven script using the select statement to print calories for food items such as pizza, burger, Salad, Pasta etc.
<source lang="bash"></source>
+
<syntaxhighlight lang="bash" ></syntaxhighlight>
  
 
----
 
----
  
 
* Write a shell script that, given a file name as the argument will count vowels, blank spaces, characters, number of line and symbols.
 
* Write a shell script that, given a file name as the argument will count vowels, blank spaces, characters, number of line and symbols.
<source lang="bash"></source>
+
<syntaxhighlight lang="bash" >#!/bin/bash
 
+
file=$1
 +
v=0
 +
 +
if [ $# -ne 1 ]
 +
then
 +
echo "$0 fileName"
 +
exit 1
 +
fi
 +
if [ ! -f $file ]
 +
then
 +
echo "$file not a file"
 +
exit 2
 +
fi
 +
 +
while read -n 1 c
 +
do
 +
  l=$(echo $c | tr [:upper:] [:lower:])
 +
  [[ "$l" == "a" || "$l" == "e" || "$l" == "i" || "$l" == "o" || "$l" == "u" ]] && (( v++ ))
 +
done < $file
 +
 +
echo "Vowels : $v"
 +
echo "Characters : $(cat $file | wc -c)"
 +
echo "Blank lines : $(grep  -c '^$' $file)"
 +
echo "Lines : $(cat $file|wc -l )"</syntaxhighlight>
 
----
 
----
  
 
* Write a shell script that, given a file name as the argument will count English language articles such As 'A', 'An' and 'The'.
 
* Write a shell script that, given a file name as the argument will count English language articles such As 'A', 'An' and 'The'.
<source lang="bash"></source>
+
<syntaxhighlight lang="bash" >#!/bin/bash
 +
file=$1
 +
a=0
 +
 +
if [ $# -ne 1 ]
 +
then
 +
echo "$0 fileName"
 +
exit 1
 +
fi
 +
if [ ! -f $file ]
 +
then
 +
echo "$file not a file"
 +
exit 2
 +
fi
 +
 +
while read line
 +
do
 +
  l=$(echo $line | tr [:upper:] [:lower:])
 +
 
 +
for word in $l
 +
do
 +
[[ $word == "a" || $word == "an" || $word == "the" ]] && ((a++))
 +
done
 +
 
 +
done < $file
 +
 +
echo "articles : $a"</syntaxhighlight>
  
 
----
 
----
  
 
* Write a shell script that, given a file name as the argument will write the even numbered line to a file with name evenfile and odd numbered lines in a text file called oddfile.
 
* Write a shell script that, given a file name as the argument will write the even numbered line to a file with name evenfile and odd numbered lines in a text file called oddfile.
<source lang="bash"></source>
+
<syntaxhighlight lang="bash" >#!/bin/bash
 +
file=$1
 +
counter=0
 +
 +
if [ $# -ne 1 ]
 +
then
 +
echo "$0 fileName"
 +
exit 1
 +
fi
 +
if [ ! -f $file ]
 +
then
 +
echo "$file not a file"
 +
exit 2
 +
fi
 +
 +
while read line
 +
do
 +
((counter++))
 +
EvenNo=$(( counter%2 ))
 +
 
 +
if [ $EvenNo -eq 0 ]
 +
then
 +
echo $line >> evenfile
 +
else
 +
echo $line >> oddfile
 +
fi
 +
 
 +
done < $file</syntaxhighlight>
  
 
----
 
----
  
 
* Write a shell script to monitor Linux server disk space using a while loop. Send an email alert when percentage of used disk space is >= 90%.
 
* Write a shell script to monitor Linux server disk space using a while loop. Send an email alert when percentage of used disk space is >= 90%.
<source lang="bash"></source>
+
<syntaxhighlight lang="bash" >#!/bin/bash
 +
ADMIN="me@somewher.com"
 +
# set alert level 90% is default
 +
ALERT=90
 +
df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
 +
do
 +
  #echo $output
 +
  usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1  )
 +
  partition=$(echo $output | awk '{ print $2 }' )
 +
  if [ $usep -ge $ALERT ]; then
 +
    echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" |
 +
    mail -s "Alert: Almost out of disk space $usep" $ADMIN
 +
  fi
 +
done</syntaxhighlight>
  
 
----
 
----
  
 
* Write a shell script to determine if an input number is a palindrome or not. A palindromic number is a number where the digits, with decimal representation usually assumed, are the same read backwards, for example, 58285.
 
* Write a shell script to determine if an input number is a palindrome or not. A palindromic number is a number where the digits, with decimal representation usually assumed, are the same read backwards, for example, 58285.
<source lang="bash"></source>
+
<syntaxhighlight lang="bash" >#!/bin/bash
 +
echo -n "Enter number : "
 +
read n
 +
 +
# store single digit
 +
sd=0
 +
 +
# store number in reverse order
 +
rev=""
 +
 +
# store original number
 +
on=$n
 +
 +
while [ $n -gt 0 ]
 +
do
 +
    sd=$(( $n % 10 )) # get Remainder
 +
    n=$(( $n / 10 ))  # get next digit
 +
    # store previous number and current digit in reverse
 +
    rev=$( echo ${rev}${sd} )
 +
done
 +
 +
if [ $on -eq $rev ];
 +
then
 +
  echo "Number is palindrome"
 +
else
 +
  echo "Number is NOT palindrome"
 +
fi</syntaxhighlight>
  
 
----
 
----
  
 
* Write a shell program to read a number *such as 123) and find the sum of digits (1+2+3=6).
 
* Write a shell program to read a number *such as 123) and find the sum of digits (1+2+3=6).
<source lang="bash"></source>
+
<syntaxhighlight lang="bash" >#!/bin/bash
 +
 
 +
#store the no
 +
num=$1
 +
 
 +
#store the value of sum
 +
sum=0
 +
 +
if [ $# -ne 1 ]
 +
then
 +
echo "$0 number"
 +
exit 1
 +
fi
 +
 
 +
while [ $num -gt 0 ]
 +
do
 +
digit=$(( num%10 ))
 +
num=$(( num/10 ))
 +
sum=$(( digit+sum ))
 +
done
 +
 
 +
echo "Sum of digits = $sum"</syntaxhighlight>
  
 
----
 
----
  
 
* Write a shell program to read a number and display reverse the number. For example, 123 should be printed as as 321.
 
* Write a shell program to read a number and display reverse the number. For example, 123 should be printed as as 321.
<source lang="bash"></source>
+
<syntaxhighlight lang="bash" >#!/bin/bash
 +
 
 +
#store the no
 +
num=$1
 +
 
 +
#store the reverse number
 +
rev=0
 +
 +
if [ $# -ne 1 ]
 +
then
 +
echo "$0 number"
 +
exit 1
 +
fi
 +
 
 +
while [ $num -gt 0 ]
 +
do
 +
digit=$(( num%10 ))
 +
num=$(( num/10 ))
 +
rev=$(( digit + rev*10 ))
 +
done
 +
 
 +
echo "Reverse of number = $rev"</syntaxhighlight>
  
 
----
 
----
  
* Write the shell program which produces a report from the output of ls -l in the following format using the for loop statement:
+
* Write the shell program which produces a report from the output of ls -l in the following format:
 
<pre>file1
 
<pre>file1
 
file2
 
file2
Line 62: Line 219:
 
Total symbolic links : 0
 
Total symbolic links : 0
 
Total size of regular files : 2940</pre>
 
Total size of regular files : 2940</pre>
<source lang="bash"></source>
+
<syntaxhighlight lang="bash" >#!/bin/bash
 +
 
 +
#copying the out of ls -l command to a file
 +
ls -l > /tmp/tmp.tmp
 +
 
 +
#initilizing values
 +
sum=0
 +
dir=0
 +
file=0
 +
link=0
 +
 
 +
#reading the file
 +
while read line
 +
do
 +
#getting the first character of each line to check the type of file
 +
read -n 1 c <<< $line
 +
 
 +
#checking if the file is a directory or not
 +
if [ $c == "d" ]
 +
then
 +
((dir++))
 +
echo "[DIR] ${line}/" | cut -d" " --fields="1 9" >> /tmp/dir.tmp
 +
 
 +
elif [ $c == "-" ] #true if the file is a regular file
 +
then
 +
((file++))
 +
echo $line | cut -d" " -f8 >> /tmp/file.tmp
 +
 
 +
elif [ $c == "l" ]  #true if the file is a symbolic link
 +
then
 +
((link++))
 +
fi
 +
 +
size=$( echo $line | cut -d" " -f5 ) #getting the size of the file
 +
sum=$(( sum+size )) #adding the size of all the files
 +
done < /tmp/tmp.tmp
 +
 
 +
cat /tmp/file.tmp #output the name of all the files
 +
cat /tmp/dir.tmp #output the name of all the directory
 +
 
 +
echo "Total regular files = $file"
 +
echo "Total directories = $dir"
 +
echo "Total symbolic links = $link"
 +
echo "Total size of regular file = $size"
 +
 
 +
#removing the temporary files
 +
rm /tmp/file.tmp
 +
rm /tmp/dir.tmp
 +
rm /tmp/tmp.tmp
 +
</syntaxhighlight>
  
 
----
 
----
  
 
* Write a  shell script that will count the number of files in each of your sub-directories using the for loop.
 
* Write a  shell script that will count the number of files in each of your sub-directories using the for loop.
<source lang="bash"></source>
+
<syntaxhighlight lang="bash" >#!/bin/bash
 +
 
 +
START=$HOME
 +
 +
# change your directory to command line if passed
 +
# otherwise use home directory
 +
[ $# -eq 1 ] && START=$1
 +
 +
if [ ! -d $START ]
 +
then
 +
echo "$START not a directory!"
 +
exit 1
 +
fi
 +
 +
# use find command to get all subdirs name in DIRS variable
 +
DIRS=$(find "$START" -type d)
 +
 +
# loop thought each dir to get the number of files in each of subdir
 +
for d in $DIRS
 +
do
 +
  [ "$d" != "." -a "$d" != ".." ] &&  echo "$d dirctory has $(ls -l $d | wc -l) files"
 +
done</syntaxhighlight>
  
 
----
 
----
  
 
* Write a shell script that accepts two directory names as arguments and deletes those files in the first directory which are similarly named in the second directory.
 
* Write a shell script that accepts two directory names as arguments and deletes those files in the first directory which are similarly named in the second directory.
<source lang="bash"></source>
+
<syntaxhighlight lang="bash" >#!/bin/bash
 +
 
 +
SRC="$1"
 +
DST="$2"
 +
if [ $# -ne 2 ]
 +
then
 +
        echo "$(basename $0) dir1 dir2"
 +
        exit 1
 +
fi
 +
 +
if [ ! -d $SRC ]
 +
then
 +
        echo "Directory $SRC does not exists!"
 +
        exit 2
 +
fi
 +
 +
if [ ! -d $DST ]
 +
then
 +
        echo "Directory $DST does not exists!"
 +
        exit 2
 +
fi
 +
 +
for f in $DST/*
 +
do
 +
#echo Processing $f
 +
        if [ -f $f ]
 +
        then
 +
                tFile="$SRC/$(basename $f)"
 +
                if [ -f $tFile ]
 +
                then
 +
                        echo -n "Deleting $tFile..."
 +
                        /bin/rm $tFile
 +
                        [ $? -eq 0 ] && echo "done" || echo "failed"
 +
 +
                fi
 +
        fi
 +
done</syntaxhighlight>
  
 
----
 
----
  
 
* Write a shell script to search for no password entries in /etc/passwd  and lock all accounts.
 
* Write a shell script to search for no password entries in /etc/passwd  and lock all accounts.
<source lang="bash"></source>
+
<syntaxhighlight lang="bash" >#!/bin/bash
 +
# Shell script for search for no password entries and lock all accounts
 +
# Set your email
 +
ADMINEMAIL="admin@somewhere.com"
 +
 +
### Do not change anything below ###
 +
#LOG File
 +
LOG="/root/nopassword.lock.log"
 +
STATUS=0
 +
TMPFILE="/tmp/null.mail.$$"
 +
 +
echo "-------------------------------------------------------" >>$LOG
 +
echo "Host: $(hostname),  Run date: $(date)" >> $LOG
 +
echo "-------------------------------------------------------" >>$LOG
 +
 +
# get all user names
 +
USERS="$(cut -d: -f 1 /etc/passwd)"
 +
 +
# display message
 +
echo "Searching for null password..."
 +
for u in $USERS
 +
do
 +
  # find out if password is set or not (null password)
 +
  passwd -S $u | grep -Ew "NP" >/dev/null
 +
  if [ $? -eq 0 ]; then # if so
 +
    echo "$u" >> $LOG
 +
    passwd -l $u #lock account
 +
    STATUS=1  #update status so that we can send an email
 +
  fi
 +
done
 +
echo "========================================================" >>$LOG
 +
if [ $STATUS -eq 1 ]; then
 +
  echo "Please see $LOG file and all account with no password are locked!" >$TMPFILE
 +
  echo "-- $(basename $0) script" >>$TMPFILE
 +
  mail -s "Account with no password found and locked" "$ADMINEMAIL" < $TMPFILE
 +
#  rm -f $TMPFILE
 +
fi</syntaxhighlight>
  
 
----
 
----
  
 
* Write a shell program to read two numbers and display all the odd numbers between those two numbers.
 
* Write a shell program to read two numbers and display all the odd numbers between those two numbers.
<source lang="bash"></source>
+
<syntaxhighlight lang="bash" >#!/bin/bash
 +
# Shell program to read two numbers and display all the odd
 +
 
 +
echo -n "Enter first number : "
 +
read n1
 +
 +
echo -n "Enter second number : "
 +
read n2
 +
 +
if [ $n2 -gt $n1 ];
 +
then
 +
  for(( i=$n1; i<=$n2; i++ ))
 +
  do
 +
    # see if it is odd or even number
 +
    test=$(( $i % 2 ))
 +
    if [ $test -ne 0 ];
 +
    then
 +
      echo $i
 +
    fi
 +
  done
 +
else
 +
  echo "$n2 must be greater than $n1, try again..."
 +
fi</syntaxhighlight>
  
 
----
 
----

Latest revision as of 22:50, 29 March 2016

← Chapter 5 ChallengesHomeChapter 6: Shell Redirection →

  • Decide whether the following sentence is true or false:
  1. False
  2. False
  3. False
  4. False
  5. True
  6. True
  7. True

  • Write a menu driven script using the select statement to print calories for food items such as pizza, burger, Salad, Pasta etc.

  • Write a shell script that, given a file name as the argument will count vowels, blank spaces, characters, number of line and symbols.
#!/bin/bash
file=$1
v=0
 
if [ $# -ne 1 ]
then
	echo "$0 fileName"
	exit 1
fi
if [ ! -f $file ]
then
	echo "$file not a file"
	exit 2
fi
 
while read -n 1 c
do
  l=$(echo $c | tr [:upper:] [:lower:])
  [[ "$l" == "a" || "$l" == "e" || "$l" == "i" || "$l" == "o" || "$l" == "u" ]] && (( v++ ))
done < $file
 
echo "Vowels : $v"
echo "Characters : $(cat $file | wc -c)"
echo "Blank lines : $(grep  -c '^$' $file)"
echo "Lines : $(cat $file|wc -l )"

  • Write a shell script that, given a file name as the argument will count English language articles such As 'A', 'An' and 'The'.
#!/bin/bash
file=$1
a=0
 
if [ $# -ne 1 ]
then
	echo "$0 fileName"
	exit 1
fi
if [ ! -f $file ]
then
	echo "$file not a file"
	exit 2
fi
 
while read line
do
  l=$(echo $line | tr [:upper:] [:lower:])

for word in $l
do
	[[ $word == "a" || $word == "an" || $word == "the" ]] && ((a++))
done

done < $file
 
echo "articles : $a"

  • Write a shell script that, given a file name as the argument will write the even numbered line to a file with name evenfile and odd numbered lines in a text file called oddfile.
#!/bin/bash
file=$1
counter=0
 
if [ $# -ne 1 ]
then
	echo "$0 fileName"
	exit 1
fi
if [ ! -f $file ]
then
	echo "$file not a file"
	exit 2
fi
 
while read line
do
	((counter++))
	EvenNo=$(( counter%2 ))

	if [ $EvenNo -eq 0 ] 
	then
		echo $line >> evenfile 
	else
		echo $line >> oddfile
	fi

done < $file

  • Write a shell script to monitor Linux server disk space using a while loop. Send an email alert when percentage of used disk space is >= 90%.
#!/bin/bash
ADMIN="me@somewher.com"
# set alert level 90% is default
ALERT=90
df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
  #echo $output
  usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1  )
  partition=$(echo $output | awk '{ print $2 }' )
  if [ $usep -ge $ALERT ]; then
    echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" |
     mail -s "Alert: Almost out of disk space $usep" $ADMIN
  fi
done

  • Write a shell script to determine if an input number is a palindrome or not. A palindromic number is a number where the digits, with decimal representation usually assumed, are the same read backwards, for example, 58285.
#!/bin/bash
echo -n "Enter number : "
read n
 
# store single digit
sd=0
 
# store number in reverse order
rev=""
 
# store original number
on=$n
 
while [ $n -gt 0 ]
do
    sd=$(( $n % 10 )) # get Remainder
    n=$(( $n / 10 ))  # get next digit
    # store previous number and current digit in reverse
    rev=$( echo ${rev}${sd} )
done
 
if [ $on -eq $rev ];
then
  echo "Number is palindrome"
else
  echo "Number is NOT palindrome"
fi

  • Write a shell program to read a number *such as 123) and find the sum of digits (1+2+3=6).
#!/bin/bash

#store the no
num=$1

#store the value of sum
sum=0
 
if [ $# -ne 1 ]
then
	echo "$0 number"
	exit 1
fi

while [ $num -gt 0 ] 
do
	digit=$(( num%10 ))
	num=$(( num/10 ))
	sum=$(( digit+sum ))
done 

echo "Sum of digits = $sum"

  • Write a shell program to read a number and display reverse the number. For example, 123 should be printed as as 321.
#!/bin/bash

#store the no
num=$1

#store the reverse number
rev=0
 
if [ $# -ne 1 ]
then
	echo "$0 number"
	exit 1
fi

while [ $num -gt 0 ] 
do
	digit=$(( num%10 ))
	num=$(( num/10 ))
	rev=$(( digit + rev*10 ))
done 

echo "Reverse of number = $rev"

  • Write the shell program which produces a report from the output of ls -l in the following format:
file1
file2
[DIR] test/
Total regular files : 7
Total directories : 4
Total symbolic links : 0
Total size of regular files : 2940
#!/bin/bash

#copying the out of ls -l command to a file
ls -l > /tmp/tmp.tmp

#initilizing values
sum=0
dir=0
file=0
link=0

#reading the file
while read line
do 
	#getting the first character of each line to check the type of file 	
	read -n 1 c <<< $line

	#checking if the file is a directory or not
	if [ $c == "d" ] 
	then
		((dir++))
		echo "[DIR] ${line}/" | cut -d" " --fields="1 9" >> /tmp/dir.tmp

	elif [ $c == "-" ] #true if the file is a regular file
	then
		((file++))
		echo $line | cut -d" " -f8 >> /tmp/file.tmp

	elif [ $c == "l" ]  #true if the file is a symbolic link
	then
		((link++))
	fi
	
	size=$( echo $line | cut -d" " -f5 ) #getting the size of the file
	sum=$(( sum+size )) #adding the size of all the files 
done < /tmp/tmp.tmp

cat /tmp/file.tmp #output the name of all the files
cat /tmp/dir.tmp #output the name of all the directory

echo "Total regular files = $file"
echo "Total directories = $dir"
echo "Total symbolic links = $link"
echo "Total size of regular file = $size"

#removing the temporary files
rm /tmp/file.tmp
rm /tmp/dir.tmp
rm /tmp/tmp.tmp

  • Write a shell script that will count the number of files in each of your sub-directories using the for loop.
#!/bin/bash

START=$HOME
 
# change your directory to command line if passed
# otherwise use home directory
[ $# -eq 1 ] && START=$1 
 
if [ ! -d $START ]
then
	echo "$START not a directory!"
	exit 1
fi
 
# use find command to get all subdirs name in DIRS variable
DIRS=$(find "$START" -type d)
 
# loop thought each dir to get the number of files in each of subdir
for d in $DIRS
do
   [ "$d" != "." -a "$d" != ".." ] &&  echo "$d dirctory has $(ls -l $d | wc -l) files" 
done

  • Write a shell script that accepts two directory names as arguments and deletes those files in the first directory which are similarly named in the second directory.
#!/bin/bash

SRC="$1"
DST="$2"
if [ $# -ne 2 ]
then
        echo "$(basename $0) dir1 dir2"
        exit 1
fi
 
if [ ! -d $SRC ]
then
        echo "Directory $SRC does not exists!"
        exit 2
fi
 
if [ ! -d $DST ]
then
        echo "Directory $DST does not exists!"
        exit 2
fi
 
for f in $DST/*
do
#echo Processing $f
        if [ -f $f ]
        then
                tFile="$SRC/$(basename $f)"
                if [ -f $tFile ]
                then
                        echo -n "Deleting $tFile..."
                        /bin/rm $tFile
                        [ $? -eq 0 ] && echo "done" || echo "failed"
 
                fi
        fi
done

  • Write a shell script to search for no password entries in /etc/passwd and lock all accounts.
#!/bin/bash
# Shell script for search for no password entries and lock all accounts
# Set your email
ADMINEMAIL="admin@somewhere.com"
 
### Do not change anything below ###
#LOG File
LOG="/root/nopassword.lock.log"
STATUS=0
TMPFILE="/tmp/null.mail.$$"
 
echo "-------------------------------------------------------" >>$LOG
echo "Host: $(hostname),  Run date: $(date)" >> $LOG
echo "-------------------------------------------------------" >>$LOG
 
# get all user names
USERS="$(cut -d: -f 1 /etc/passwd)"
 
# display message
echo "Searching for null password..."
for u in $USERS
do
  # find out if password is set or not (null password)
   passwd -S $u | grep -Ew "NP" >/dev/null
   if [ $? -eq 0 ]; then # if so
     echo "$u" >> $LOG
     passwd -l $u #lock account
     STATUS=1  #update status so that we can send an email
   fi
done
echo "========================================================" >>$LOG
if [ $STATUS -eq 1 ]; then
   echo "Please see $LOG file and all account with no password are locked!" >$TMPFILE
   echo "-- $(basename $0) script" >>$TMPFILE
   mail -s "Account with no password found and locked" "$ADMINEMAIL" < $TMPFILE
#   rm -f $TMPFILE
fi

  • Write a shell program to read two numbers and display all the odd numbers between those two numbers.
#!/bin/bash
# Shell program to read two numbers and display all the odd

echo -n "Enter first number : "
read n1
 
echo -n "Enter second number : "
read n2
 
if [ $n2 -gt $n1 ];
then
  for(( i=$n1; i<=$n2; i++ ))
  do
    # see if it is odd or even number
    test=$(( $i % 2 ))
    if [ $test -ne 0 ];
    then
      echo $i
    fi
  done
else
  echo "$n2 must be greater than $n1, try again..."
fi

← Chapter 5 ChallengesHomeChapter 6: Shell Redirection →