Contents
How does the associative array printing in Bash work?
It is well explained in the Bash Reference Manual → 3.5.3 Shell Parameter Expansion: Produces a possibly-quoted version of the value of parameter, except that it prints the values of indexed and associative arrays as a sequence of quoted key-value pairs (see Arrays).
Can you print an array in reverse order?
(Printing the elements in reverse order without reversing the array is just a for loop counting down from the last element to zero.) This is a standard “swap first and last” algorithm.
Is there a way to reverse an array in Bash?
To reverse an arbitrary array (which may contain any number of elements with any values): With bash 4.4+, given that bash variables can’t contain NUL bytes anyway, you can use GNU tac -s ” on the elements printed as NUL delimited records: POSIXly, to reverse the POSIX shell array ( $@, made of $1, $2 …):
Which is better zsh or Bash associative array?
Also note that zsh uses a much more sensible and useful array definition syntax than ksh93 ‘s (copied by bash ): (you can’t easily copy a hash without a loop with bash, and note that bash currently doesn’t support empty keys or key/values with NUL bytes).
How to flatten JSON into Bash associative array?
Array indexes are not represented in a form that can be used to query the original JSON. But what I really want is output formatted so that it could be sourced directly in a Bash program (implying the array name is passed to jq as an argument): I’m looking to have the more human-readable syntax above as opposed to the more general:
How to create an array from a text file in Bash?
If you have an older version of Bash, you can use a loop to read the file into an array: arr= () while IFS= read -r line; do arr+= (“$line”) done < file In case the file has an incomplete (missing newline) last line, you could use this alternative: arr= () while IFS= read -r line || [ [ “$line” ]]; do arr+= (“$line”) done < file
How to loop over lines of a file in Bash?
The error is using for — the idiomatic way to loop over lines of a file is: See BashFAQ/005 for more details. mapfile and readarray (which are synonymous) are available in Bash version 4 and above. If you have an older version of Bash, you can use a loop to read the file into an array: