在我的bash脚本中,我执行了其他用户的命令。我想使用bash函数使用 su.

my_function()
{
  do_something
}

su username -c "my_function"

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

有帮助吗?

解决方案

您可以导出该功能以使其可用到子壳:

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归因
不隶属于 StackOverflow
scroll top