问题描述
我得到了这个简单的脚本:
I got this simple script:
#!/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"
但是当我运行它时,出现了这个错误:
But when I run it, I got this error:
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"
.
Then, Sublime Text correctly opens the file "./New Empty File"
in a new window.
如何使runuser
正确理解具有可变数量的命令行参数的所有参数,即无需硬编码"\"$2\" \"$3\" \"$4\" ..."
?
How to make runuser
correctly understand all argument with a variable number of command line arguments, i.e., without hard coding "\"$2\" \"$3\" \"$4\" ..."
?
推荐答案
这与您的最后一个问题稍有不同,因为您必须将-c选项的参数扩展为单个字符串.
This is slightly different from your last question because you have to make the expansion of the arguments into a single string for the -c option.
bash printf格式化程序%q 是您的朋友在这里:
The bash printf formatter %q is your friend here:
cmd=$( printf '%q ' "${@:2}" )
sudo runuser sublime_vanilla -c "$cmd"
另一方面,快速浏览一下runuser手册页则表明:
On the other hand, a quick perusal through the runuser man page suggests:
sudo runuser -u sublime_vanilla "${@:2}"
另一个想法:sudo runuser -u sublime_vanilla -- "${@:2}"
用双连字符表示运行用户选项的结尾.
Another thought: sudo runuser -u sublime_vanilla -- "${@:2}"
with the double hyphens to indicate the end of the runuser options.
这篇关于如何使runuser正确转发所有命令行参数,而不是尝试解释它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!