簡體   English   中英

我可以在 bash 腳本中間運行 'su' 嗎?

[英]Can I run 'su' in the middle of a bash script?

我可以在腳本中間更改/su 用戶嗎?

if [ "$user" == "" ]; then
  echo "Enter the table name";
  read user
fi

gunzip *
chown postgres *
su postgres 
dropdb $user
psql -c "create database $user with encoding 'unicode';" -U dbname template1
psql -d $user -f *.sql

您可以,但 bash 不會將后續命令作為 postgres 運行。 相反,請執行以下操作:

su postgres -c 'dropdb $user'

-c標志以用戶身份運行命令(請參閱man su )。

您可以使用here 文檔在腳本中嵌入多個su命令:

if [ "$user" == "" ]; then
  echo "Enter the table name";
  read user
fi

gunzip *
chown postgres *
su postgres <<EOSU
dropdb $user
psql -c "create database $user with encoding 'unicode';" -U dbname template1
psql -d $user -f *.sql
EOSU

不是這樣的。 su將調用一個默認為 shell 的進程。 在命令行上,此 shell 將是交互式的,因此您可以輸入命令。 在腳本的上下文中,shell 將立即結束(因為它無關緊要)。

su user -c command

command將以user身份執行 - 如果su成功,通常只有無密碼用戶或以 root 身份運行腳本時才會出現這種情況。

使用sudo以獲得更好、更細粒度的方法。

不,你不能。 或者至少......你可以 su 但 su 將在那時簡單地打開一個新的shell,完成后它將繼續執行腳本的其余部分。

一種解決方法是使用su -c 'some command'

請參閱以下問題中的答案,

您可以在答案中提到的 << EOF 和 EOF 之間寫。

#!/bin/bash
whoami
sudo -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami

如何使用 su 以該用戶身份執行 bash 腳本的其余部分?

我今天聽到的另一個有趣的想法是對腳本進行遞歸調用,當您以 root 身份運行並且希望以其他用戶身份運行腳本時。 請參閱下面的示例:

我以“root”身份運行腳本“my_script”並希望腳本以用戶“raamee”身份運行


#!/bin/bash

#Script name is: my_script

user=`whoami`

if [ "$user" == "root" ]; then
  # As suggested by glenn jackman. Since I don't have anything to run once 
  # switching the user, I can modify the next line to: 
  # exec sudo -u raamee my_script and reuse the same process
  sudo -u raamee my_script
fi

if [ "$user" == "raamee" ]; then
  #put here the commands you want to perform
  do_command_1
  do_command_2
  do_command_3
fi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM