I heard through the grapevine that files in /etc/profile will be automatically sourced by bash upon login?

I tried writing something simple to /etc/profile:

 echo "echo 'foo'" > /etc/profile/foo.sh

but I got this weird error:

bash: /etc/profile/foo.sh: Not a directory

is there a correct way to do this?

  • 1
    Don't listen to the grapevine. Look things up in your shell's manual instead. There, it may say that it sources /etc/profile, so have a look at that file. There, it may say that it's sourcing all the files in /etc/profile.d, or it may not, depending on your system. It certainly doesn't on my machine. – Kusalananda Jun 24 at 14:44
up vote 8 down vote accepted

/etc/profile is a file. Hence the error when trying to create /etc/profile/foo.sh.

/etc/profile.d is the directory you're thinking of. Scripts placed in there get sourced on login. In your example, you'd want to create /etc/profile.d/foo.sh.

The script logic behind this and how it's pulled in can be seen below. Similar code is in /etc/profile, /etc/bashrc, /etc/csh.cshrc and /etc/csh.login.

$ grep -A 8 ^for.*profile.d /etc/profile
for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do
    if [ -r "$i" ]; then
        if [ "${-#*i}" != "$-" ]; then
            . "$i"
        else
            . "$i" >/dev/null
        fi
    fi
done
$

Example of creating and invoking such a script:

# echo id >/etc/profile.d/foo.sh
# su - steve
Last login: Sat Jun 23 21:44:41 UTC 2018 on pts/0
uid=1000(steve) gid=1001(steve) groups=1001(steve),4(adm),39(video),1000(google-sudoers) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
$

More information at What do the scripts in /etc/profile.d do?

  • 1
    got it so /etc/profile sources the files in /etc/profile.d folder. Can you add an example of how to write a new file to /etc/profile.d? I am getting permissions issues. I assume sudo is needed, but can't figure it out. – Alexander Mills Jun 23 at 21:41
  • 1
    Also, when /etc/profile.d files are run, I assume they are not run as root, but instead run as whoever is logging in? – Alexander Mills Jun 23 at 21:42
  • 1
    Yes, root needed. Otherwise some doofus could create a nasty script that got executed by anyone using the server. When actually run, they run as whoever is logging in. – steve Jun 23 at 21:44
  • 1
    Ok thanks, frustratingly, if I run this sudo echo "echo 'here here now.';" > /etc/profile.d/alex.sh, I still get a permissions error. Weird. – Alexander Mills Jun 23 at 21:46
  • 2
    It's because the sudo echo itself gets elevated privileges, while subsequent stdout redirection remains running with original privileges. – steve Jun 23 at 22:01

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.