Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

run: /bin/bash /test.bash

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

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

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?

like image 658
Sanya Snex Avatar asked Apr 09 '26 08:04

Sanya Snex


1 Answers

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:

#!/bin/bash

# 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 | awk '/IP4-SETTINGS[.]GATEWAY:/ { 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.

like image 129
Charles Duffy Avatar answered Apr 10 '26 20:04

Charles Duffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!