在su命令下运行bash函数
在我的bash脚本中,我作为另一个用户执行一些命令。我想使用在su命令下运行bash函数,bash,shell,su,Bash,Shell,Su,在我的bash脚本中,我作为另一个用户执行一些命令。我想使用su调用bash函数 my_function() { do_something } su username -c "my_function" 上面的脚本不起作用。当然,my_函数没有在su中定义。我的一个想法是将函数放入一个单独的文件中。您是否有更好的办法避免生成另一个文件?您可以在系统中启用“sudo”,并使用它。您必须在使用它的相同范围内使用该功能。因此,要么将函数放在引号内,要么将函数放在单独的脚本中,然后使用su-c运行
su
调用bash函数
my_function()
{
do_something
}
su username -c "my_function"
上面的脚本不起作用。当然,
my_函数
没有在su
中定义。我的一个想法是将函数放入一个单独的文件中。您是否有更好的办法避免生成另一个文件?您可以在系统中启用“sudo”,并使用它。您必须在使用它的相同范围内使用该功能。因此,要么将函数放在引号内,要么将函数放在单独的脚本中,然后使用su-c运行该脚本。您可以导出函数以使其可用于子shell:
export -f my_function
su username -c "my_function"
另一种方法是生成案例并将参数传递给执行的脚本。 例如: 首先创建一个名为“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'
一切都应该很好。
希望这有帮助:)sudo未启用。系统管理员将无法启用它。如何使用
sudo
?简单的sudo my_函数
即使在导出该函数后也无法工作。我想在su之外调用相同的脚本。另一个剧本也是我的主意。