0

I'm using below if statement to trigger sucess/failure email alert. But, && condition doesn't seems to be working as expected. Could someone assist whether below if statement is correct.

OUT_FILE=TEST_UPLOAD.csv
STRING=`grep 'party_id' $OUT_FILE`

if [ -f $OUT_FILE ] && [ -z $STRING ]; then
echo "File upload failed"
else
echo "File upload success"
fi
chepner
  • 497,756
  • 71
  • 530
  • 681
  • you also need a space before your first closing bracket – Jason Holloway Nov 05 '20 at 12:43
  • What *is* expected? Where does `$STRING` come from, how is it set if upload purportedly succeeds, etc? – chepner Nov 05 '20 at 12:51
  • 1
    Correct results when quoting "$OUT_FILE" and "$STRING"? – Jens Nov 05 '20 at 12:53
  • Exactly that. `test -z $var` doesn't work right unless you quote your expansion (`test -z "$var"`). Otherwise, it becomes `[ -z ]`, which is true (being an alternative way to write `[ -n '-z' ]`), instead of `[ -z '' ]`, which is false. – Charles Duffy Nov 05 '20 at 13:08
  • @CharlesDuffy That's exactly when you would *want* it to be true, though :) It's `-n` that breaks when you provide an unquoted, unset/null parameter. `[ -n "" ]` fails, but `[ -n ]` would succeed. `test -z $var` would fail, though, if `$var` produced two or more words. – chepner Nov 05 '20 at 13:16
  • @AlexanderLHayes, it's almost never the right thing to run `somecommand; if [ "$?" != 0 ]; then ...`; compare to `if ! somecommand; then ...` -- among other faults, the former syntax leaves `somecommand` as "unchecked", so any time it returns a nonzero exit status will trigger `set -e` behavior and ERR traps. – Charles Duffy Nov 05 '20 at 13:17
  • @chepner, you're right that I misidentified the exact failure mode. Since the OP is providing code that _has_ failure modes, though, I'm quite comfortable letting the duplicates stand until and unless they update the question with a reproducer that conflicts with them. – Charles Duffy Nov 05 '20 at 13:19

0 Answers0