【问题标题】:POSIX equivalent to prinf -vPOSIX 等价于 printf -v
【发布时间】:2021-09-23 14:23:33
【问题描述】:

我有一个脚本可以用另一个值替换一个变量,具体取决于输入:

#!/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 是bashism。我该如何修改这个程序?我可以使用等效的功能吗?谢谢!

【问题讨论】:

  • 仅供参考:read -p 也是一种 bashism。 printf "Do you ...? " >&2; read ANSWER.

标签: bash shell sh posix


【解决方案1】:

read本身可以设置名称在$1中的变量。但是,您仍然需要先read ANSWER,以便您可以检查响应。完成后,您可以使用 read 和 here-document 将 $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
}

【讨论】:

    猜你喜欢
    • 2016-12-12
    • 2012-08-23
    • 2010-10-11
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多