Register
It is currently Mon Jul 28, 2014 4:18 am

one line test for file and contents


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Tue Dec 02, 2008 8:56 am   

Joined: Tue Dec 02, 2008 8:30 am
Posts: 6
Location: Bonny Scotland
i need to test the contents of a file if it exists, and to set a flag
for example
Code:
...
MYDIR="/home/fred/"
...
FLAG="NO"
if [ -e $MYDIR"FLAGFILE" -a `cat $MYDIR"FLAGFILE"` = "YES" ]; then
  FLAG="YES"
fi
...

this generates an error if $MYDIR"FLAGFILE" (/home/fred/FLAGFILE in this example) does not exist. even though it shouldn't evaluate the second part of the boolean AND if the first part returns false.
I can do this with two test lines
Code:
...
MYDIR="/home/fred/"
...
FLAG="NO"
if [ -e $MYDIR"FLAGFILE" ]; then
  if [ `cat $MYDIR"FLAGFILE"` = "YES" ]; then
    FLAG="YES"
  fi
fi

which works just fine but it obviously makes the script the test/s are in much longer.

Has anyone any hints on making the single liner version work? thanks


Top
 Profile  
 PostPosted: Tue Dec 02, 2008 10:02 am   

Joined: Mon Nov 17, 2008 7:25 am
Posts: 221
Code:
if [ -e ${MYDIR}FLAGFILE ] && [ "`cat ${MYDIR}FLAGFILE`" = "YES" ]; then
   FLAG="YES"
fi


This should work :)

Best regards
Fredrik Eriksson


Top
 Profile  
 PostPosted: Tue Dec 02, 2008 10:41 am   

Joined: Tue Dec 02, 2008 8:30 am
Posts: 6
Location: Bonny Scotland
thanks fredrick, that does the trick.

I had forgotten about the && and || binary operators for concatinating tests.
It's a shame that the original attempt doesn't work, i guess bash evaluates the whole test operators before starting to compare


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 10 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP