In: Computer Science
UNIX ONLY
Write a bash script that will accept a filename as a command line argument. Your script should first check whether the filename has been passed as argument or not (hint: at least one argument has to be provided). If no argument has been provided your script should display appropriate message and exit. If a file name has been provided, your script should check if the file exists in the current directory and display the contents of the file. Otherwise if the file does not exist it should display an appropriate error message
WHAT WOULD THIS LOOK LIKE IN TERMINAL?
bash-3.2$ vim fileexsits.sh
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Illegal number of parameters"
exit 2
fi
FILE="$1"
if [ -f "$FILE" ];
then
echo "File $FILE exist."
echo "Printing the contents of file"
cat $FILE
else
echo "File $FILE does not exist"
fi
Save the file and provide the permissions.
chmod 777 -R fileexsits.sh
CASE : when file doesn't exists
bash-3.2$ ./fileexsits.sh hello.o
File hello.o does not exist
bash-3.2$
bash-3.2$
bash-3.2$
CASE : when file exists
bash-3.2$ ./fileexsits.sh hello.c
File hello.c exist.
Printing the contents of file
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Hello World\n"); // waw hello Richard and ok
exit(0); // end of the program
}
CASE : no Argument
bash-3.2$ ./fileexsits.sh
Illegal number of parameters