Monday, 18 April 2022

Tinkering with arrays in ZSH

Someone had asked: -

if you have a command that returns two values, can you assign each value to a separate variable? For example, I have a command that returns two lines, and I want NAME to be set to the first line and TITLE to the second line. I seem to recall doing this in the past, but I can’t find an example or a note on it.

which made me think about how one might achieve this

I'm using zsh, and looked at dumping the output from a command into an array

I started with the sw_vers command: -

ProductName: macOS
ProductVersion: 12.3.1
BuildVersion: 21E258

and found a way to dump the multiline output into an array: -

array_of_lines=("${(@f)$(sw_vers)}")                                 

and checked each of the elements in the array: -

echo $array_of_lines[1]                                                    

ProductName: macOS

echo $array_of_lines[2]

ProductVersion: 12.3.1

echo $array_of_lines[3]

BuildVersion: 21E258

I also used ${#array_of_lines} to get the size of the array: -

echo ${#array_of_lines}

3

to iterate through the array and dump out each element in turn: -

for ((i = 1; i<=${#array_of_lines}; i++)); do echo $array_of_lines[i]; done

ProductName: macOS
ProductVersion: 12.3.1
BuildVersion: 21E258

Whether this helps, we shall see ....

No comments:

Reminder - installing podman and skopeo on Ubuntu 22.04

This follows on from: - Lest I forget - how to install pip on Ubuntu I had reason to install podman  and skopeo  on an Ubuntu box: - lsb_rel...