Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Convert the file list into a Bash array. This uses Matt McClure's approach for returning an array from a Bash function: <a href="http://notes-matthewlmcclure.blogspot.com/2009/12/return-array-from-bash-function-v-2.html" rel="nofollow">http://notes-matthewlmcclure.blogspot.com/2009/12/return-array-from-bash-function-v-2.html</a> The result is a way to convert any multi-line input to a Bash array.</p> <pre><code>#!/bin/bash # This is the command where we want to convert the output to an array. # Output is: fileSize fileNameIncludingPath multiLineCommand="find . -mindepth 1 -printf '%s %p\\n'" # This eval converts the multi-line output of multiLineCommand to a # Bash array. To convert stdin, remove: &lt; &lt;(eval "$multiLineCommand" ) eval "declare -a myArray=`( arr=(); while read -r line; do arr[${#arr[@]}]="$line"; done; declare -p arr | sed -e 's/^declare -a arr=//' ) &lt; &lt;(eval "$multiLineCommand" )`" for f in "${myArray[@]}" do echo "Element: $f" done </code></pre> <p>This approach appears to work even when bad characters are present, and is a general way to convert any input to a Bash array. The disadvantage is if the input is long you could exceed Bash's command line size limits, or use up large amounts of memory.</p> <p>Approaches where the loop that is eventually working on the list also have the list piped in have the disadvantage that reading stdin is not easy (such as asking the user for input), and the loop is a new process so you may be wondering why variables you set inside the loop are not available after the loop finishes.</p> <p>I also dislike setting IFS, it can mess up other code.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload