POSIX equivalent to prinf -v



我有一个脚本,根据输入用另一个值替换一个变量:

#!/bin/bash
prompt()
{
while true; do
read -p "Do you wish to install this program? " "ANSWER"
case "$ANSWER" in
[Yy]* ) printf -v "$1" %s "true"; break;;
[Nn]* ) printf -v "$1" %s "false"; break;;
* ) echo "Please answer yes or no.";;
esac
done
}
prompt "QUESTION"
if [ "$QUESTION" = "true" ]; then
echo "SUCCESS"
elif [ "$QUESTION" = "false" ]; then
echo "FAILURE"
fi

虽然我希望脚本与POSIX兼容,但这样做很好。我的所有脚本都使用#!/bin/sh,尽管printf -v是抨击。如何修改此程序?有没有我可以使用的等效函数?谢谢

read本身可以设置名称在$1中的变量。但是,您仍然需要首先使用read ANSWER,以便检查响应。完成后,您可以使用read和here文档将$ANSWER的值传递给prompt请求的任何变量。

prompt () {
while :; do
printf "Do you wish to install this program? " >&2
read ANSWER
case $ANSWER in
[Yy]* ) ANSWER=true ; break ;;
[Nn]* ) ANSWER=false; break ;;
* ) printf 'Please answer yes or no.n' >&2 ;;
esac
done
read "$1" <<EOF
$ANSWER
EOF
}

可以使用命令替换来确保未在全局环境中设置ANSWER

prompt () {
read "$1" <<EOF
$(while :; do
printf "Do you wish to install this program? " >&2
read ANSWER
case $ANSWER in
[Yy]* ) printf true; break ;;
[Nn]* ) printf false; break ;;
* ) printf 'Please answer yes or no.n' >&2 ;;
esac
done
)
EOF
}

相关内容

  • 没有找到相关文章

最新更新