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']
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']
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With