How can I set a default value for a variable and convert it to uppercase in one line?

0
10
Asked By CuriousCoder42 On

I'm looking for a way to assign a default value to a variable while also converting that value to uppercase, all in one line. I tried using this command that I found: `VAR=${VAR^^:-DEFAULT_VALUE}`, but it doesn't seem to work in my bash script or in the console. I am using bash version 5.x. Any tips on how I can achieve this? Thanks!

3 Answers

Answered By SyntaxSavvy On

It sounds like you're trying to achieve two things: set a default value and then convert it to uppercase. This can be done in bash with something like: `parameter=${parameter-default}; parameter=${parameter^^}`. This way, if `parameter` is unset, it gets assigned the default, and then it’s converted to uppercase. Just make sure you’re handling unassigned variables correctly!

UppercaseNinja -

Can it be done in 1 line? I can easily do it in more than 1 using the old fashioned tr command.

HelpfulHarry -

Thanks for clarifying! I didn’t know about using `:-` to set defaults. This might help with a bug I've been dealing with!

Answered By OneLinerFan On

Just so you know, you can’t handle more than one manipulation in a single parameter expansion in bash, so be careful with that.

Answered By PipeDreamer On

If using pipes is an option, you might try something like this: `VAR=

InputEnthusiast -

I think you might be missing the VAR part; the DEFAULT_VALUE is just a fallback.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.