Setting environment variables explicitly in shell script

Fedora Version : WS 34
Shell : bash

I have a shell script which will be executed by root from root’s cron job.

Within the shell script, I have commands like below and it will error out (saying command not found) during cron job if I don’t set the environment variables.

systemctl restart network

To set the environment variables for this script, I can source the .bash_profile or .bashrc files of root user at the beginning of the script.
But, I am thinking of explicilty setting PATH and HOME variables.

I have 2 questions on this :

  1. What should be the values for PATH and HOME variables for the root user?

  2. Any other relevant environment variables which I should set ?

root’s HOME is usually /root

As for the path, I apologize in advance because I am going to give a different answer than what you asked but…

You should never rely on $PATH in a script. Either specify the commands fully or locate them as part of the script.

2 Likes

Is it worth discussing the larger issue that you’re trying to solve here? Maybe there’s a better way?

2 Likes

Use the full path in you cron job, you can use the command ‘which’ to check where “systemctl” (or any other command lives on your system:

$ which systemctl
/bin/systemctl