Ubuntu – The syntax for IF/ELSE in bash

bashcommand line

I am trying to pull logs and doing few others things directly. written a small line BASH but not working. I am sure thats with IF Condition.

sed -rne '/21:25:07/,/21:50:07/ p'  server.log.2015-04-21 > /tmp/filename.log ;
du -sh  /tmp/filename.log ; 
if [`du -sh  /tmp/filename.log` -gt 0] then gzip /tmp/filename.log ;

Best Answer

You missed couple of points, the correct (Only syntatically) form would be:

if [ `du -sh  /tmp/filename.log` -gt 0 ]; then gzip /tmp/filename.log; fi
  • There must be space after test ([) and before ]

  • You need to put a ; (synonymous to newline) after first if condition

  • You need to close the if condition using fi at last portion

Also you should use $() instead of `` as command substitution as the latter one is deprecated in favor of $().

So, literally you command can be made more robust:

if [ $(du -sh  /tmp/filename.log) -gt 0 ]; then gzip /tmp/filename.log; fi

Most importantly, there is another major problem in your if condition, you are comparing a string (output of du -sh /tmp/filename.log) with an integer (0), which is wrong.

You can do the following:

if [ $(du -s ./test.txt | cut -f1) -gt 0 ]; then gzip /tmp/filename.log; fi

Or simply:

[ $(du -s ./test.txt | cut -f1) -gt 0 ] && gzip /tmp/filename.log

In the last command, the command after && will be run only if the previous command returns an exit status 0 i.e. success. So, you don't need an if condition after all.

Also if you are using bash, try to use the bash keyword [[ instead of test [ as it provides lots of features that test does not. So your command could take the following final form:

[[ $(du -s ./test.txt | cut -f1) -gt 0 ]] && gzip /tmp/filename.log

Or the simplest way:

[[ -s /tmp/filename.log ]] && gzip /tmp/filename.log

The -s indicates that if the file is greater than 0 in size then will return true.

Related Question