我们如何在* nix登录时运行脚本?

时间:2020-03-06 14:23:34  来源:igfitidea点击:

我知道我曾经知道如何执行此操作,但是...如何在登录UNIX时运行脚本(bash正常)?

解决方案

脚本〜/ .bash_profile在登录时运行。

将其放在bash个人资料中:

~/.bash_profile

如果我们使用的是OSX,则为〜/ .profile。

从维基百科Bash

When Bash starts, it executes the commands in a variety of different
  scripts.
  
  When Bash is invoked as an interactive
  login shell, it first reads and
  executes commands from the file
  /etc/profile, if that file exists.
  After reading that file, it looks for
  ~/.bash_profile, ~/.bash_login, and
  ~/.profile, in that order, and reads
  and executes commands from the first
  one that exists and is readable.
  
  When a login shell exits, Bash reads
  and executes commands from the file
  ~/.bash_logout, if it exists.
  
  When an interactive shell that is not
  a login shell is started, Bash reads
  and executes commands from ~/.bashrc,
  if that file exists. This may be
  inhibited by using the --norc option.
  The --rcfile file option will force
  Bash to read and execute commands from
  file instead of ~/.bashrc.

当使用Bash时,〜/ .bash_profile,〜/ .bash_login和〜/ .profile中的第一个将为交互式登录shell运行。我相信〜/ .profile通常由Bash之外的Unix shell运行。 Bash将为非登录交互shell运行〜/ .bashrc`。

我通常将我想始终设置的所有内容都放在.bashrc中,然后从.bash_profile中运行它,在那里我还设置了一些仅在登录时才能运行的东西,例如设置ssh代理程序"或者"正在运行的屏幕"。

如果我们希望只运行一个脚本,而只运行一个脚本,则可以使其成为用户默认的shell。

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

可能会产生有趣的效果:)(它不太安全,所以不要太信任它。没有什么比将默认外壳程序设置为擦除驱动器的脚本好了。可能非常有用)

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

登录时,大多数外壳程序都会执行登录脚本,我们可以使用该脚本执行自定义脚本。 Shell执行的登录脚本当然取决于Shell:

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

我们可能会发现我们正在使用什么shell

echo $SHELL

从提示。

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

man bash
/^INVOCATION

同样在"文件"部分,

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

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

启动是OS X中的首选方式。

如果我们希望它在登录名上运行,请将其放入〜/ 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>