0

Note, I am using ksh and running in CentOS.

I have a shell script where a logger function is set like:

if tty -s
then
  echo "${FOO}" | tee -a ${BAR_LOG_FILE}
else
  echo "${FOO}" >> ${BAR_LOG_FILE} 
fi

My question is, when I refactored this if to look like all the other if tests in my code, it stopped functioning.

Why?

My refactor was as follows:

if [ tty -s ];
then
  echo "${FOO}" | tee -a ${BAR_LOG_FILE}
else
  echo "${FOO}" >> ${BAR_LOG_FILE} 
fi

My only change was to put brackets around the if and add a ;, like the rest of my if tests, which all work as intended.

My refactor caused an error which looked like the the BAR_LOG_FILE couldn't be found.

What's going on here?

1
  • 1
    Can the downvotes be explained? I was able to find other posts dealing with test but unless you realize the [ is a command and not syntax for a test, it would be hard not to get confused by this type of question. And there's from what I can tell, no suitable reference that explains it as it relates to tty. Jun 13 '19 at 20:02
5

The square brackets after if aren’t shell syntax which can be ommitted or not depending on stylistic preferences, they’re a separate command, test. (The linked manpage describes the external test/[ command, but many shells provide their own implementation.)

Writing

if [ tty -s ];

is equivalent to writing

if test tty -s;

and since test/[ doesn’t have a tty operator, it fails.

if is followed by a command, which it runs, and the exit code of that command determines which branch is taken after the if: if it’s 0, the then branch is taken, otherwise, the else branch (if any).

2
  • OK. This makes sense given all my other if commands are followed by flags (e.g. -f, -sand not commands) and why they work as intended. Jun 13 '19 at 19:57
  • 3
    Your other if statements are followed by a command, the [ command, and -f, -s etc. are arguments to [. Jun 13 '19 at 20:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.