Creating an array from a text file in Bash

前端 未结 6 1881
小鲜肉
小鲜肉 2020-11-22 10:25

A script takes a URL, parses it for the required fields, and redirects its output to be saved in a file, file.txt. The output is saved on a new line each time a fie

6条回答
  •  旧巷少年郎
    2020-11-22 11:13

    Use mapfile or read -a

    Always check your code using shellcheck. It will often give you the correct answer. In this case SC2207 covers reading a file that either has space separated or newline separated values into an array.

    Don't do this

    array=( $(mycommand) )
    

    Files with values separated by newlines

    mapfile -t array < <(mycommand)
    

    Files with values separated by spaces

    IFS=" " read -r -a array <<< "$(mycommand)"
    

    The shellcheck page will give you the rationale why this is considered best practice.

提交回复
热议问题