Save the Output in a Shell Script Array

I wanted to do some shell processing on the contents of a directory. To do this I needed to put the contents of the directory in an array. Fortunately this is not difficult with bash.

  1. First capture the output.

    ls_output=$(ls /images)

  2. Next declare an array and reference the output with this array.

    declare -a img_files
    img_files=($ls_output)

  3. Now you can access the array directly or loop through it.

    echo ${img_files[0]}
    for img_file in ${img_files[@]}
    do
      ...
    done

Thanks O’Reilly’s Bash Cookbook.

Leave a Reply

Your email address will not be published. Required fields are marked *