U b u n t u Ubuntu Ubuntu 系统在用户登录时,会自动执行 / e t c / p r o f i l e /etc/profile /etc/profile,查看该脚本可以看到:

# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).

if [ "$PS1" ]; then
  if [ "$BASH" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    fi
  else
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi

在最后几行脚本中,首先会判断是否存在 / e t c / p r o f i l e . d /etc/profile.d /etc/profile.d 文件夹,如果存在则会遍历该文件夹下的 ∗ . s h *.sh .sh 脚本并挨个执行。

所以想要在用户登录时自动执行脚本,不必修改 / e t c / p r o f i l e /etc/profile /etc/profile 脚本,当然修改这个脚本也是可以做到的,不过不推荐,只需要在 / e t c / p r o f i l e . d /etc/profile.d /etc/profile.d 文件夹下,写一个 x . s h x.sh x.sh 脚本即可,具体可以参考该文件夹下其他脚本,另外写完脚本以后,也无需对他修改权限,因为执行他的命令并不是 . / x . s h ./x.sh ./x.sh 的方式,而是 .   x . s h .\ x.sh . x.sh,相当于 s h   x . s h sh\ x.sh sh x.sh