【问题标题】:Running bash function in command of su在 su 命令中运行 bash 函数
【发布时间】:2011-04-13 04:13:22
【问题描述】:

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

my_function()
{
  do_something
}

su username -c "my_function"

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

【问题讨论】:

    标签: bash shell su


    【解决方案1】:

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

    export -f my_function
    su username -c "my_function"
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • sudo 未启用。系统管理员不会启用它。
      • 您如何使用sudo 做到这一点?一个简单的sudo my_function 将不起作用,即使在导出该函数之后也是如此。
      【解决方案3】:

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

      【讨论】:

      • 我想在 su 外部调用相同的脚本。另一个脚本也是我的主意。
      【解决方案4】:

      另一种方法是创建案例并将参数传递给执行的脚本。 示例可能是: 首先制作一个名为“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'
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-13
        • 2022-09-05
        • 1970-01-01
        • 2015-06-26
        • 2019-12-22
        • 2011-05-14
        相关资源
        最近更新 更多