Script not working if crontab scheduled

Hi all,

I'm working to a script with /bin/bash shebang.
The script works perfectly if I run from command line.

The script runs under a non root user and inside the commands are set with sudo command in a such a way they can be run under root, for example (first rows of the script):

#!/bin/bash

#Command directory di NNM###

dir_nnm=/opt/OV/bin
dir_nnm_psg=/opt/OV/nonOV/Postgres/bin


### Ricavo il nome del sec group custom ####


secgroup_name="`sudo $dir_nnm_psg/psql -d nnm -U postgres -tc "select name from public.nms_sec_group" | egrep -iv "default|unresolved" | sed -e 's/^[ \t]*//'`"

I'd like to run in crontab under that non root user but when it starts under crontab the variables are set to empty.

Why this behaviour?

And the scripts runs fine when you execute it ?

yes it does

That means it is set correctly ( or something else missing? ) in your environment, not in the script... why dont you expoprt the variables? If that doesnt solve, then soucre your profile in the script, if that works, copy your profile ot profile4cron so you scource that one
And since you are like unsastified to not know why exaclty, I would comment a profile and uncomment one line after the other to see what was missing...

If the script shown is executed by cron, be sure to use full path to applications inside the script..
Eg: /usr/bin/sudo, /usr/bin/sed, just like you had done for psql using the $dir_nnm_psg..
For egrep i'd alias it like:

alias egrep="/usr/bin/grep -e"

Hth

EDIT:
Also, if you need to enter the password for sudo, it wont work at all, as there is no "input box" or 'terminal' shown to the user, never (afaik).
Further, sudo executes the command as root, so why not execute the script as root directly in the first place?

This is because programs run by cron have no terminal, and sudo uses the current terminal to get a password.