Mathias26
Mathias26

Reputation: 79

How can I test if files given as an argument exist?

I am making a bash script that you have to give 2 files or more as arguments.
I want to test if the given files exist. I'm using a while loop because I don't know how many files are given. The problem is that the if statement sees the $t as a number and not as the positional parameter $number. Does somebody have a solution?

t=1
max=$#
while [ $t -le $max ]; do

    if [ ! -f $t ]; then
            echo "findmagic.sh: $t is not a regular file"
            echo "Usage: findmagic.sh file file ...."
            exit
    fi

    t=`expr $t + 1`
done

Upvotes: 2

Views: 129

Answers (1)

whoan
whoan

Reputation: 8521

You can do it with the bash Special parameter @ in this way:

script_name=${0##*/}
for t in "$@"; do
    if [ ! -f "$t" ]; then
        echo "$script_name: $t is not a regular file"
        echo "Usage: $script_name file file ...."
        exit 1
    fi
done

With "$@" you are expanding the positional parameters, starting from one as separate words (your arguments).


Besides, remember to provide a meaningful exit status (e.g. exit 1 instead of exit alone). If not provided, the exit status is that of the last command executed (echo in your case, which succes, so you're exiting with 0).

And for last, instead of write the script name (findmagic.sh in your case), you can set a variable at the beginning in your script:

script_name=${0##*/}

and then use $script_name when necessary. In this way you don't need to update your script if it changes its name.

Upvotes: 3

Related Questions