144
votes
How to add/remove an element to/from the array in bash?
To add an element to the beginning of an array use.
arr=("new_element" "${arr[@]}")
Generally, you would do.
arr=("new_element1" "new_element2" "..." "new_elementN" "${arr[@]}")
To add an element ...
Community wiki
54
votes
Bash to check if directory exist. If not create with an array
Just use:
mkdir -p -- "${array1[@]}"
That will also create intermediary directory components if need be so your array can also be shortened to only include the leaf directories:
array1=(
/apache/...
40
votes
how to shift array value in bash
To answer the question in the title, you can "shift" an array with the substring/subarray notation. shift itself works with just the positional parameters.
$ a=(a b c d e)
$ a=("${a[@]:...
36
votes
Accepted
What is the difference between $path and $PATH (lowercase versus uppercase) with zsh?
That's a feature of zsh inherited from csh/tcsh.
The $path array variable is tied to the $PATH scalar (string) variable. Any modification on one is reflected in the other.
In zsh (contrary to (t)csh), ...
35
votes
Accepted
How can I create a multidimensional array, or something similar, with bash?
You don't. If you find yourself needing something like a multi-dimensional array, that is a very strong indication that you should be using an actual programming language instead of a shell. Shells ...
32
votes
Bash - reverse an array
Another unconventional approach:
#!/bin/bash
array=(1 2 3 4 5 6 7)
f() { array=("${BASH_ARGV[@]}"); }
shopt -s extdebug
f "${array[@]}"
shopt -u extdebug
echo "${array[@]}"
Output:
7 6 5 4 3 2 1
...
26
votes
Bash - reverse an array
Unconventional approach (all not pure bash):
if all elements in an array are just one characters (like in the question) you can use rev:
echo "${array[@]}" | rev
otherwise if none of the ...
25
votes
Accepted
What type of operation is /#/- in "${my_array[@]/#/-}"?
This is an instance of pattern replacement in shell parameter expansion: ${parameter/pattern/replacement} expands ${parameter}, replacing the first instance of pattern with replacement. In the context ...
25
votes
Accepted
How to iterate over array indices in zsh?
zsh arrays are normal arrays like those of most other shells and languages, they are not like in ksh/bash associative arrays with keys limited to positive integers (aka sparse arrays). zsh has a ...
23
votes
Accepted
jq - add objects from file into json array
jq has a flag for feeding actual JSON contents with its --argjson flag. What you need to do is, store the content of the first JSON file in a variable in jq's context and update it in the second JSON
...
22
votes
Accepted
How do I shift a bash array at some index in the middle?
unset removes an element. It doesn't renumber the remaining elements.
We can use declare -p to see exactly what happens to numbers:
$ unset "numbers[i]"
$ declare -p numbers
declare -a ...
20
votes
Accepted
Bash - reverse an array
I have answered the question as written, and this code reverses the array. (Printing the elements in reverse order without reversing the array is just a for loop counting down from the last element to ...
19
votes
Accepted
How to port to bash-style arrays to ash?
Before arrays were in bash, ksh, and other shells, the usual method was to pick a delimiter that wasn't in any of the elements (or one that was uncommon to minimise any required escaping), and iterate ...
19
votes
Accepted
Possible bug in Bash?: foo() { echo "${var[0]}"; }; var=(bar baz) foo
Generally calling:
var=value cmd
where cmd is a function is not portable.
With bash, that only works for scalar variables (and with x=(...) parsed as an array but assigned as a scalar) and there are ...
19
votes
Accepted
Remove all empty strings from an array in Zsh
There is the parameter expansion ${name:#pattern} (pattern can be empty), which will work on elements of an array:
a=('a' '' 'b' 'c')
echo ${(j./.)a:#}
# If the expansion is in double quotes, add the ...
18
votes
Accepted
splitting a line into array in bash with tab as delimiter
The array assignment tmp=(${line///}) splits the value on whatever characters IFS contains, which by default includes tabs, and spaces and newlines. (I don't see what the empty substitution does.) To ...
16
votes
Bash - reverse an array
If you actually want the reverse in another array:
reverse() {
# first argument is the array to reverse
# second is the output array
declare -n arr="$1" rev="$2"
for i in "${arr[@]}"
...
16
votes
Accepted
Referencing array elements by strings, and initialising arrays in awk
Array indexes are either integers or quoted strings in awk. What you are doing here are using variables that have not yet been initialised. Their values are therefore empty.
You get the latest ...
16
votes
Accepted
BASH script: How to assign each line of command output to values in an array?
Using readarray in the bash shell, and GNU sed:
readarray -t my_array < <( my_command | sed '1~2d' )
The built-in readarray reads the lines into an array. The lines are read from a process ...
16
votes
Accepted
Unary test -v on an array element
In bash, you can do:
[ -v 'a[2]' ]
or
[[ -v a[2] ]]
To test whether the array element of index 2, or the associative array element of key "2" is set (even if that's to an empty string), ...
15
votes
Accepted
Compact way to get tab-separated fields into variables
Yes:
while read -r width height size thedate thetime; do
# use variables here
done <file
This will read from standard input and split the data on blanks (spaces or tabs). The last variable ...
15
votes
Number of elements/words in a shell array variable
To print the number of elements in an array variable in various shells with array support:
csh/tcsh/zsh/rc/es/akanga: echo $#array
ksh¹/bash¹/zsh: echo "${#array[@]}"
fish: count $array
yash: echo "${...
15
votes
jq - add objects from file into json array
This is the exact case that the input function is for:
input and inputs [...] read from the same sources (e.g., stdin, files named on the command-line) as jq itself. These two builtins, and jq’s own ...
15
votes
Accepted
zsh: for loop over newline-delimited entries
To split on newline in zsh, you use the f parameter expansion flag (f for line feed) which is short for ps:\n::
for num (${(f)numholds}) print -r New item: $num
You could also use $IFS-splitting ...
14
votes
Accepted
How do I capture a MySQL result set in a bash array?
With the --batch option, mysql should output the result one record on a line, and columns separated by tabs. You can read the lines to an array with Bash's mapfile and process substitution, or command ...
14
votes
Accepted
Split zsh array from subshell by linebreak
The native splitting operator (beside the Bourne-like $IFS word splitting which is done on unquoted command substitutions) is with the s parameter expansion flag:
array=( ${(ps:\n:)"$(cmd)"} ...
14
votes
Accepted
Does `declare -a A` create an empty array `A` in Bash?
That depends whether the corresponding variable has already been declared in the current scope (top-level aka global or current function) before.
If it hasn't been declared in the current scope (and ...
14
votes
Accepted
In bash, how do I get the index of the last element of an array without a loop
In case of an array which is not sparse, last index is number of elements - 1:
i=$(( ${#a[@]} - 1 ))
To include the case of a sparse array, you can create the array of indexes and get the last one:
a=...
13
votes
Bash: slice of positional parameters
More array slicing examples in bash
In place of using some_array_variable in your code (argv in your case), simply use @ in that variable name's place. The symbol @ represents the input argument array,...
13
votes
Accepted
How do I join an array of strings where each string has spaces?
My modified version of your script:
#!bin/bash
my_array=("Some string" "Another string")
my_join() {
[ "$#" -ge 1 ] || return 1
local IFS="$1"
shift
printf '%s\n' "$*"
}
my_join , "${my_array[...
Only top scored, non community-wiki answers of a minimum length are eligible
Related Tags
array × 641bash × 424
shell-script × 178
shell × 60
awk × 53
zsh × 46
variable × 41
string × 27
text-processing × 26
linux × 24
scripting × 24
bash-array × 23
for × 21
function × 18
grep × 16
associative-array × 16
csv × 15
ksh × 15
arguments × 15
quoting × 13
sort × 13
sed × 12
jq × 11
parameter × 11
files × 10