4

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
  • 2
    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
    Commented Jun 24, 2018 at 14:44

1 Answer 1

10

/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?

8
  • 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. Commented Jun 23, 2018 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? Commented Jun 23, 2018 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
    Commented Jun 23, 2018 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. Commented Jun 23, 2018 at 21:46
  • 2
    It's because the sudo echo itself gets elevated privileges, while subsequent stdout redirection remains running with original privileges.
    – steve
    Commented Jun 23, 2018 at 22:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .