Linux可以做條件判斷在Linux的某一行插入內容嗎

Linux可以做條件判斷在Linux的某一行插入內容嗎

Linux可以做條件判斷在Linux的某一行插入內容嗎?

例如,我想將用戶“test”新增至/etc/sudoers,讓它可以切換到root:

  1 #
  2 # This file MUST be edited with the 'visudo' command as root.
  3 #
  4 # Please consider adding local content in /etc/sudoers.d/ instead of
  5 # directly modifying this file.
  6 #
  7 # See the man page for details on how to write a sudoers file.
  8 #
  9 Defaults        env_reset
 10 Defaults        mail_badpass
 11 Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"
 12 
 13 # Host alias specification
 14 
 15 # User alias specification
 16 
 17 # Cmnd alias specification
 18 
 19 # User privilege specification
 20 root    ALL=(ALL:ALL) ALL
 21 
 22 # Members of the admin group may gain root privileges
 23 %admin ALL=(ALL) ALL
 24 
 25 # Allow members of group sudo to execute any command
 26 %sudo   ALL=(ALL:ALL) ALL
 27 
 28 # See sudoers(5) for more information on "#include" directives:
 29 
 30 #includedir /etc/sudoers.d

我希望我的命令找到第 20 行(如果 root ALL=(ALL:ALL) ALL ),然後在第 21 行添加以下內容

test    ALL=(ALL:ALL) ALL

Linux 命令可以做到這一點嗎?

我對 Linux 很陌生,非常感謝任何幫助!

答案1

在哪裡添加該行並不重要,sudo 不關心順序。

只需將其附加到末尾即可:

echo 'test    ALL=(ALL:ALL) ALL' | sudo tee -a /etc/sudoers

或者,更好的是,使用包含目錄:

echo 'test    ALL=(ALL:ALL) ALL' | sudo tee /etc/sudoers.d/test

這樣,當 sudoers 檔案在套件更新期間發生變更時,您無需手動更新它。

相關內容