ms061210
ms061210

Reputation: 41

Checking files if exists

I found a code in this site on how to check if the file exists or not, and then added some code to match my idea. Am I doing this correct?

declare file="file.txt"
declare regex=$skedtemp
declare file_content=$( cat "${file}" )
if [[ " $file_content " =~ $regex ]] 
then
    skedran=$((RANDOM%200+600))
    skedtemp="SN$skedran"
    sked=$skedtemp
else
    sked=$skedtemp
fi

if it already exist then it will generate another random number and if it does not exist, the generated number will then be used.

Upvotes: 1

Views: 136

Answers (2)

Zombo
Zombo

Reputation: 1

To test if files exists you can do this

[ -a file.txt ]

or

[ -e file.txt ]

or

[ -f file.txt ]

In response to Jonathan Leffler’s comment

File operators:

  -a FILE        True if file exists.

ref

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246744

You're probably looking for grep

file="file.txt"
if grep "$skedtemp" $file
then
    skedran=$((RANDOM%200+600))
    skedtemp="SN$skedran"
fi
sked=$skedtemp

Upvotes: 0

Related Questions