Dear community,
what I'm try to do is deny users to run a script without parameters from command bash, but the same script should run without parameters only from crontab.
Example runs by crontab:
*/5 * * * * /tmp/script.sh
Here the normal execution starts every 5 minutes
Example #1 runs by user:
# /tmp/script.sh
Output: You cannot start script without parameters
Example #2 runs by user:
# /tmp/script.sh --help
Output: OK I'll give you help
execution starts taking care the parameter
could be a solution, however "stupid" user :rolleyes: can check the crontab and see the flag, then run the script with --crontab flag causing disaster!
About the env, I don't understand what you mean, could you please report an example?
Look values. Is there some usable variable. Or run crontab using some special user. Then check in the script, is the user your cron user or not.
Variable is not so good, because user can set 1st the variable and then run the script.
Then you already know how to preserve and restore file descriptors. The important thing is that you get rid of the error message that moment, afterwards you can put stderr right where it was.
And you don't have to use 5 in my code. Make it 7 since you're already using 5 and 6.
Corona, sorry if I resume the thread, but finally I had time to test your code.
CheckInteractive ()
{
if exec 7</dev/tty
then
bold=`tput bold`
normal=`tput sgr0`
echo ; echo "${bold}WARNING: SCRIPT cannot start from command line, use parameters instead (interactive mode)!${normal}"
exit
fi
}
CheckInteractive
Rest of the script
This works perfect when on terminal, but generate error when start from crontab and the rest of the script is not executed. This is the mail content it generated every time script starts from crontab:
TERM environment variable not set.
/tmp/test.sh[345]: /dev/tty: cannot open [No such device or address]
Thank you, but I notice that the error stop the rest of the script as reported in my post. So the problem is not only the generated mail!
But probably you have replied before I modified my post!
I did warn you there'd be error message spam. I also told you how to deal with that. Redirect stderr into /dev/null so the messages don't go into your cron mails, but save that FD for later before you do so so you can restore it afterwards.
Your code already does this kind of redirection, you appeared to know how to do so already. I'll show you again though.
CheckInteractive ()
{
exec 10<&2 # Make a copy in FD 10
exec 2>/dev/null
if exec 7</dev/tty
then
bold=`tput bold`
normal=`tput sgr0`
echo ; echo "${bold}WARNING: SCRIPT cannot start from command line, use parameters instead (interactive mode)!${normal}"
exit
fi
exec 2>&10 # Restore stderr
exec 10>&- # Close the copy
}