Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list and append values in bash script

Tags:

bash

I'm having a while loop and need to append the outcome of the loop to the list(like in python) in bash script. How to do that. I created an array but there are no commas in it. It has only space but I want commas so that I can use them in the .env file

arr=()
while [ ]
do 
  ........
  ........
  ........
  val='some value'
  arr+=$val
done

echo ${arr}

output:

('some value1' 'some value2' 'some value3')

Expected Outcome:

['some value1','some value2','some value3']
like image 671
swarna Avatar asked Nov 18 '25 04:11

swarna


2 Answers

Here one idea/approach.

#!/usr/bin/env bash

arr=()

while IFS= read -r val; do
  arr+=("'$val'")
done < <(printf '%s\n' 'foo bar' 'baz more' 'qux lux')

(IFS=,; printf '[%s]' "${arr[*]}")

Output

['foo bar','baz more','qux lux']
like image 158
Jetchisel Avatar answered Nov 20 '25 18:11

Jetchisel


Here is a solution using echo :

arr=()
while [ ... ]
do 
  ........
  ........
  ........
  val='some value'
  arr+=("$val")              # () and "" added
done

# print each value protected by "" and separated by ,
first=true
echo -n "arr values = [ "
for v in "${arr[@]}" ; do
    if $first ; then first=false ; else echo -n ", " ; fi
    echo -n "\"$v\""
done
echo " ]"

# Another way to print arr values
declare -p arr

To write the array values in a python file, you may try this :

dest="somefile.py"
{
    first=true
    echo -n "arr = [ "
    for v in "${arr[@]}" ; do
        if $first ; then first=false ; else echo -n ", " ; fi
        echo -n "\"$v\""
    done
    echo " ]"
} >| "$dest"

Note that it is fragile, it won't work if v contains ". A solution is given here with operator @Q (search Parameter transformation" in man bash):

dest="somefile.py"
{
    first=true
    echo -n "arr = [ "
    for v in "${arr[@]}" ; do
        if $first ; then first=false ; else echo -n ", " ; fi
        echo -n "${v@Q}"    # operator @Q
    done
    echo " ]"
} >| "$dest"
like image 40
Edouard Thiel Avatar answered Nov 20 '25 19:11

Edouard Thiel