Nothing Special   »   [go: up one dir, main page]

Exercise No 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

LINUX COMMANDS AND UBUNTU OS Exercise No 3

1)Write a shell script that accept a list of file names as arguments count and report
the occurrence of each word.

Code:-

#!/bin/bash

if [ $# -eq 0 ]; then
echo "No arguments"
else
tr " " "\n" < $1 > temp
shift
for i in "$@"; do
tr " " "\n" < "$i" > temp1
y=$(wc -l < temp)
j=1
while [ $j -le $y ]; do
x=$(head -n $j temp | tail -1)
c=$(grep -c "$x" temp1)
echo "$x $c"
j=$((j + 1))
done
done
fi

OUTPUT:

apple 4
grape 2
banana 3
orange 3
2).write a shell script to find the factorial of a given integer.

CODE:-

#!/bin/bash

factorial() {
if [ $1 -le 1 ]; then
echo 1
else
prev=$(factorial $(( $1 - 1 )))
echo $(( $1 * prev ))
fi
}

echo "Enter a number: "


read number

result=$(factorial $number)
echo "The factorial of $number is $result"

OUTPUT:-

~/19-12-2024$ sh fact.sh
Enter a number:
5
The factorial of 5 is 120

3)..write a shell script that lists all files in a directory.

CODE:-

#!/bin/bash
echo "Enter directory name:"
read dir
if [ -d "$dir" ]; then
echo "List of directories in the directory:"
ls -l "$dir" | egrep '^d'
else
echo "Enter a proper directory name."
fi

OUTPUT:-

~/19-12-2024$ sh third.sh
Enter directory name:
darshan
List of directories in the directory:
drwxr-xr-x 1 runner runner 24 Dec 19 03:35 darshan1

You might also like