【发布时间】:2019-11-21 00:47:00
【问题描述】:
我正在开发一个 shell 程序来自动化我的 Arch(强制 btw)安装。为了使其更具交互性,我构建了以下函数:
# READYN
# ARGS:
# - Yes/no question
# - Command to run if yes
# - Command to run if no
#
# Prompts the user with a yes/no question (with precedence for yes) and
# run an order if the answer is yes or another if it's no.
readyn () {
while :
do
local yn;
printf "%s? [Y/n]: " "$1";
read yn;
if [[ "$yn" =~ ^([yY][eE][sS]|[yY])?$ ]]; then
$2;
break;
elif [[ "$yn" =~ ^([nN][oO]|[nN])+$ ]]; then
$3;
break;
fi
done
}
我已成功将 "echo Hello World!" 作为参数传递并运行它。我还能够传递另一个函数。例如:
yayprompt () {
printf "yay is required to install %s.\n" "$1"
readyn "Install yay, the AUR manager" "yayinstall" ""
}
如果是,则调用yayinstall,如果不是,则不执行任何操作。
我的问题来自更复杂的函数,这些函数作为参数传递,但要么无法识别,要么在不应该运行时运行。问题来自以下功能:
# MANAGEPGK
# ARGS:
# - Package name
# - Package variable
# - Yay required
#
# Checks if the package is added to the pkglist to either add or remove it.
# If yay is required to install it, it prompts the user whether they wish
# to install yay or don't install the package (if yay is not installed).
# This functions DOES NOT prompt any installation options on the user. To
# do this, use PROMPTPKG.
managepkg () {
local pkgvar=$2
if [ $pkgvar == 0 ]; then
if [ $3 == 1 ] && [ $yay == 0 ]; then
yayprompt;
fi
if [ $3 == 0 ] || [ $yay == 1 ]; then
addpkg "$1";
pkgvar=1;
fi
else
rmpkg "$1";
pkgvar=0;
fi
echo "$pkgvar";
}
为了让它正常工作,它必须(或者至少我不得不)这样调用:
dewm_cinnamon=$(managepkg cinnamon $dewm_cinnamon 0)
现在,我正在尝试将其作为参数传递给 readyn,但这些输出取决于格式(我总是将 yes 回答为空字符串:
简单引号:
readyn "Install gaps" \
'dewm_i3gaps=$(managepkg i3-gaps $dewm_i3gaps 0)' \
'dewm_i3=$(managepkg i3-wm $dewm_i3 0)';
Install gaps? [Y/n]:
./architup.sh: line 341: dewm_i3gaps=$(managepkg: command not found
双引号:
readyn "Install gaps" \
"dewm_i3gaps=$(managepkg i3-gaps $dewm_i3gaps 0)" \
"dewm_i3=$(managepkg i3-wm $dewm_i3 0)";
Install gaps? [Y/n]:
./architup.sh: line 341: dewm_i3gaps=1: command not found
附上美元:(这个运行两个命令,如 cat pkglist 所示)
readyn "Install gaps" \
$(dewm_i3gaps=$(managepkg i3-gaps $dewm_i3gaps 0)) \
$(dewm_i3=$(managepkg i3-wm $dewm_i3 0));
Install gaps? [Y/n]:
Install compton? [Y/n]: ^C
Documents/Repositories/architup took 5s
➜ cat pkglist
i3-gaps
i3-wm
我应该使用什么语法让readyn根据用户输入只运行一个命令?
谢谢!
【问题讨论】:
-
为什么必须为您的安装编写脚本,这对您的实际问题有何影响?还是您只是想推荐您选择的发行版?
-
@tripleee 我指的是I use Arch btw meme。在我说我使用 Arch 之后,btw 是强制性的:p
标签: linux bash shell command-line command-line-arguments