如何使runuser正确转发所有命令行参数,而不是试图解释它们?

问题描述 投票:0回答:1

我有这个简单的脚本:

#!/bin/bash
SOURCE_USER=$USER
DESTINE_USER=$1

id -u $SOURCE_USER > /dev/null 2>&1

if [ "$?" == "1" ] || [ -z $SOURCE_USER ]
then
    printf "Error: Invalid source user '$SOURCE_USER'\\n"
    exit 1
fi

if [ -z $DESTINE_USER ]
then
    printf "Error: Invalid destine user '$DESTINE_USER'\\n"
    exit 1
fi

SOURCE_GROUPS=$(id -Gn ${SOURCE_USER} | sed "s/${SOURCE_USER} //g" | sed "s/ ${SOURCE_USER}//g" | sed "s/ /,/g")
SOURCE_SHELL=$(awk -F : -v name=${SOURCE_USER} '(name == $1) { print $7 }' /etc/passwd)

id -u $DESTINE_USER > /dev/null 2>&1

if [ "$?" == "1" ]
then
    printf "Creating destine user %s\\n" "$DESTINE_USER"
    useradd --groups ${SOURCE_GROUPS} --shell ${SOURCE_SHELL} --create-home ${DESTINE_USER}
    passwd ${DESTINE_USER}
    xhost '+si:localuser:$DESTINE_USER'
    sudo usermod -G "$SOURCE_USER" "$DESTINE_USER"
else
    printf "Updating destine user '%s' with groups '%s' and shell '%s'\\n" "$DESTINE_USER" "$SOURCE_GROUPS" "$SOURCE_SHELL"
    sudo usermod -a -G "$SOURCE_GROUPS" "$DESTINE_USER"
    sudo chsh -s "$SOURCE_SHELL" "$SOURCE_USER"
fi

sudo runuser sublime_vanilla -c "${@:2}"

我像这样运行它:

$ bash run_as_user.sh sublime_vanilla /usr/bin/subl -n "./New Empty File"

但是当我运行它时,我收到了这个错误:

runuser: invalid option -- 'n'
Try 'runuser --help' for more information.

但如果我用sudo runuser sublime_vanilla -c "${@:2}"取代sudo runuser sublime_vanilla -c "\"$2\" \"$3\" \"$4\" \"$5\" \"$6\" \"$7\" \"$8\" \"${@:9}\""

然后,Sublime Text在新窗口中正确打开文件"./New Empty File"

如何使runuser正确理解所有参数与可变数量的命令行参数,即没有硬编码"\"$2\" \"$3\" \"$4\" ..."

bash shell arguments parameter-passing eval
1个回答
1
投票

这与your last question略有不同,因为您必须将参数扩展为-c选项的单个字符串。

bash printf formatter %q是你的朋友:

cmd=$( printf '%q ' "${@:2}" )
sudo runuser sublime_vanilla -c "$cmd"

另一方面,通过runuser手册页快速浏览表明:

sudo runuser -u sublime_vanilla "${@:2}"

另一个想法:sudo runuser -u sublime_vanilla -- "${@:2}"用双连字符表示runuser选项的结束。

© www.soinside.com 2019 - 2024. All rights reserved.