From 6e9ab553b8006a14723db673c62d595364dc3be6 Mon Sep 17 00:00:00 2001 From: ericgaspar Date: Fri, 22 Jan 2021 17:08:28 +0100 Subject: [PATCH] Add ynh_exec_as to official --- data/helpers.d/logging | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/data/helpers.d/logging b/data/helpers.d/logging index dc32ecba9..e5d208a0f 100644 --- a/data/helpers.d/logging +++ b/data/helpers.d/logging @@ -100,6 +100,30 @@ ynh_print_err () { ynh_print_log "[Error] ${message}" >&2 } +# Execute a command as another user +# +# usage: ynh_exec_as --user=USER --command=COMMAND [ARG ...] +# | arg: -u, --user= - the user that will execute the command +# | arg: -n, --command= - the command to be executed +# +# Requires YunoHost version 4.1.7 or higher. +ynh_exec_as() +{ + # Declare an array to define the options of this helper. + local legacy_args=uc + local -A args_array=( [u]=user= [c]=command= ) + local user + local command + # Manage arguments with getopts + ynh_handle_getopts_args "$@" + + if [[ $user = $(whoami) ]]; then + eval "$command" + else + sudo -u "$user" "$command" + fi +} + # Execute a command and print the result as an error # # usage: ynh_exec_err your_command