Home > other >  How to create a list and append values in bash script
How to create a list and append values in bash script

Time:11-05

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']

CodePudding user response:

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']

CodePudding user response:

You have a number of issues here, starting from your expected output. The command echo ${arr} suffers from broken quoting and only prints the first element of the array anyway; the output you expect looks like how e.g. Python represents a list, but Bash would simply print the values themselves in whichever format you specify, without any explicit formatting you didn't put there yourself.

To print an array, try

printf '%s\n' "${arr[@]}"

To print an array with explicit formatting around each value, try e.g.

printf "['%s'" "${arr[0]}"
printf ",'%s'" "${arr[@]:1}"
printf ']\n'

Now, to build the array properly in the first place, you have to add to the array, not to the first element.

arr=()
while true;  # not while [ ]
do 
  ........
  arr =('some value')  # use parentheses
done

To add VARIABLE_VALUE= before the output, just ... do that.

printf "VARIABLE_VALUE=['%s'" "${arr[0]}"
printf ",'%s'" "${arr[@]:1}"
printf ']\n'

CodePudding user response:

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"
  •  Tags:  
  • bash
  • Related