0

I am trying to add users from a csv file to a group in a bash script running on CentOS 8. The group names are "Faculty" and "Students", which I am forcing them to be lowercase. The following did not work. It defaults to the "else" clause, even when $groupName is "Faculty" (I would "echo" before the if statement).

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

However, it worked when I gave it a substring of only the capital letter:

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

Using the second method gives me the outcome I need, I am just curious why the first bit of code did NOT work. All the answers I've seen on StackOverflow say that's the syntax for comparing strings, so I can't see what I'm doing wrong.

  • 2
    Does your input have DOS line endings? https://stackoverflow.com/questions/39527571/are-shell-scripts-sensitive-to-encoding-and-line-endings – tripleee Oct 04 '21 at 18:22
  • Please post the output of `declare -p groupName`. `The group names are "Faculty" and "Students", which I am forcing them to be lowercase` just `${gruopName,,}` then. – KamilCuk Oct 04 '21 at 18:23
  • 1
    `set -x`, to enable tracing, is your friend. – Charles Duffy Oct 04 '21 at 18:42

1 Answers1

0

Ways to force a variables value to lowercase in bash without having to check for specific values:

#!/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}"
Shawn
  • 47,241
  • 3
  • 26
  • 60
  • If this _does_ work, we have duplicates the question can be closed with -- but I don't know that we're confident at this point that it will (are we sure the problem isn't caused by CRLFs instead of LFs as line terminators?) – Charles Duffy Oct 04 '21 at 19:08