Anonymous Anonymous - 1 year ago 74
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

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

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

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


OK - so, you type in bash This means that you're running your script but passing no arguments to 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 testfile.dat

or just testfile.dat

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

Best of luck.