2010-09-16 146 views
10

在我的bash腳本中,我以另一個用戶的身份執行一些命令。我想使用su來調用bash函數。在su命令中運行bash函數

my_function() 
{ 
    do_something 
} 

su username -c "my_function" 

上述腳本不起作用。 my_function當然沒有在su裏面定義。我有一個想法是將函數放入一個單獨的文件中。你有更好的主意,避免製作另一個文件嗎?

回答

11

您可以導出功能,使其可在子shell:

export -f my_function 
su username -c "my_function" 
2

您可以在系統中啓用'sudo',然後使用它。

+0

sudo未啓用。系統管理員不會啓用它。 – 2010-09-16 11:42:24

+2

你如何用'sudo'做到這一點?即使在導出該函數後,一個簡單的'sudo my_function'也不起作用。 – michas 2013-12-05 14:25:12

1

您必須在相同的範圍內使用該功能。所以要麼把函數放在引號內,要麼把函數放到一個單獨的腳本中,然後用su -c運行。

+0

我想在su之外調用相同的腳本。另一個腳本也是我的想法。 – 2010-09-16 11:46:10

0

另一種方式,可以使案件和傳遞參數給執行腳本。例如: 首先創建一個名爲「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 

添加上述代碼後運行這些命令來看看它在行動:

[email protected]:/# chmod +x script.sh #This will make the file executable 
[email protected]:/# ./script.sh   #This will run the script without any parameters, triggering the default action.   
this is my function. 
[email protected]:/# ./script.sh do_my_second_function #Executing the script with parameter 
this function is my second one. 
[email protected]:/# 

爲了儘可能滿足你的要求,你就只需要運行,使這項工作

su username -c '/path/to/script.sh do_my_second_function' 

和一切都應該工作正常。 希望這有助於:)