【问题标题】:Writing a portable and generic confirm function in bash - can you improve it?在 bash 中编写一个可移植的通用确认函数 - 你能改进它吗?
【发布时间】:2019-07-10 10:04:09
【问题描述】:

我正在尝试为 bash 编写一个通用的“确认”函数,该函数要求输入,并基于 [Yy] 或 [Nn] 的默认值向调用函数返回 0 或 1。

有效,但是:

  • 如果我稍后再读,我发现代码有点难以理解(特别是 must_match 处理逻辑)
  • 我不确定我是否使用了不可移植的函数返回值的任何特性(SO 上有很多关于使用局部变量、eval 和其他机制处理返回值的线程。作为另一个示例,我发现即使在今天 - 2019 年 2 月,OSX bash 也不支持 out ${VAR,,} 将字符串转换为小写)

您能否建议这是否是一个好方法和/或我可以如何改进它:

我的功能:

confirm() {
    display_str=$1
    default_ans=$2
    if [[ $default_ans == 'y/N' ]]
    then
        must_match='yY'
    else
       must_match='nN'
    fi
    read -p "${display_str} [${default_ans}]:" ans
    if [[ $ans == [$must_match] ]]
    then
        [[ $must_match == 'yY' ]] && return 0 || return 1
    else
        [[ $must_match == 'yY' ]] && return 1 || return 0
    fi

}

我如何使用它:

confirm 'Install Server' 'y/N'  && install_es  || echo 'Skipping server install'
confirm 'Install hooks' 'Y/n'  && install_hooks  || echo 'Skipping machine learning hooks install'

可移植性:非正式地使用该术语,应该适用于流行的 Linux 发行版,例如,过去 5 年。换句话说,尽可能为 linux 系统提供便携性。

(我知道 other 关于确认函数的线程,但它们似乎只处理 Y/n)

【问题讨论】:

  • 您必须定义“便携”的含义。通常,这意味着它符合 POSIX 标准。您似乎的意思是它应该在 bash 3.2 或更高版本中工作。
  • @chepner 谢谢 - 添加说明
  • 请注意,几乎所有最新的 Linux 发行版都将附带bash 4 或更高版本,因此支持${var,,}(不是你需要它)。出于许可原因,macOS 不会也永远不可能发布晚于 3.2 的版本。 (如果您的目标机器在您的控制之下,您可以随意安装更新的版本。)

标签: bash


【解决方案1】:

confirm 的退出状态只是最后执行的命令的退出状态。这意味着所有你需要做的是以[[ $ans == [$must_match] ]]结尾;不管must_match 是什么,如果$ans 匹配,则返回0,否则返回1。

在样式注释中,我会将must_match 设置为模式本身,而不是模式中将出现的字符。

confirm() {
    display_str=$1
    default_ans=$2
    if [[ $default_ans == 'y/N' ]]
    then
       must_match='[yY]'
    else
       must_match='[nN]'
    fi
    read -p "${display_str} [${default_ans}]:" ans
    [[ $ans == $must_match ]]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多