これは、なにをしたくて書いたもの?
Linuxで、現在使っているシェルを知りたい、ということで。
環境
確認環境は、こちらです。
$ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 20.04.2 LTS Release: 20.04 Codename: focal $ uname -srvmpio Linux 5.4.0-72-generic #80-Ubuntu SMP Mon Apr 12 17:35:00 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
確認方法
こんな感じで確認できます。
$$とpsコマンドを使う方法。
$ ps -p $$
PID TTY TIME CMD
1012 pts/0 00:00:00 bash
$0を使う方法。
$ echo $0 -bash
どちらも、シェルの特殊変数です。
$$はシェルのプロセスIDなので、これを利用してpsコマンドで検索しています。
($$) Expands to the process ID of the shell.
$0は、シェルまたはシェルスクリプト名に展開されます。
($0) Expands to the name of the shell or shell script.
Special Parameters (Bash Reference Manual)
SHELL環境変数
ところで、$SHELL環境変数を使うことで、ログインシェルを知ることもできます。
$ echo $SHELL /bin/bash
The full pathname to the shell is kept in this environment variable. If it is not set when the shell starts, bash assigns to it the full pathname of the current user's login shell.
bash(1): GNU Bourne-Again SHell - Linux man page
Then the HOME, PATH, SHELL, TERM, MAIL, and LOGNAME environment variables are set.
login(1): sign on - Linux man page
ですが、あくまでこれはログインシェルであるため、今回の目的には使えません。
たとえばdashに切り替えて実行しても、ログインシェルがbashだった場合は、$SHELLはbashのままになっています。
$ dash $ echo $SHELL /bin/bash
$$や$0であれば、こういったケースでも反映されます。
$ dash
$ ps -p $$
PID TTY TIME CMD
1035 pts/0 00:00:00 dash
$ echo $0
dash
どうしてこれを調べたのか?
ところで、どうしてこの情報を調べたかというと。
たとえば、Ubuntu Linuxを使ってDockerイメージを作ろうとして、RUNを使う時のシェルをbashと思い込んだりしていると
ハマることがあるからですね(?)
Dockerfile
FROM ubuntu:20.04 RUN ps -p $$ RUN echo $0 RUN ls -l /bin/sh
イメージビルド。
$ docker image build -t kazuhira/ubuntu:20.04 .
Sending build context to Docker daemon 2.048kB
Step 1/4 : FROM ubuntu:20.04
---> 7e0aa2d69a15
Step 2/4 : RUN ps -p $$
---> Running in 20ddbac68399
PID TTY TIME CMD
1 ? 00:00:00 sh
Removing intermediate container 20ddbac68399
---> 833ba210cce2
Step 3/4 : RUN echo $0
---> Running in ebb8269363b4
/bin/sh
Removing intermediate container ebb8269363b4
---> aae0638b98b8
Step 4/4 : RUN ls -l /bin/sh
---> Running in c2cf9d68a1a4
lrwxrwxrwx 1 root root 4 Jul 18 2019 /bin/sh -> dash
Removing intermediate container c2cf9d68a1a4
---> d8b7bde05fa0
Successfully built d8b7bde05fa0
Successfully tagged kazuhira/ubuntu:20.04
はい、バッチリdashです。
lrwxrwxrwx 1 root root 4 Jul 18 2019 /bin/sh -> dash
その割には、コンテナを起動してみるとbashだったり…。
$ docker container run -it --rm kazuhira/ubuntu:20.04
root@3729361dc201:/# ps -p $$
PID TTY TIME CMD
1 pts/0 00:00:00 bash
root@3729361dc201:/# echo $0
/bin/bash