0

In my bash script, I want to take the response and make it lower case to anticipate and avoid errors.

However, when I convert to my response to lower case, I can't seem to store that change in the variable.

How can I update the case of an input string and store such that I can compare it later?

#!/usr/bin/env bash -e


echo "To reset cluster on existing EKS cluster, we must first destroy the existing cluster."
read -p "Do you want to auto-approve the terraform destroy (y/n): " response

response="$response" | tr '[:upper:]' '[:lower:]'

echo $response

if [ $response = 'y' ]; then
    echo "Destroy is auto-approved."
else 
    echo "Destroy is not auto-approved"
fi
3
  • 1
    Use command substitution: $() to store the output of a command inside a variable , : response=$(echo "$response" | tr '[:upper:]' '[:lower:]') Commented Jun 7, 2022 at 6:08
  • You can also extend your condition if [ "$response" = "y" -o "$response" = "Y" ] ... Commented Jun 7, 2022 at 7:20
  • 1
    Another way: before the read, declare -l response will automatically lower case it whenever the variable is assigned to. Commented Jun 7, 2022 at 13:18

1 Answer 1

2

No need to create a child process for this task. Simply do a

response=${response,,?}

The ,, operator converts each character matched by the glob pattern ? to upper case.

UPDATE: As Shawn pointed out, and also according to the man-page (which says: If pattern is omitted, it is treated like a ?, which matches every character), you can omit the question mark and just do a:

response=${response,,}
Sign up to request clarification or add additional context in comments.

2 Comments

You don't even need the ?. ${response@L} is another way on recent versions.
Interesting point! While the @L does not work on my bash (perhaps too old), I see that I can indeed drop the ?.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.