在su命令中运行bash函数

在su命令中运行bash函数

问题描述:

在我的bash脚本中,我以另一个用户的身份执行一些命令。我想使用su来调用bash函数。在su命令中运行bash函数

my_function() 
{ 
    do_something 
} 

su username -c "my_function" 

上述脚本不起作用。 my_function当然没有在su里面定义。我有一个想法是将函数放入一个单独的文件中。你有更好的主意,避免制作另一个文件吗?

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

export -f my_function 
su username -c "my_function" 

您可以在系统中启用'sudo',然后使用它。

+0

sudo未启用。系统管理员不会启用它。 – 2010-09-16 11:42:24

+2

你如何用'sudo'做到这一点?即使在导出该函数后,一个简单的'sudo my_function'也不起作用。 – michas 2013-12-05 14:25:12

您必须在相同的范围内使用该功能。所以要么把函数放在引号内,要么把函数放到一个单独的脚本中,然后用su -c运行。

+0

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

另一种方式,可以使案件和传递参数给执行脚本。例如: 首先创建一个名为“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' 

和一切都应该工作正常。 希望这有助于:)