質問
私のbashスクリプトでは、別のユーザーとしていくつかのコマンドを実行します。使用してBash関数を呼び出したいです su
.
my_function()
{
do_something
}
su username -c "my_function"
上記のスクリプトは機能しません。もちろん、 my_function
内部で定義されていません su
. 。私が持っているアイデアの1つは、関数を別のファイルに配置することです。別のファイルの作成を避けるより良いアイデアはありますか?
解決
関数をエクスポートして、サブシェルで利用できるようにすることができます。
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'
そして、すべてが正常に機能するはずです。お役に立てれば :)
所属していません StackOverflow