Home > other >  bash script with runuser in a variable not working
bash script with runuser in a variable not working

Time:11-15

I am trying to run a command that recognizes if the user is root or not, then run a script with parameters, and check the results. The problem is bash wont let me do it with runuser.

#!/bin/bash
check_other_script(){
        user=mruser
        bin_dir=/home/$user/bin
        script_name=myscript
        decho "[d] Performing $script processing of settings check"
        sub_cmd="${bin_dir}/${script_name} -s"
        if [ "$running_user_type" == "root" ]; then
                        #cmd="runuser -l $user -c "$sub_cmd""
        elif [ "$running_user_type" == "non-root" ]; then
                        cmd="$sub_cmd"
        fi
        decho "[d] command to run: $cmd"
        $cmd
    status="$?"
    decho "[d] script status code: $status."

}

check_other_script
exit 0

Here is the output I get though:

runuser -l mruser -c /home/mruser/bin/myscript -s
runuser: option requires an argument -- 's'
Try 'runuser --help' for more information.

Bash does not like how I am putting runuser into a variable and trying to use quotes in the command. It does not see the quotes and thinks -s is a parameter for runuser which it is not. I tried using single quotes an double quotes, nothing works.

cmd="runuser -l $user -c "$sub_cmd""
cmd="runuser -l $user -c '$sub_cmd'"
cmd="runuser -l $user -c \"$sub_cmd\""
cmd='runuser -l $user -c '/home/mruser/bin/myscript -s''

How can I get runuser into a variable and have it run the command with a parameter without errors from runuser?

CodePudding user response:

Put your command with its parameters in an array:

...
sub_cmd="ls -l \"xxxx\""
...
declare -a cmd=("runuser" "-l" "$user" "-c" "$sub_cmd")
...
"${cmd[@]}"
...

CodePudding user response:

Figured it out. Thank you @Biffen. Cant declare commands inside variables, need to declarer them inside functions. Here is my new code that works:

#!/bin/bash
check_other_script(){
        user=mruser
        bin_dir=/home/$user/bin
        script_name=myscript
        decho "[d] Performing $script processing of settings check"
        sub_cmd="${bin_dir}/${script_name} -s"
        if [ "$running_user_type" == "root" ]; then
                        script_cmd(){
                           runuser -l $user -c "$sub_cmd"
                        }
        elif [ "$running_user_type" == "non-root" ]; then
                        script_cmd(){
                           $sub_cmd
                        }
        fi
        script_cmd
    status="$?"
    decho "[d] script status code: $status."

}

check_other_script
exit 0
  • Related