I have created a script that smartd daemon (smartmontools) executes as per command below.DEVICESCAN -a -m email -M test -M exec /usr/share/smartmontools/my-script -n stand...Smartd appears to be running as root looking at the top command output but it fails to find a config file in /root. $USER, $HOME, whoami, export USER=$(id -u -n) commands do not echo anything, not even an empty line. When executed manually in terminal it prints the current username as expected. Script was chmod'ed to 700.Why is this happening?Edit: Here is the actual script that I want to run.#!/bin/shexport USER=$(id -u -n)echo $whoamiecho USER: echo $USERecho $HOMEEMAIL_EXEC=mailxEMAIL_ACCOUNT=gmailEMAIL_SUBJECT=simplifiedEMAIL_BODY=simplifiedecho $EMAIL_BODY  | $EMAIL_EXEC -A $EMAIL_ACCOUNT -s $EMAIL_SUBJECT email@gmail.comAfter restarting smartd errors are found in the log and no email is sent unlike if executed manually as root.sudo systemctl restart smartdjournalctl -u smartdHere is the output of journalctl log:Test of /etc/smartmontools/run.d/email to email@gmail.com produced unexpected output (69 bytes) to STDOUT/STDERR:USER:rootAccount `gmail' does not exist.No mail for rootexport USER=$(id -u -n) appears to have set the $USER variable as you mentioned. gmail is a profile in /root/.mailrc file. Same error is produced when running as non-root user because the .mailrc file is missing in users home.How can I set the $HOME variable like the $USER variable? That might give an idea why it's not finding the file.
Shell script printing blank $USER variable when executed by Smartd
shell;shell script;arch linux;root;smartctl
Your ultimate problem was that mailx, when called from a shell script run by smartd, started by systemd, on Arch Linux, was not reading the root user's $HOME/.mailrc file.This was caused by a few factors:The mailx on Arch Linux, s-nail, relies on the environment variable HOME when looking for the .mailrc file. If HOME isn't present, it uses the current working directory.  if ((cp = getenv(HOME)) == NULL)      cp = .; /* XXX User and Login objects; Login: pw->pw_dir */  homedir = savestr(cp); systemd sets HOME only when the unit configuration file contains the User option.From Environment variables in spawned processes:$USER, $LOGNAME, $HOME, $SHELLUser name (twice), home directory, and the login shell. The variables are set for the units that have User= set, which includes user systemd instances.Since there was no HOME variable in the environment provided to smartd, and it was likely started in the / directory, mailx didn't read the /root/.mailrc file.To fix: add the lineexport HOME=~orexport MAILRC=~/.mailrcto the shell script before it invokes mailxor (not tested by me) addUser=rootto the [Service] stanza of your smartd.service unit configuration file.