0

I've got the following bash script to check if a string length is nonzero using -n and equals "OK" by converting the variable to uppercase using ${1^^}:

#!/bin/bash
myfunction() {
    result=0
    if [[ -n $1 && ${1^^} = "OK" ]]; then
            result=1
    fi
    echo $result >> /home/[REDACTED]/mylog
}
myfunction "ok"
myfunction "NO"

I made it executable using:

sudo chmod +x ./test

I then call it with either of the following:

bash ./test
./test

And the file always contains the expected result:

1
0

However, when trying to run from cron and the file contains:

0
0

I set up cron with this command:

sudo crontab -e

And here is the content:

* * * * * /home/[REDACTED]/test

I'm probably overlooking something obvious like syntax or cron environment... any suggestions?

Thanks!

feganmeister
  • 686
  • 1
  • 8
  • 15
  • 1
    Are you sure the shell `cron` runs is `bash` ? By default cron is configured tu use `/bin/sh` which behaves differently than bash – Aserre Mar 11 '19 at 09:45
  • Sounds likely... How would I check? Edit: I updated cron to this but made no difference: * * * * * /bin/bash -c "/home/[REDACTED]/test" – feganmeister Mar 11 '19 at 10:04
  • After reading this [article](https://stackoverflow.com/questions/12230690/string-comparison-in-bash-not-found/12230723) I tried "sh ./test" and got "[[: not found" so it does seem cron is executing as sh not bash. – feganmeister Mar 11 '19 at 10:15
  • are you using a mac by any chance ? if so, `/bin/bash` is bash 3.2, which doesn't recognize the `${1^^}` syntax – Aserre Mar 11 '19 at 10:17
  • No, and apologies I should have stated my environment: Ubuntu 16.04.5 LTS – feganmeister Mar 11 '19 at 10:20
  • Still, it might be that it runs an old bash version on cron. Try to print `echo $BASH_VERSION $1 ${1^^} $result >> /home/[REDACTED]/mylog` instead. – user1934428 Mar 11 '19 at 12:43

1 Answers1

0

Not sure why, but deleting the first line of the file and retyping has resolved it:

#!/bin/bash

Thanks all for the help!

feganmeister
  • 686
  • 1
  • 8
  • 15