13

私のbashスクリプトでは、別のユーザーとしていくつかのコマンドを実行します。を使用してbash関数を呼び出したいsu

my_function()
{
  do_something
}

su username -c "my_function"

上記のスクリプトは機能しません。もちろん、my_function内部では定義されていませんsu。私が持っているアイデアの1つは、関数を別のファイルに入れることです。別のファイルを作成しないようにするためのより良いアイデアはありますか?

4

4 に答える 4

14

関数をエクスポートして、サブシェルで使用できるようにすることができます。

export -f my_function
su username -c "my_function"
于 2010-09-16T14:19:11.230 に答える
2

システムで「sudo」を有効にして、代わりにそれを使用できます。

于 2010-09-16T11:40:18.847 に答える
1

関数は、使用するのと同じスコープ内にある必要があります。したがって、関数を引用符で囲むか、関数を別のスクリプトに配置して、su-cで実行します。

于 2010-09-16T11:41:24.303 に答える
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'

そして、すべてが正常に機能しているはずです。お役に立てれば :)

于 2010-09-16T15:17:05.780 に答える