su 命令未設定 BASH_VERSION 值且未載入設定檔

su 命令未設定 BASH_VERSION 值且未載入設定檔

我有一個 Ubuntu 20.04 LTS 伺服器版本,在建立新使用者並透過 ssh 連線在 shell 中使用它時遇到一個奇怪的問題。重現它的步驟:

  1. 使用 root 帳戶建立新使用者useradd --create-home test
  2. 從 root 使用者登入以使用 進行測試su test

結果:

root@server:~# useradd --create-home test;
root@server:~# echo $BASH_VERSION
5.0.17(1)-release
root@server:~# su test;
$ echo $BASH_VERSION
$

提示未設置,環境變數未加載,自動完成不起作用,別名不起作用,就好像 .profile 和 .bashrc 檔案不存在,但它們確實存在且權限設定正確:

root@server:/home/test# md5sum /etc/skel/.profile ./.profile 
f4e81ade7d6f9fb342541152d08e7a97  /etc/skel/.profile
f4e81ade7d6f9fb342541152d08e7a97  ./.profile
root@server:/home/test# md5sum /etc/skel/.bashrc ./.bashrc
1f98b8f3f3c8f8927eca945d59dcc1c6  /etc/skel/.bashrc
1f98b8f3f3c8f8927eca945d59dcc1c6  ./.bashrc
root@server:/home/test# ls -lah
total 24K
drwxr-xr-x  3 test test 4.0K Sep 18 13:18 .
drwxr-xr-x  9 root root 4.0K Sep 18 13:17 ..
-rw-r--r--  1 test test  220 Feb 25  2020 .bash_logout
-rw-r--r--  1 test test 3.7K Feb 25  2020 .bashrc
-rw-r--r--  1 test test  807 Feb 25  2020 .profile

當我以測試使用者身分登入時,為什麼無法載入設定檔?

答案1

正如文檔所說su

為了向後相容,su預設不會更改目前目錄,只設定環境變數 HOME 和 SHELL(如果目標使用者不是 root,則加上 USER 和 LOGNAME)。建議始終使用該--login選項(而不是其快捷方式-)以避免混合環境引起的副作用。

當在--login或下時-lsu也會運行登入shell,反過來又獲取.profile.bashrc應該始終獲取)。

若要查看載入了哪些文件,請在文件的開頭插入一行簡單的內容:

echo "$BASH_SOURCE" >&2

相關內容