Anonymous Anonymous - 2 years ago 179
Bash Question

Shell script file testing

I have to do these steps:

a. Accept the file name as command line argument

b. Check for sufficient number of command line argument.

c. Check if the given file exist or not.

d. Check if the file is readable.

e. Exit out of the program with success using the statement exit 0

This is what i did so far, but when i run the script i always get "Invalid argument" and "File Does Not Exist" as the output.

#! /bin/bash
filename=$1

if [ $# -eq 1 ]
then
echo $1
else
echo "Invalid argument"
fi

if [ -e "$1" ]; then
echo "File Exists"
exit 1
else
echo "File Does not Exist"
exit 1
fi

if [ -r "$1" ]; then
echo "File is readable"
exit 1
else
echo "File is not readable"
exit 1
fi

Answer Source

OK - so, you type in bash myfilename.sh. This means that you're running your script but passing no arguments to myfilename.sh. Try the following:

echo "This is a test file" > testfile.dat

This will create a file named testfile.dat which contains some text. (The actual text in the file doesn't matter. If you've got time you can type in the complete works of Shakespeare. But it won't change how your shell script functions). Next, run your script as

bash myfilename.sh testfile.dat

or just

myfilename.sh testfile.dat

Here you're telling your script to check for the existence of testfile.dat.

Best of luck.