Shell Script
Shell Script
Implement the shell program using case and command line arguments to perform the
following:
file copy
file move
file delete
file permission change
Usage should be below::
$ fileops.sh c fname
would copy fname to fname.cpy
$ fileops.sh m fname
would move fname to old.fname
$ fileops.sh d fname
would delete fname from the directory
$ fileops.sh p fname
would change the permission of the file to readonly for group and others
$fileops.sh any other arguments .. more than 2 or not c or m or d and fname then it should exit
SOLUTION:
#! /bin/bash
if [ $# != 2 ]
then
echo "Invalid choice."
exit
else
opt=$1
fname=$2
case $opt in
c)
cp $fname $fname.cpy
if [ -e $fname ]
then
echo
echo "$fname copied to $fname.cpy"
fi
;;
m)
mv $fname old.$fname
if [ -e old.$fname ]
then
echo "$fname moved to old.$fname"
fi
;;
d)
rm $fname
if [ ! -e $fname ]
then
echo "$fname removed"
fi
;;
p)
chmod go=r $fname
if [ -e $fname ]
then
echo "For file $fname Group & others permission changed to Read only."
fi
;;
esac
fi
Screenshots of Program :
Q2. Also use any related system calls and write C program for performing the same operations
$fileops.exe c fname
file copy, move and delete instead of system command
Solution:
#include <stdio.h>
#include <unistd.h>
#include<fcntl.h>
#include<unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
void copy();
void move();
void delete();
void change_permission();
switch (command)
{
case 'c':
copy(fname);
break;
case 'm':
move(fname);
break;
case 'd':
delete(fname);
break;
case 'p':
change_permission(fname);
break;
default :
printf("Invalid Option [c copy] | [m move] | [d delete] | [p
permission]\n");
exit(1);
}
}
else
{
printf("Invalid Arguments\n");
exit(1);
}
return 0;
}
strcpy(newfname, fname);
strcat(newfname, extention);
if(sourcefile < 0 )
{
printf("Source file not Exist\n"); //Source file not found
}
else
{
// Destination file open in write mode and if not found then create
int destfile = open(newfname, O_WRONLY | O_CREAT);
while((read_in = read(sourcefile, &buffer, 10000)) > 0)
{
write_out = write(destfile, &buffer, read_in);
}
printf("File Successfully copied to %s\n", newfname);
close(destfile);
}
close(sourcefile);
}
void move(char *fname)
{
int result;
char *prefix = "old.";
char *newfname = malloc(strlen(fname) + strlen(prefix) + 1);
strcpy(newfname, prefix);
strcat(newfname, fname);
if(result == 0)
{
printf("%s Moved to %s\n", fname, newfname);
}
else
{
printf("Can't move, File not Found!...\n");
}
}
result = unlink(fname);
if(result == 0)
{
printf("%s Deleted Successfuly!\n", fname);
}
else
{
printf("Can't Delete, File not Found!...\n");
}
}
if(result == 0)
{
printf("%s, File permission successfuly changed to readly for Group and
Others!\n", fname);
}
else
{
printf("Can't change file permission, File not Found!...\n");
}
}
Screenshots of output: