user3227961
user3227961

Reputation: 3

How to redirect / link variables in bash?

I am trying to linking variables in a bash script (three or more). For example:

read -e -p "Enter the 5' restriction enzyme:" RE5

I expect that the user enter "BamHI", and I would like to link the user input (BamHI) to another text string, ("GGATCC"). But I don't know if all user will input it as lower or upper case, so to correct it I use:

RE5l=`echo "$RE5" | tr '[:upper:]' '[:lower:]'`

And set:

bamhi=GGATCC

Now when I enter echo $RE5l I get bamhi , but I would like to get GGATCC

But I don't know how to do it or what is wrong. All suggestions, correction or another way to do it are very welcome. Thank you in advance.

Upvotes: 0

Views: 79

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295403

The answer by @gniourf_gniourf is better practice, and is what you should accept and use. This is being provided only because it's a more direct answer to the question.

Almost everything you're doing is fine:

read -e -p "Enter the 5' restriction enzyme:" RE5
RE5l=${RE5,,}
bamhi=GGATCC

...but if you want to honor indirection in the lookup, use a ! character to do so:

echo "${!RE5l}"

...instead of

echo "${RE5l}"

Upvotes: 0

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

#!/bin/bash

# Better to put your "database" in an associative array:
declare -A database
database[bamhi]=GGATCC

read -rep "Enter the 5' restriction enzyme: " RE5

# Bash has builtin operator for lowercase conversion
RE5l=${RE5,,}

# Now you can retrieve the value from the associative array:
printf 'Output: %s\n' "${database[$RE5l]}"

If you want to check for existence in the database, replace the last two lines with:

# Checking whether data is in database
# If exists, retrieve the value from the associative array
if [[ -z ${database[$RE5l]+1} ]]; then
    echo "Not found"
else
    printf 'Output: %s\n' "${database[$RE5l]}"
fi

Upvotes: 1

Related Questions