【问题标题】:Why is bash string comparator only working when given substring? [duplicate]为什么 bash 字符串比较器仅在给定子字符串时才起作用? [复制]
【发布时间】:2021-11-25 03:43:24
【问题描述】:

我正在尝试将 csv 文件中的用户添加到在 CentOS 8 上运行的 bash 脚本中的组中。组名是“Faculty”和“Students”,我将它们强制为小写。以下没有工作。它默认使用“else”子句,即使 $groupName 是“Faculty”(我会在 if 语句之前“回显”)。

    if [ "$groupName" = "Faculty" ]
    then
        goodGroup="faculty"
    else
        goodGroup="student"
    fi

但是,当我给它一个只有大写字母的子字符串时,它就起作用了:

    if [ "${groupName:0:1}" = "F" ]
    then
        goodGroup="faculty"
    else
        goodGroup="student"
    fi

使用第二种方法可以得到我需要的结果,我只是好奇为什么第一段代码不起作用。我在 StackOverflow 上看到的所有答案都说这是比较字符串的语法,所以我看不出我做错了什么。

【问题讨论】:

  • 您的输入是否有 DOS 行尾? stackoverflow.com/questions/39527571/…
  • 请发布declare -p groupName的输出。 The group names are "Faculty" and "Students", which I am forcing them to be lowercase 只是 ${gruopName,,} 然后。
  • set -x,启用跟踪,是你的朋友。

标签: linux string bash


【解决方案1】:

在 bash 中强制变量值小写而无需检查特定值的方法:

#!/usr/bin/env bash

# Using declare to give a variable the lowercase attribute
declare -l groupName1
groupName1=Faculty
printf "%s\n" "$groupName1"

# Using parameter expansion
groupName2=FACULTY
printf "%s\n" "${groupName2,,}" # or "${groupName2@L}"

【讨论】:

  • 如果这个 确实 工作,我们有重复的问题可以结束 - 但我不知道我们在这一点上有信心它会(是我们确定问题不是由 CRLF 而不是 LF 作为行终止符引起的?)
猜你喜欢
  • 2012-01-22
  • 2013-10-20
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-06
  • 2015-08-30
  • 2012-03-02
相关资源
最近更新 更多