Skip to content
Advertisement

How to build a conditional while statement in Bash?

Hello Stackoverflow community,

In order to make my code as less ‘copy-paste-ey’ as possible, I’m trying to come up with a smarter method to make it more compact.

Is there any way to create a ‘conditional while’-statement (if that’s even a thing) in your script without having to repeat everything over again? Basically, I have the same core function, but a different while statement should be fired off depending if a variable is present or not.

See my original script below:

JavaScript

This is my core function, but instead of counting the lenght of $1, I’d like the possibility for the count to be equal to the provided variable $val, but only if it’s provided.

What I’d like to achieve – but doesn’t work due to the syntax:

JavaScript

The only way I manage to achieve is by reusing most of the core, basically a copy-paste action. I’d like to come up with a better method of achieving this:

JavaScript

I believe this example perfectly sums up what I’m trying to achieve. If you can point me towards a direction, I would really appreciate it.

JavaScript

Thank you in advance,

Ivan

Advertisement

Answer

Use the default value operator.

JavaScript

If val is not empty, you’ll use that value. Otherwise, it will use ${#1}.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement