LoginSignup
63
74

More than 5 years have passed since last update.

suコマンドの基本

Last updated at Posted at 2016-07-09

suはよく使うが体系的に学んだことがなかったので調べてみました。

コマンド 意味 説明
su ユーザを切り替える(Substitute User) ユーザーを切り替えるのに使用する。

書式

 $ su [-flmp] [-c command] [-s shell] [-] [--help] [user[arg...]] 
オプション名 説明
-f 初期設定ファイル(.bashrc)を実行しない
-l, - ログイン・シェルを使用してユーザーを切り替える
-m, -p 環境変数"HOME","USER","LOGNAME","SHELL"を変更しない
-c ユーザ切り替え後、commnadを実行する
-s shell 指定したシェルを実行する。
--help ヘルプ
user[arg...] ログインするユーザを指定する

使用例


「管理者権限を見てみる。」

# (e.g:vagrantユーザ → rootユーザ)
[vagrant@localhost ~]$ id
uid=500(vagrant) gid=500(vagrant) 所属グループ=500(vagrant) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[vagrant@localhost ~]$ whoami
vagrant

[vagrant@localhost ~]$ su // userを省略するとrootになります。
パスワード: vagrant
[root@localhost vagrant]/# id
uid=0(root) gid=0(root) 所属グループ=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[root@localhost vagrant]/# whoami
root

「 [ - ] の有無について」
「-」をつけた場合は、現在のシェルの環境変数をすべて解除し、その上で指定したユーザーとしてシェルを起動します。そして、カレントディレクトリをそのユーザーホームディレクトリとします。

# (e.g:vagrantユーザ → rootユーザ)

# 環境変数を作成
[vagrant@localhost ~]$ export SAMPLE=sample
[vagrant@localhost ~]$ echo $SAMPLE
sample
[vagrant@localhost ~]$ pwd
/home/vagrant // 現在のディレクトリ

#「-」なし
[vagrant@localhost ~]$ su
パスワード:

[root@localhost vagrant]/# echo $SAMPLE
sample  //環境変数が引き継がれている

[root@localhost vagrant]/# pwd
/home/vagrant // カレントディレクトリのまま

# 「-」あり
[vagrant@localhost ~]$ su -
パスワード:

[root@localhost ~]/# echo $SAMPLE

[root@localhost ~]/# pwd
/root // ホームディレクトリ

-cの使用例(ユーザ切り替え後、commnadを実行する)

# rootユーザで「test.txt」ファイルを作成してみる。
[vagrant@localhost ~]$ su -c 'touch test.txt; ls -la test.txt' -
パスワード:
-rw-r--r--. 1 root root 0 Jul  9 15:03 test.txt // rootユーザで作成されています。
[vagrant@localhost ~]$
63
74
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
63
74