arnpry
arnpry

Reputation: 1141

IF Multiple Files Exist

I have an IF statement in a bash script that checks if six files exist or not.

Bash Code

if [ -f file1.txt ] && [ -f file2.txt ] && [ -f file3.txt ] && [ -f file4.txt ] && [ -f file5.txt ] && [ -f file6.txt ];
then
echo "Required Files Exist"
else
echo "Required Files Do Not Exist"
fi

Expected Result

Required Files Exist

Actual Result

Required Files Do Not Exist

All of the files DO exist

Upvotes: 1

Views: 2185

Answers (2)

tripleee
tripleee

Reputation: 189357

Your code should work fine if indeed all six files exist in the current directory.

You might want to refactor it to reduce code duplication, though.

all_exist () {
    local filename
    for filename; do
        test -f "$filename" && continue
        echo "$0: $filename does not exist - aborting" >&2
        return 1
    done
    return 0
}

all_exist file1.txt file2.txt file3.txt file4.txt file5.txt file6.txt && echo "$0: all files exist" >&2

If your files are really named this monotonously, perhaps just

all_exist file{1..6}.txt

Upvotes: 3

qwsj
qwsj

Reputation: 456

You run the script from a different directory.

For example: you are in /root/ and run the script /root/script/script.sh

you will search files in /root/, but not in /root/script/.

Before run script try it: touch file{1..6}.txt

Upvotes: 0

Related Questions