linux 变量中包含runuser的bash脚本不起作用

tzxcd3kk  于 2022-11-22  发布在  Linux
关注(0)|答案(2)|浏览(145)

我试着运行一个命令来识别用户是否是root,然后运行一个带参数的脚本,并检查结果。问题是bash不让我用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

下面是我得到的输出:

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

Bash不喜欢我把runuser放在变量中,并试图在命令中使用引号。它看不到引号,并认为-s是runuser的参数,但事实并非如此。我尝试使用单引号和双引号,但没有任何效果。

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''

如何将runuser导入变量,并让它运行带有参数的命令,而不会出现runuser错误?

6vl6ewon

6vl6ewon1#

将命令及其参数放入数组中:

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

sz81bmfz2#

找到了。谢谢@Biffen。不能在变量中声明命令,需要在函数中声明它们。下面是我的新代码:

#!/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

相关问题