[英]Running bash function in command of su
在我的bash腳本中,我以其他用戶身份執行一些命令。 我想使用su
調用bash函數。
my_function()
{
do_something
}
su username -c "my_function"
上面的腳本不起作用。 當然,在su
內部未定義my_function
。 我的一個想法是將函數放入單獨的文件中。 您是否有一個更好的主意,避免制作另一個文件?
您可以導出該函數以使其可用於子shell:
export -f my_function
su username -c "my_function"
您可以在系統中啟用“ sudo”,而改用它。
您必須在與使用該功能相同的范圍內擁有該功能。 因此,可以將函數放在引號內,或將函數放入單獨的腳本中,然后使用su -c運行該腳本。
另一種方法是創建案例並將參數傳遞給執行的腳本。 例如:首先創建一個名為“ script.sh”的文件。 然后在其中插入以下代碼:
#!/bin/sh
my_function() {
echo "this is my function."
}
my_second_function() {
echo "this is my second function."
}
case "$1" in
'do_my_function')
my_function
;;
'do_my_second_function')
my_second_function
;;
*) #default execute
my_function
esac
添加以上代碼后,運行以下命令以查看其運行情況:
root@shell:/# chmod +x script.sh #This will make the file executable
root@shell:/# ./script.sh #This will run the script without any parameters, triggering the default action.
this is my function.
root@shell:/# ./script.sh do_my_second_function #Executing the script with parameter
this function is my second one.
root@shell:/#
要按照您的要求進行這項工作,您只需要運行
su username -c '/path/to/script.sh do_my_second_function'
並且一切都應該正常工作。 希望這可以幫助 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.