Basic Linux Programs

Exercises-1:
Write a shell script sum.sh that takes an unspecified number of command line arguments (up
to 9) of ints and finds their sum. Modify the code to add a number to the sum only if the number
is greater than 10
Ans:
#! /bin/sh
sum=0
for var in “$@”
do
if [ $var –gt 10 ]
then
sum=`expr $sum + $var`
fi
done
printf “%s\n” $sum % sh 2.1.sh 2 4 5  — run the script as
**************************************************************************************************
Exercise-2
Write a shell script takes the name a path (eg:/afs/andrew/course/15/123/handin), and counts
all the sub directories (recursively).
Ans:
#! /bin/sh
ls –R $1 | wc –l
run the script as:
% sh 2.2.sh /afs/andrew/course/15/123/handin
*********************************************************
Exercise-3
Write a shell script that takes a file where each line is given in the format
F08,guna,Gunawardena,Ananda,SCS,CSD,3,L,4,15 123 ,G ,,
Creates a folder for each user name (eg: guna) and set the permission to rw access for user only
(hint: use fs sa)
Ans:
#! /bin/sh
cat $1 |
while read line
do
userid=`echo $line | cut –d”,” –f2`
mkdir $userid
fs sa $userid $userid rw
done
*****************************************************************
Exercise-4
Write a shell script that takes a name of a folder as a command line argument, and produce a
file that contains the names of all sub folders with size 0 (that is empty sub folders)
#! /bin/sh
ls $1 |
while read folder
do
if [ -d $1/$folder ]
then
files=`ls $1/$folder | wc –l`
if [ $files –eq 0 ]
then
echo $folder >> output.txt
fi
fi
done
*******************************************************************
Exercise-5
Write a shell script that takes a name of a folder, and delete all sub folders of size 0
#! /bin/sh
ls $1 |
while read folder
do
files=`ls $folder | wc –l`
if [ files –eq 0 ]
then
rmdir $folder
fi
done
*********************************************************************
Exercise-6
write a shell script that will take an input file and remove identical lines (or duplicate lines
from the file)
#! /bin/sh
cat $1 | sort |
while read line
do
if [ $prev!=$line ]
then
echo $line >> sorted.txt
fi
prev=$line
done