0% found this document useful (0 votes)
2 views

osLab

The document outlines various shell scripts aimed at performing different tasks such as assigning file permissions, creating directories, checking file existence, compressing files, searching patterns, calculating sums, and more. Each task includes an algorithm and a program demonstrating the implementation of the described functionality. The results confirm that the scripts meet their respective aims.

Uploaded by

parasagrawal9889
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

osLab

The document outlines various shell scripts aimed at performing different tasks such as assigning file permissions, creating directories, checking file existence, compressing files, searching patterns, calculating sums, and more. Each task includes an algorithm and a program demonstrating the implementation of the described functionality. The results confirm that the scripts meet their respective aims.

Uploaded by

parasagrawal9889
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

1.

Write a shell Script to assign a file permission to the given file using Symbolic
Mode/Absolute Mode.
AIM: Assign file permissions to a given file using Symbolic Mode or Absolute Mode.

ALGORITHM:
1.Accept the file name and the desired permission mode (Symbolic or Absolute) as inputs.

2.Check if the file exists. If not, display an error message and exit.

3.If the file exists, check if the permission mode is symbolic or absolute.

4.If the permission mode is symbolic, accept the symbolic permissions as input.
5.Use the chmod command with the appropriate options and the symbolic permissions to assign
the file permissions.

6.If the permission mode is absolute, accept the octal permissions as input.
7.Use the chmod command with the appropriate options and the octal permissions to assign the
file permissions.

8.Display a success message if the file permissions are assigned successfully.

9.If any error occurs during the process, display an error message.

Program:
echo "Enter the file

name" read file

echo "Enter the file contents and press

control +d" cat>$file

echo "Permission for the file"

ls -l $file

echo "Changing permission using symbolic mode" chmod u+x

$file chmod g+wx $file chmod o-r $file echo "File permission

after assigning permission using symbolic mode"

ls -l $file
echo "Changing permission using absolute
mode"
chmod u=rw $file

chmod g=rw $file

chmod o=r $file

echo "File permission after assigning permission using absolute mode"

ls -l $file

Output:

Result : The above algorithm and program clearly satisfy the desired aim of assigning
permission to a given file using symbolic mode or absolute mode .

2. Write a shell script to create two directories and store five files in one directory using the
related commands and to transfer all the files to another directory.
AIM: Create two directories, store five files in one directory, and transfer all the files to another
directory using related commands.

ALGORITHM:

1.Create two directories: `source_dir` and `destination_dir`.

2.Use the `mkdir` command to create the directories.

3.Store five files in the `source_dir`.

4.Use the touch command to create the files within the `source_dir`.
5.Transfer all the files from the `source_dir` to the `destination_dir`.

6.Use the mv command to move the files.

7.Display a success message after the files are transferred Program:


echo "Current Directory

is " pwd

echo "Create Subdirectory"

echo "Enter two subdirectory

names" read name name1

mkdir $name $name1

echo "Move to subdirectory

$name" cd $name

echo "Current directory is

`pwd`" echo "Create five

files" echo "Enter file name "

read file1 file2 file3 file4 file5

touch $file1 $file2 $file3

$file4 $file5 echo "Contents

of current directory" ls

echo "Move files from $name1 directory" mv $file1 $file2

$file3 $file4 $file5 /home/luci/Desktop/oslab/$name1 echo

"Files are moved to $name1 directory"

echo "Change to directory location to subdirectory

$name1" cd ..

cd $name1
echo "Current directory is `pwd`" echo
"Display contents of $name1 " ls

Output:

Result : The above algorithm and program clearly satisfy the desired aim to Create two
directories, store five files in one directory, and transfer all the files to another directory using
related commands

3. Write a shell script to accept a file name as input and display whether it exists or not. If it
exits, then give the details of its attributes like access permission, it’s size etc.
AIM: Accept a file name as input, display whether it exists or not, and if it exists, provide the
details of its attributes such as access permissions and size.

ALGORITM:

1.Accept the file name as input.


2.Check if the file exists. If not, display a message indicating that the file does not exist and exit.
3.If the file exists, use the `ls` command with the `-l `option to obtain detailed information about
the file.
4.Parse the output of the` ls` command to extract the relevant attributes such as access
permissions and size.

5.Display the file's existence and its attribute details.

Program:
echo "Enter the

filename" read
name echo "File

Details" if

[ $name ] then

echo "File exits" echo "File size

is:" wc -c $name echo "File

type: " file $name if [ -r $name

-a -w $name -a -x $name ] then

echo "File is readable writeable and

exceutrable" elif [ -r $name -a -w

$name ] then

echo "File is readable and

writable" elif [ -r $name ]

then

echo "File is

read only" elif [

-w $name ]

then

echo "File is write

only" elif [ -x $name ]

then echo "File is

execuatble only" else

echo "File not readable, writable and

executable" fi else

echo "File does not

exist" fi

Output :
Result : The above algorithm and program clearly satisfy the desired aim to Accept a file name
as input, display whether it exists or not, and if it exists, provide the details of its attributes such
as access permissions and size.
4. To compresses a file using gzip and pack commands

Aim: Compress a file using gzip and pack commands.

ALGORITHM:

1.Accept the file name as input.

2.Check if the file exists. If not, display an error message and exit.

3.If the file exists, use the `gzip` command to compress the file.

4.Use the `pack` command to pack the compressed file into an archive.

5.Display a success message if the compression and packing are successful.

6.If any error occurs during the process, display an error message.

Program:
echo "Enter the filename to be

compressed" read f

echo "Before zipping file

size is" wc -c $f

echo "Compress

Results" gzip -l $f.gz


echo "Unzipping using gunzip"

gunzip $f.gz

echo "After unzipping file

is " wc -c $f

Output:

Result : The above algorithm and program clearly satisfy the desired aim of compressing a file
using gzip and pack command.

5. To find a given pattern in a list of files of current directory using grep and fgrep
commands.

AIM: Find a given pattern in a list of files in the current directory using grep and fgrep
commands.

ALOGRITHM:

1.Accept the pattern to search as input.


2.Use the `grep` command to search for the pattern in the list of files in the current directory.

3.Display the matching lines and the corresponding file names.


4.If the pattern is a fixed string (no regular expression), use the `fgrep` command instead of
`grep`.

5.If no matches are found, display a message indicating no matches were found.

Program:
echo "Enter file
name: " read f f1
echo "Searching
using grep." opt1=y
while [ $opt1 = y ] do echo "Enter the pattern you
want to search: " read pat echo "Output of grep
search: " grep "$pat" $f $f1 echo "Do you want to
enter one more pattern for grep (y/n):" read opt1
done opt2=y echo "Searching using fgrep. " while
[ $opt2 = y ] do echo "Enter pattern you want to
searh: "
read p fgrep "$p" $f $f1 echo "Do you want to
enter one more pattern for fgrep" read opt2
done

Output :
Result : The above algorithm and program clearly satisfy the desired aim of finding a given
pattern in a list of files in the current directory using grep and fgrep commands.

6. Shell Script to find out the sum of the given numbers using command line argument.

AIM: Find the sum of given numbers using command-line arguments.

ALOGITHM:

1.Accept numbers as command-line arguments.

2.Initialize a variable `sum` to 0 to store the sum of numbers.

3.Iterate through each command-line argument:

4.Convert the argument to a number.

5.Add the number to the `sum` variable.

6.Display the final sum.

Program:

#!/bin/bash

# Store the total sum


sum=0
# Loop through each command-line argument
for number in "$@"; do # Add the number
to the sum sum=$((sum + number)) done
# Print the final sum

echo "Sum: $sum"


OUTPUT:
Result : The above algorithm and program clearly satisfy the desired aim to Find the sum of
given numbers using command-line arguments.

7. Write a shell script to find the largest among the 3 given numbers.
AIM: Write a shell script to find the largest and smallest numbers among the 3 given numbers.

ALGORITHM:

1.Accept three numbers as command-line arguments.

2.Initialize variables `largest` and `smallest` with the first number.

3.Compare the second number with `largest` and `smallest`:

• If the second number is larger than `largest`, update `largest` with the second number.

• If the second number is smaller than `smallest`, update `smallest` with the second
number.

4. Compare the third number with `largest` and `smallest`:

• If the third number is larger than `largest`, update `largest` with the third number.

• If the third number is smaller than `smallest`, update `smallest` with the third number.

Program:
echo "Enter Num1" read num1 echo "Enter

Num2" read num2 echo "Enter Num3"

read num3 if [ $num1 -gt $num2 ] &&

[ $num1 -gt $num3 ] then echo $num1 elif

[ $num2 -gt $num1 ] && [ $num2 -gt

$num3 ] then echo $num2 else echo

$num3 fi

Output :

Result : The above algorithm and program clearly satisfy the desired aim to Write a shell script
to find the largest and smallest numbers among the 3 given numbers.

8. Shell Script which works similar to the Unix commands Head Tail.
AIM: Create a shell script that functions similarly to the Unix commands `head` and
`tail`.

ALGORITHM:

1.Accept the file name and number of lines as command-line arguments.

2.Check if the file exists. If not, display an error message and exit.

3.If the file exists, check if the user wants to display the head or tail of the file.

4.If the user wants the head:


5.Use the `head` command with the specified number of lines to display the head of the file.

6.If the user wants the tail:

7.Use the `tail` command with the specified number of lines to display the tail of the file.

8.If any error occurs during the process, display an error message.

PROGRAM: #!/bin/bash

# Accept the file name and number of lines as command-line arguments


filename=$1 num_lines=$2
# Check if the file
exists if [[ ! -e
$filename ]]; then
echo "File not found!"

exi
t1
fi
# Check if the user wants the head or
tail if [[ $3 == "head" ]]; then #
Display the head of the file head -n
$num_lines $filename elif [[ $3 ==
"tail" ]]; then # Display the tail of the
file
tail -n $num_lines $filename

else

# Invalid option echo "Invalid option! Please


specify 'head' or 'tail'." fi
OUTPUT:

• Displaying the head of the file:


• Displaying the tail of the file:

Result : The above algorithm and program clearly satisfy the desired aim to Create a shell script
that functions similarly to the Unix commands `head` and `tail`.

9. Write a shell script to reverse a number supplied by a user.

AIM: Write a shell script to reverse a number provided by the user.

ALGORITHM:

1.Accept the number as a command-line argument.

2.Initialize a variable `reversed` to store the reversed number.

3.Extract the digits from the number one by one:

• Use the modulo operator % to get the last digit.

• Multiply the `reversed` variable by 10 and add the last digit to it.

• Update the number by dividing it by 10 to remove the last digit.

4.Repeat step 3 until the number becomes 0.

5.Display the reversed number.

Program:

read -p "Enter a number: " number

temp=$number

while [ $temp -ne 0 ] do


reverse=$reverse$((temp%10))
temp=$((temp/10)) done
Output:

Result : The above algorithm and program clearly satisfy the desired aim to reverse a number
provided by the user.

10. Write the shell script to find the sum, the average and the product of the four integers
entered.
AIM: Write a shell script to find the sum, average, and product of four integers entered by the
user.

ALGORITHM:

1.Accept four integers as command-line arguments.

2.Initialize variables `sum`, `average`, and `product` to 0.

3.Add all four integers to the `sum` variable.

4.Calculate the average by dividing the `sum` by 4.

5.Calculate the product by multiplying all four integers.

6.Display the sum, average, and product.

Program:
echo "Enter four integers with space

between" read a b c d

sum=`expr $a + $b + $c +

$d` avg=`expr $sum / 4`

dec=`expr $sum % 4`

dec=`expr \( $dec \*

1000 \) / 4` product=`expr

$a \* $b \* $c \* $d` echo
Sum = $sum echo Average

= $avg.$dec echo Product

= $product Output:

Result : The above algorithm and program clearly satisfy the desired aim to find the sum,
average, and product of four integers

11. Write a shell script to find how many terminals has this user logged in.

Program:

AIM: Write a shell script to find the number of terminals a user has logged in.

ALGORITHM:

1.Accept the username as a command-line argument.

2.Use the `who` command with the `-u` option to obtain the list of logged-in users.

3.Filter the output based on the provided username.

4.Count the number of occurrences of the username in the filtered output.

5.Display the number of terminals the user has logged in. Program
echo "Enter the

LOGNAME" read

lgname x=`who | grep

$lgname | wc -l` if [ $x -
eq 0 ] then echo "user

name did not logged" fi

echo "Number of terminal $lgname has logged in is $x"

Output:

Result : The above algorithm and program clearly satisfy the desired aim to number of terminals
a user has logged in.
8.Display the sum of digits.

Program:
echo "Enter a

Number" read

num sum=0

while [ $num -

gt 0 ] do

mod=$((num%10)) #It will split each

digits sum=$((sum + mod)) #Add

each digit to sum. num=$((num/10))

#Divide num by 10. done

echo "Sum of entered number is $sum "

Output :
Result : The above algorithm and program clearly satisfy the desired aim to find the sum of
digits of a given number.

12. Write a script to find the value of one number raised to the power of another.

AIM: Write a shell script to find the value of one number raised to the power of another.

ALGORITHM:

1.Accept the base number and exponent as command-line arguments.

2.Initialize a variable `result` to store the final result.

3.Check if the exponent is 0. If so, set `result` to 1.

4.If the exponent is positive:

• Use a loop to multiply the base number with itself `exponent` number of times.

• Update the `result` variable in each iteration.

5.If the exponent is negative:

• Use the `bc` command to calculate the power using the` ^` operator.

• Assign the result to the `result` variable.

6.Display the final result.

Program :
echo "Input number" read

no echo "Input power" read

power counter=0 ans=1


while [ $power -ne

$counter ] do ans=`echo

$ans \* $no | bc`

counter=`echo $counter +

1 | bc` done

echo "$no power of $power is $ans"

Output:

Result : The above algorithm and program clearly satisfy the desired aim to find the value of
one number raised to the power of another

13. Write a shell script, which will receive any number of filename as arguments. The shell
script should check whether such files already exists.
AIM: Write a shell script that receives any number of filenames as arguments and checks
whether the files already exist.

ALGORITHM:

1.Accept filenames as command-line arguments.

2.Iterate through each filename.

3.Check if each file exists using the `-e` option with the `test` command.

4.Display a message indicating whether each file exists or not.

Program:
#!/bin/bash for file in

"$@"; do if [ -e "$file" ];

then echo "File '$file'

already exists." else

echo "File '$file' does not

exist."

fi

done

Output:

Result : The above algorithm and program clearly satisfy the desired aim to receives any number
of filenames as arguments and checks whether the files already exist.

14. Write a shell program to add, subtract and multiply the 2 given numbers passed as
command line arguments.
AIM: Write a shell program to add, subtract, and multiply two given numbers passed as
command-line arguments.

ALGORITHM:

1.Accept two numbers as command-line arguments.

2.Check if exactly two arguments are provided. If not, display an error message and exit.

3.Assign the first argument to the variable `num1` and the second argument to `num2`.

4.Perform arithmetic operations on the numbers:

• Addition: Add `num1` and `num2`, store the result in `sum`.


• Subtraction: Subtract `num2` from `num1`, store the result in `diff`.

• Multiplication: Multiply `num1` and `num2`, store the result in `prod`.

5.Display the results of the arithmetic operations.

Program:
add=`expr $1 + $2`

sub=`expr $1 - $2`

mul=`expr $1 \* $2`

echo " Addition of $1 and $2 is $add

" echo " Subtraction of $1 from $2

is $sub " echo " Multiplication of $1

and $2 is $mul " Output :

Result : The above algorithm and program clearly satisfy the desired aim to add, subtract, and
multiply two given numbers passed as command-line arguments.

15. Shell Script to Count and Report the Number of Entries in Each Subdirectory.
AIM: Write a shell script to count and report the number of entries (files and directories) in each
subdirectory mentioned in the path provided as a command-line argument.

ALGORITHM:

1.Accept the directory path as a command-line argument.

2.Check if the directory exists using the `-d` option with the `test` command.

3.If the directory exists, proceed with counting and reporting.

4.Iterate through each subdirectory within the provided directory.


5.Use the `find` command with the `-type d` option to find only directories within each
subdirectory.

6.Count the number of entries (files and directories) within each subdirectory.

7.Display the subdirectory name along with the count of entries.

8.Repeat steps 4-7 for all subdirectories within the main directory.

9.Display a message indicating the completion of counting and reporting.

PROGRAM: #!/bin/bash

# Accept the directory path as a command-line argument directory=$1


# Check if the directory exists
if [ -d "$directory" ]; then
# Iterate through each subdirectory
for subdirectory in "$directory"/*; do
if [ -d "$subdirectory" ]; then
# Find the number of entries (files and directories) within the subdirectory num_entries=$
(find "$subdirectory" -mindepth 1 -maxdepth 1 | wc -l)
# Display the subdirectory name and the count of entries
echo "Subdirectory: $subdirectory" echo "Number of
Entries: $num_entries"
echo

fi

done echo "Counting and reporting


completed." else echo "Directory
'$directory' does not exist." Fi
OUTPUT:
Result : The above algorithm and program clearly satisfy the desired aim to count and report the
number of entries (files and directories) in each subdirectory mentioned in the path provided as a
command-line argument.

16. Shell script to reverse content of a file .


AIM: Write a shell script to reverse the contents of a file.

ALGORITHM:

1.Accept the filename as a command-line argument.

2.Check if the file exists using the `-f` option with the `test` command.

3.If the file exists, proceed with the reversal.

4.Use the`tac` command to reverse the lines in the file.

5.Create a temporary file to store the reversed contents.

6.Redirect the reversed output to the temporary file using the` >` operator.
7.Overwrite the original file with the contents of the temporary file using the `mv` command.

8.Remove the temporary file.

9.Display a message indicating the successful reversal.

PROGRAM:
#!/bin/bash

# Accept the filename as a command-line argument filename=$1


# Check if the file
exists if [ -f
"$filename" ]; then
# Reverse the contents of the file and store in a temporary file tac
"$filename" > temp.txt
# Overwrite the original file with the reversed contents
mv temp.txt "$filename" # Remove the temporary file
rm temp.txt
echo "File '$filename' contents reversed successfully." else

echo "File '$filename' does not exist."


fi

OUTPUT:

Result : The above algorithm and program clearly satisfy the desired aim to Write a shell script
to reverse the contents of a file.

17. Write a menu driven shell script for Copy a file, Move a file.
AIM: Write a menu-driven shell script to copy a file, remove a file, and move a file.

ALGORITHM:
1.Display a menu with options for file operations.

2.Prompt the user to select an option.

3.Based on the user's choice, perform the corresponding file operation.

4.Repeat the menu and prompt until the user chooses to exit.

5.Handle invalid menu choices gracefully.

6.Display appropriate messages for successful file operations or any errors encountered.

Program:
echo "Menu " echo

"1. Copy a File "

echo "2. Remove a

file " echo "3. Move

a file" echo "4. Quit"

echo "Enter your

Choice: \c" read

Choice case

"$Choice" in

1) echo "Enter File name

to copy: \c" read f1 echo

"Enter File name: \c " read f2

if [ -f $f1 ] then cp $f1 $f2

else

echo "$f1 does not

exist" fi

;;

2) echo "Enter the File

to be removed: " read r1


if [ -f $r1 ] then rm -i

$r1 else echo " $r1 file

does not exist " fi ;;

3) echo "Enter File name

to move: \c" read f1 echo

"Enter destination: \c " read

f2 if [ -f $f1 ] then if [ -d

$f2 ] then mv $f1 $f2

echo " $f1 does not exist: " fi

Output:

;;

4)

echo "Exit......." exit;; esac

Result : The above algorithm


and program clearly satisfy
the desired aim to menu-driven shell script to copy a file, remove a file, and move a file.

You might also like