Get the App
SLTechnology News&Howtos  ›  Development  › 

How to understand bash readarray

Shulou Source: shulou.com Published: 2022-06-03 05:41:17 09月10日 Update

This article focuses on "how to understand bash readarray". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to understand bash readarray.

§0x01 Origin

There are the following requirements in the work, to parse the contents of a file, but the file is in json format, I do not want to use jq. The rows that meet the requirements are filtered out by grep and then processed in the for loop. And then found that this can not be achieved.

Lines=$ (grep xxxx / path/to/file.json) for line in ${lines}; do echo ${line} done

The content of the grep output becomes one line. Comparing the running environment with ubuntu, it is found that the content of lines is different. In the runtime, it is one line (the newline character disappears), and in ubuntu it is multiple lines. After changing the sed, it is confirmed that it is the problem with the bash implementation. You can't update the version of bash in the runtime environment, so you have to consider other implementations.

§0x02 readarry

After looking up the data, we found that readarray, a built-in function of bash, can implement this requirement, and it also has an individual named mapfile. Personally, I think readarray is easier to understand. Its actual way is as follows:

# declare that it is a list delcare-a linesreadarray-t lines <

Tags: File content form input command standard environment run one line between mode process requirements learning output different no practical deeper two Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Shulou Tech Info Xiaomi Apple macOS