1

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.

2 Answers 2

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

2
  • Hmmm...OK, some different version of ... something. man test sayeth 'EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are true'. This was on RHEL5. man bash does show the text you show. However, it does not tell the whole story: bash -c '[ -f file.txt -a ! -L file.txt ] && echo Yes || echo No' has -a acting as an 'and' operator. So, the -a operator appears to be ... err, polymorphic? It seems odd to add yet another 'file exists' operator when there were already sufficient and the -a already had a meaning. Weird! But lots of stuff in bash seems odd to me. Jan 8, 2013 at 6:26
  • @JonathanLeffler its akin to [ $foo ] and [ -n $foo ]
    – Zombo
    Jan 8, 2013 at 6:38
0

You're probably looking for grep

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.