Bash – How to write an automatically sourced shell script to /etc/profile

bashetcprofile

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?

Best Answer

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

Related Question