hi all,

i am using a unix script to control various pieces of code,
sometime i call this python script,
HOW can i store the result of the python script
INTO an array defined in my unix script ?

thanx

Dani AI

Generated

Short answer: it depends on the shell. As asked, confirm which shell you run; showed a bash loop/awk approach (and correctly warned it can be slow). Below are safer, clearer ways to take Python output and populate a shell array — pick the one that matches your shell and the kind of data (spaces/newlines) you must preserve.

For bash (recommended if you need a real array)

  • Have Python print one item per line.
  • Use readarray / mapfile (Bash 4+):
# Python prints one item per line to stdout
readarray -t items < <(python3 myscript.py)

# access:
echo "${items[0]}"
for item in "${items[@]}"; do
  printf '%s\n' "$item"
done

If items can contain newlines or arbitrary binary, produce NUL-separated output from Python and use NUL-aware readarray:

# Python: write NUL-terminated items (example)
#   sys.stdout.write(item + '\0') for each item

mapfile -d '' -t items < <(python3 myscript.py)

If you only have POSIX / sh (no arrays)

  • Don’t try to emulate large arrays in plain sh. Process the stream line-by-line:
python3 myscript.py | while IFS= read -r line; do
  # process "$line" as it arrives
done

Troubleshooting and tips

  • Preserve whitespace by making Python emit one record per line (or use NULs for full safety). Avoid arr=( $(python...) ) — that will split on IFS and mangle spaces.
  • If the array is empty, confirm Python writes to stdout (not stderr) and check for CRLF (\r) on Windows-produced output.
  • For very large outputs, avoid loading everything into memory; stream/process in Python or in the shell loop.
  • If portability matters, use JSON from Python and parse with jq or let Python produce the final form you need before the shell touches it.

These approaches avoid the per-line subshell/awk overhead hinted at and give predictable behavior for quoting and splitting.

Recommended Answers

All 2 Replies

hi all,

i am using a unix script to control various pieces of code,
sometime i call this python script,
HOW can i store the result of the python script
INTO an array defined in my unix script ?

thanx

What shell are you running?

Here is an example of a bash array. These values are split from a CSV line:

declare -a varray
for aline in `cat $USERFILE`
do
  varray=(`echo $aline | awk '{ split($0, ulist, ","); for(i=1; i<=11; i++) printf ulist[i] " "; }'`)

Note: Doing this in bash is horribly slow & $USERFILE is not /etc/passwd, it is another file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.