How to pass strings with newlines from function to array?

一笑奈何 提交于 2020-06-28 05:44:52

问题


Using Bash I am extracting multiple strings from a binary file. Those strings are filenames, so only NUL and slash can not appear. I use a function that outputs those filenames to an array. I know, I can use IFS separator newline to get filenames with spaces. I hope it is possible to separate functions multiline strings with NUL to save in array, so any *nix legal filename can be worked with. If I set IFS to '' or '\0' I get some numbers instead of names. Not sure why, and maybe I have overseen something pretty basic :) How do I achieve getting all possible filename strings including not just spaces, but newlines and other characters/byte values as well?

Here is my simplified example.

#! /bin/bash
binaryFile=$1

getBinaryList () {
    fileNameAddresses=( 123 456 789 )           #Just a mock example for simplicity
    for currAddr in "${fileNameAddresses[@]}"
    do
        fileNameStart=$((currAddr))             #Just a mock example for simplicity
        fileNameLength=48                       #Just a mock example for simplicity
        currFileName=$( dd status=none bs=1 skip=$fileNameStart count=$fileNameLength if=$binaryFile )
    printf "%s\n" "$currFileName"
    done
}

IFS=$'\n'
allFileNames=($(getBinaryList $binaryFile))

echo ${#allFileNames[@]}
printf "%s\n" "${allFileNames[@]}"

回答1:


Your idea is right, but with a couple of slight modifications you can achieve what you are looking for. In the getBinaryList() function instead of using printf() emitting output with newline formatting, use a NULL byte separator, i.e.

printf "%s\0" "$currFileName"

and now instead of modifying IFS to newline and slurping the result into an array. Use a command like mapfile which puts the results directly into array. The command provides an option to delimit results on the NULL byte with -d '' and to store in array specified by -t. So your result can look like

mapfile -t -d '' allFileNames < <(getBinaryList "$binaryFile")


来源:https://stackoverflow.com/questions/61366223/how-to-pass-strings-with-newlines-from-function-to-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!