FAQ: bash
🆀 .bashrc
などのシェル設定ファイルの読み込み順について教えてください
🅐 読み込み順についての正式な情報源は、bash(1)
マニュアルです。(man bash
コマンドで表示できます。)
以下 4 つの場合でシェル設定ファイルの読み込み順が異なります。bash(1)
マニュアルの該当の記載を併記します。
1, interactive, login shell
ssh
でログインした場合やsu -
を実行した場合など。(su -
はsu --login
と同じ。ログインシェルとしてシェルを起動せよの意味。)
qlogin
した場合もこれに該当します。
~/.bash_profile
, ~/.bash_login
, ~/.profile
の順で探して最初に存在したファイルを読み込みます。
When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, 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. The--noprofile
option may be used when the shell is started to inhibit this behavior.
したがって bash の動作としては SSH でログインした際には~/.bashrc
は自動的には読み込まれませんが、
上記のシェル設定ファイルの中に~/.bashrc
を読み込むように書かれている場合が多い、という関係にあります。
2, interactive, non-login shell
ターミナルエミュレータを起動した場合や、screen
, emacs の shell-mode を起動した場合など。
~/.bashrc
が読み込まれます。
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
.
- 注意: GNU screen と同じような機能を持つポピュラーなソフトウェアとして
tmux
がありますが、tmux
を起動するとデフォルトでは bash はログインシェルとして起動します。
3, non-interactive, login shell
scp を実行する場合や、ローカルマシンにあるスクリプトをリモートサーバ上で実行する場合がこれに当たります。
ssh you@remotehost 'bash -s' < local_script.sh
~/.bashrc
が読み込まれます。
Bash attempts to determine when it is being run with its standard input connected to a network connection, as when executed by the remote shell daemon, usually
rshd
, or the secure shell daemonsshd
. If bash determines it is being run in this fashion, it reads and executes commands from~/.bashrc
, if that file exists and is readable. It will not do this if invoked assh
. The--norc
option may be used to inhibit this behavior, and the--rcfile
option may be used to force another file to be read, but rshd does not generally invoke the shell with those options or allow them to be specified.
4, non-interactive non-login shell
シェルスクリプトを実行した場合など。
シェル設定ファイルは読み込まれません。
参考資料
🆀 環境を初期状態に戻したいのですが、どのようにしたらよいでしょうか。(Ubuntu Linux 22.04 の場合)
🅐 環境を初期状態に戻すには.bash_profile
, .bashrc
を以下の状態に戻してログインし直してください。