Sanya Snex Sanya Snex - 2 months ago 13x
Bash Question

Bash empty variable after running cron, but runs manually

I have simple bash script that working manual at the terminal, but after cron gives an empty variable.

gwip=`/usr/bin/nmcli dev list iface eth0 | grep IP4-SETTINGS.GATEWAY: | awk '{ print $2}'`
printf '%s\n' "$(date) =- $gwip -= " >> /var/log/looog.log

/bin/bash /test.bash

output in file /var/log/looog.log:

1 monday 2016 14:17:36 +0300 =- -=

When I run through cron, variable is empty.

*/1 * * * * root /bin/bash /test.bash

output in file /var/log/looog.log:

1 monday 2016 14:19:13 +0300 =- -=

Why variable $gwip is empty? how to fix it?


Qualifying /usr/bin/nmcli isn't enough -- you're calling a bunch of other tools that need to be found from the PATH also.

Also, in general -- when debugging a cron job, arrange for its stderr to go to a file, like so:


# log stdout and stderr to two different files
exec >>/var/log/looog.log 2>>/var/log/looog.err.log

# ...and log every command we try to execute to stderr (aka looog.err.log)
set -x

# set a PATH variable
export PATH=/bin:/usr/bin

# original code here, using modern POSIX $() syntax, vs old hard-to-nest ``
gwip=$(nmcli dev list iface eth0 | grep IP4-SETTINGS.GATEWAY: | awk '{ print $2}')
printf '%s\n' "$(date) =- $gwip -= "

The key things here are the explicitly-set PATH (not having the value you expect set in PATH is a common issue in cron jobs), and the stderr log (which ensures that any other issues can be identified by reading its contents).

Note the use of a single redirection to looog.log up-front. This doesn't make a significant difference when you're literally only running one print statement, but if you would have extended this script to have more than one, it's more efficient to open your output file only one than to re-open it every time you have something to write.