如何在* nixlogin时运行脚本?

我知道我有一次知道如何做到这一点,但是…你如何运行一个脚本(bash是好的)在UNIX上login?

从维基百科Bash

当Bash开始时,它以各种不同的脚本执行命令。

当Bash作为交互式loginshell被调用时,它首先从文件/ etc / profile中读取和执行命令,如果该文件存在的话。 读取该文件后,它将按照该顺序查找〜/ .bash_profile,〜/ .bash_login和〜/ .profile,并从第一个存在并读取的第一个中读取和执行命令。

当loginshell退出时,Bash从文件〜/ .bash_logout中读取并执行命令(如果存在)。

当一个不是loginshell的交互式shell被启动时,如果该文件存在,Bash将读取并执行〜/ .bashrc中的命令。 这可以通过使用–norc选项来禁止。 –rcfile文件选项将强制Bash从文件而不是〜/ .bashrc中读取和执行命令。

login时,大多数shell会执行一个login脚本,您可以使用它来执行您的自定义脚本。 shell执行的login脚本当然取决于shell:

  • bash:.bash_profile,.bash_login,.profile(用于向后兼容)
  • sh:.profile
  • tcsh和csh:.login
  • zsh:.zshrc

你可能会发现你在做什么shell

echo $SHELL 

从提示。

当使用Bash时, ~/.bash_profile~/.bash_login~/.profile将会为一个交互式loginshell运行。 我相信~/.profile通常由Bash之外的Unix shell来运行。 Bash将为非login交互式shell运行~/.bashrc

我通常把所有我想要的东西放在.bashrc ,然后从.bash_profile运行它,在那里我还设置了一些应该只在login时运行的东西,比如设置ssh-agent或运行screen

如果你想运行一个脚本和一个脚本,你可以使用户使用默认的shell。

 echo "/usr/bin/uptime" >> /etc/shells vim /etc/passwd * username:x:uid:grp:message:homedir:/usr/bin/uptime 

可以有有趣的效果:)(它不安全的寿,所以不要太信任它,没有什么比设置你的默认shell是擦拭你的驱动器的脚本…虽然,我可以想象一个场景,可能会非常有用)

如果你在OSX上,那么它是~/.profile

把它放在你的bashconfiguration文件中 :

 ~/.bash_profile 

Launchd是OS X中的首选方式。

如果你想让它在你的login运行,把它放在~/Library/LaunchAgents

开始launchd项目

 launchctl load /Library/LaunchDaemons/com.bob.plist 

停止项目

 launchctl unload /Library/LaunchDaemons/com.bob.plist 

示例com.bob.plist

 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>com.bob</string> <key>RunAtLoad</key> <true/> <key>ProgramArguments</key> <array> <string>/usr/bin/java</string> <string>-jar</string> <string>/Users/user/program.jar</string> </array> </dict> </plist> 

这个问题我好几天都感到沮丧。 没有任何工作在Ubuntu上。 如果我把这个调用放在/ etc / profile中,它在login尝试时都会崩溃。 我不能使用“启动应用程序”,因为这不是我想要的。 这只会为当前用户设置脚本。

最后我发现这个小文章: http : //standards.freedesktop.org/autostart-spec/autostart-spec-0.5.html

解决办法是:

  1. 找出$ XDG_CONFIG_DIRSpath:

    echo $ XDG_CONFIG_DIRS

  2. 把你的脚本放在那个目录下

在执行脚本的/etc/profile中添加一个条目。 这将在每次login时运行。 如果您只为自己的帐户执行此操作,请使用其中一个login脚本(例如.bash_profile )来运行它。

在本地系统的bash手册页中search^ INVOCATION,以获取启动时要读取哪个文件的信息。

 man bash /^INVOCATION 

同样在FILES部分,

  ~/.bash_profile The personal initialization file, executed for login shells ~/.bashrc The individual per-interactive-shell startup file 

将您的脚本添加到正确的文件。 确保脚本位于$ PATH中,或使用脚本文件的绝对path。

脚本~/.bash_profile在login时运行。