zl程序教程

您现在的位置是:首页 >  Python

当前栏目

Ubuntu 用户登录自启脚本

2023-04-18 14:05:46 时间

Ubuntu 系统在用户登录时,会自动执行 /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

在最后几行脚本中,首先会判断是否存在 /etc/profile.d 文件夹,如果存在则会遍历该文件夹下的 *.sh 脚本并挨个执行。

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