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:
messenger() { msg1=$1 count=0 echo " " while [[ $count -ne ${#1} ]] do echo -n "*" ((count += 1)) done echo -e "n$1" while [[ $count -ne 0 ]] do echo -n "*" ((count -= 1)) done echo -e "n" }
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:
messenger() { msg1=$1 val=$2 count=0 echo " " if [[ -z $val ]] then while [[ $count -ne ${#1} ]] else while [[ $count -ne $val ]] fi do echo -n "*" ((count += 1)) done echo -e "n$1" while [[ $count -ne 0 ]] do echo -n "*" ((count -= 1)) done echo -e "n" }
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:
messenger() { msg1=$1 val=$2 count=0 echo " " if [[ -z $val ]] then while [[ $count -ne ${#1} ]] do echo -n "*" ((count += 1)) done echo -e "n$1" while [[ $count -ne 0 ]] do echo -n "*" ((count -= 1)) done echo -e "n" else while [[ $count -ne $val ]] do echo -n "*" ((count += 1)) done echo -e "n$1" while [[ $count -ne 0 ]] do echo -n "*" ((count -= 1)) done echo -e "n" fi }
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.
$ bash --version GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
Thank you in advance,
Ivan
Advertisement
Answer
Use the default value operator.
while [[ $count -ne ${val:-${#1}} ]]
If val
is not empty, you’ll use that value. Otherwise, it will use ${#1}
.