Friday, March 18, 2022

[SOLVED] bash shell scripting: conditional string concatenation

Issue

I want to conditionally submit a text into another shell script. Meaning I want to replace "WARNING" in case deb=1 with "INFO":

#!/usr/bin/env bash
...
if [[ $abc -lt 98 ]] || [[ $deb -eq 1 ]]
then 
    ./discord.sh --webhook-url=$url --text "WARNING: $abc"
fi

I also want to avoid another complete IF statement. I expect to have something like

deb=1 ? "INFO" : "WARNING"

Does that work? If yes, how would the complete statement look like? "--text ..."

Thank you in advance.


Solution

Can be done with an array index to match a numerical log-level with a name string:

#!/usr/bin/env bash

url=https://example.com/hook

logLevel=(WARNING INFO)

for abc in 97 98; do
  for deb in 0 1; do
    printf 'abc=%d, deb=%d:\n' $abc $deb
    (((i = 1 == deb) || 98 > abc)) &&
      echo ./discord.sh --webhook-url=$url --text "${logLevel[i]}: $abc"
  done
done

Output:

abc=97, deb=0:
./discord.sh --webhook-url=https://example.com/hook --text WARNING: 97
abc=97, deb=1:
./discord.sh --webhook-url=https://example.com/hook --text INFO: 97
abc=98, deb=0:
abc=98, deb=1:
./discord.sh --webhook-url=https://example.com/hook --text INFO: 98


Answered By - Léa Gris
Answer Checked By - Clifford M. (WPSolving Volunteer)