Export USER env variable for use in cron

I have a script that requires setting the env USER variable. Since the script is used by several users, I cannot just do export USER=xxx at the beginning of the script. I could define in crontab , but I'm just wondering if there is a good way to pull it.

I tried sourcing .bashrc and .profile , but none of them defines USER, and Ubuntu .bashrc just returns to non-interactive shells.

+4
source share
3 answers

You can get around this by writing at the top of the script (Bashism):

 USER=$(whoami) 

or old style:

 USER=`whoami` 

... if you have whoami in PATH , which can also be set in crontab in the same way as several (most?) other variables. That is, you can also set the variable in crontab (at least in Vixies cron ) - see here .

+5
source

Use the env command. Your crontab entry might look like this:

 * * * * * env USER=foouser /path/to/script.sh 
+4
source

You can specify the environment variable before the command. Thus, it will not affect anything else in crontab.

user.sh:

 #!/bin/sh echo $USER 

cli:

 USER=foo ./user.sh ## outputs "foo" 
0
source

Source: https://habr.com/ru/post/1447488/


All Articles