0

Alright, so I'm trying to use a variables value to then use the value of that variable inorder to get the value of that variable.

So, my script takes $1 as a message, and then takes $2 as the color in which to print that out as.

#!/bin/bash

# TAKES $1 as MSG and $2 as COLOR.
export black='echo -e "\E[30;47m"'
export red='echo -e "\E[31;47m"'
export green='echo -e "\E[32;47m"'
export yellow='echo -e "\E[33;47m"'
export blue='echo -e "\E[34;47m"'
export magenta='echo -e "\E[35;47m"'
export cyan='echo -e "\E[36;47m"'
export white='echo -e "\E[37;47m"'

# VARIABLES
export color="$2"              # Set Color
export message="$1"            # Set MSG

# Use $color for what variable to substitute with, so we get the echos.
# Previously tried \$$color to get $whatever_$2_was but it wouldn't get the value.
\$$color

echo "$message"                # Echo Message.
tput sgr0                      # Reset to normal.

It'd be called as:

USAGE: cecho "MESSAGE" color

So, basically the scripts point is to color $message with whatever $2 equals.

Anyidea how to either:

1. Get the value of the variable with the $2 name,

or

2. Better way of writing this script?

1 Answer 1

5

Look up indirection (fourth paragraph of Shell Parameter Expansion):

${!color}

If color=white, this will generate the string from $white, which is what you're after, I think. You could also look up the eval command, but it is generally not as desirable (more dangerous than) the ${!color} notation.

As to better ways to write the script: I'd defer the echo -e until I used the colours, and I wouldn't export the variables unless you're planning to dot (.) or source the script:

black='\E[30;47m'
...
white='\E[37;47m'

...
color="$2"
...

echo -e "${!color}"
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was looking for and Worked amazingly, thanks for the solution and the tips!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.