What is the syntax for IF/ELSE in bash?
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 firstif
conditionYou need to close the
if
condition usingfi
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.
A good idea is to check his scripts with this tool.
Here is an annotated version of your error:
1 #!/bin/bash
2 sed -rne '/21:25:07/,/21:50:07/ p' server.log.2015-04-21 > /tmp/filename.log ;
3 du -sh /tmp/filename.log ;
4 if [`du -sh /tmp/filename.log` -gt 0] then gzip /tmp/filename.log ;
^––SC1009 The mentioned parser error was in this if expression.
^––SC1073 Couldn't parse this test expression.
^––SC1035 You need a space after the [ and before the ].
^––SC1020 You need a space before the ].
^––SC1072 Missing space before ]. Fix any mentioned problems and try again.
Source