在su的命令中运行bash函数

时间:2010-09-16 11:30:28

标签: bash shell su

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

my_function()
{
  do_something
}

su username -c "my_function"

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

4 个答案:

答案 0 :(得分:13)

您可以导出该函数以使其可用于子shell:

export -f my_function
su username -c "my_function"

答案 1 :(得分:2)

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

答案 2 :(得分:1)

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

答案 3 :(得分: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

添加上面的代码后,运行这些命令以查看它的实际效果:

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'

一切都应该正常。 希望这会有所帮助:)