Search code examples
loopsfor-loopescapingkshdouble-quotes

KSH: Loop through a double quoted comma separated variable


Using KSH. I have a variable that contains strings enclosed in double quotes and separated by commas, I would like to loop through these strings, I do not want to recognise commas in the double quotes as separators.

I've tried setting IFS to IFS="\",\"" and IFS="," but it still recognises the comma inside the double quotes.

Simplified:

errorStrings="Some error","Another error","This, error"
oldIFS=$IFS
IFS=","
for error in $errorStrings;do
  echo "Checking for $error"
  #grep "$error" file >/dev/null 2>&1 && echo "$error found"
  continue
done
IFS=$oldIFS


Actual:
Checking for Some error
Checking for Another error
Checking for This
Checking for  error

Expected:
Checking for Some error
Checking for Another error
Checking for This, error

Solution

  • The first problem is that the errorStrings is not what you expect. Try

    echo "e=[${errorStrings}]"
    

    When you want the double quotes inside your string, use

    errorStrings='"Some error","Another error","This, error"'
    

    Your script will work better when you quote $errorStrings in the for-loop.

    oldIFS=$IFS
    IFS=","
    for error in "$errorStrings";do
      echo "Checking for $error"
      #grep "$error" file >/dev/null 2>&1 && echo "$error found"
      continue
    done
    IFS=$oldIFS
    

    This loop still has to be modified for deleting the quotes. Perhaps this is a good moment for using an array:

    errorStrings=("Some error" "Another error" "This, error")
    for error in "${errorStrings[@]}";do
      echo "Checking for $error"
      #grep "$error" file >/dev/null 2>&1 && echo "$error found"
      continue
    done
    

    I am not sure what options you have in your environment, perhaps this will work too:

    errorStrings='"Some error","Another error","This, error"'
    
    echo "${errorStrings}" | sed 's/","/"\n"/g' | while read error; do
       echo "Checking for $error"
    done