Checking if a file exists

How can I check if a file exists in shell script. Basically, I want to check if a file Test_msgs has been created today. If it has been then append data to it. Otherwise, create it. I have written the following but it does not work.

todaysdate=$(date +%d%m%Y)
timenow=$(date +%H%M%S)
checktestfile='Test_msgs_$todaysdate_*.txt'
testfile='Test_msgs_'$todaysdate'_'$timenow'.txt'

if [ -f checkTestfile ]; then
echo "File appended to" >> testfile
else
echo "File created" > testfile
fi

Just a silly error; you forgot a "$" before "checkTestfile" inside the -f test. You also mis-capitalized "checkTestfile"; it should be "checktestfile" to match the variable declaration above it.

You used the -f, but there are a couple of others also that may be of interest.

if [ -r $checktestfile ] ==> to see if you can read it (may not have access)
if [ -s $checktestfile ] ==> to see if the file is non-zero or not empty

Also, in your scripting, you set a variable

testfile='Test_msgs_'$todaysdate'_'$timenow'.txt' 

But you access it as in -- need the $ before variable

echo "File created" > $testfile

@gugs:

there is no need for an if condition. You may directly use >> as it will append if file exists, or will create file if it does not exist.

echo "some text" >> testfile

True, but he wanted the first message in the file to be different based on whether it was created or appended-to. That then requires a test.