-1

Take a look at this simple example:

x="foo bar"
echo ${!x}

It erros: -bash: foo bar: invalid variable name.

I'm writing a script where a positional argument will indicate a "color name" and we use indirect references to fetch the hex code of the color name. I want the script to keep going if the user passes a color name with space in it or generally an invalid color name (which we will default to white).

I also tried this try/catch approach but to no avail:

x="foo bar"
echo ${!x} || echo error

The closes thing I could find was this, but didn't help:

Bash reference variable by string name

8
  • As you are using bash, how about switching to an array? Commented Apr 26, 2024 at 18:35
  • 1
    @Shayan If you MUST use indirection, you could abuse declare for that, e.g. declare -- "${x}" 2>/dev/null || echo error Commented Apr 26, 2024 at 18:48
  • 1
    It certainly was considered -- these names are explicitly illegal by specification. An associative array would avoid the issue -- key names are allowed to have spaces. Commented Apr 26, 2024 at 19:28
  • 1
    BTW, I'd strongly suggest declare -p instead of declare -- -- otherwise too much chance of that user input being something that has side effects when run. Commented Apr 26, 2024 at 19:33
  • 2
    you code snippets mention x='foo bar' while the description mentions processing colors; recommend you rewrite the question to focus on your actual (color) issue: a) show the setup of a couple colors, b) show your code working for a valid color and c) show your code's result with an invalid color (ie, show all stdout/stderr output); net result: provide a minimal reproducible example Commented Apr 26, 2024 at 20:36

1 Answer 1

2

This may be the error handling you need :

test -v "$x" || echo error
Sign up to request clarification or add additional context in comments.

Comments

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.