linux – for loop with bash from variable – Education Career Blog

Lets say I have a variable which has values :

#!/bin/sh
    MYVARIABLE="first,second,third"

    for vars in MYVARIABLE
    do 
    echo $vars
    done

this above doesn’t work what I want but it looks fine, this should print first second third without , I wan’t it to be printed without , any sugestions?

,

Use IFS (the input field separator), eg.

#!/bin/sh
MYVARIABLE="first,second,third"
IFS=","

for vars in $MYVARIABLE
do 
  echo $vars
done

,

try

MYVARIABLE="first,second,third"

for vars in $(echo $MYVARIABLE | tr "," "\n")
do 
  echo $vars
done

Or if you use IFS, don’t forget to set IFS back to the original one when done

MYVARIABLE="first,second,third"

OIFS=$IFS
IFS=","
for vars in $MYVARIABLE
do 
    echo $vars
done
IFS=$OIFS

,

MYVARIABLE="first,second,third"
IFS=","
set -- $MYVARIABLE
for i in ${@}; do echo $i; done

# you can also use an array in cases where you want to use the values later on
array=([email protected])
for i in ${[email protected]}; do echo ${arrayi}; done

,

Not sure what you want to do with the content of MYVARIABLE, or how do you fill it, but a very good option to deal with CSV data is to use awk.

If you have just this variable to be printed:

echo $MYVARIABLE | awk 'BEGIN { RS="," }{ print $0 }'

If you have a CSV file and need to perform calculation/transformation on the data then you should let the awk to fetch the file, using someting like:

awk 'BEGIN { FS="," ; OFS="\n" } { print $1,$2,$3 }' filename.csv
(this is just an ideia, not really related to your question)

Leave a Comment