Hot answers tagged

163 votes
Accepted

how to count the length of an array defined in bash?

You can access the array indices using ${!array[@]} and the length of the array using ${#array[@]}, e.g. : #!/bin/bash array=( item1 item2 item3 ) for index in ${!array[@]}; do echo $index/${#...
user avatar
  • 72.1k
150 votes
Accepted

Is there a way of reading the last element of an array with bash?

As of bash 4.2, you can just use a negative index ${myarray[-1]} to get the last element. You can do the same thing for the second-last, and so on; in Bash: If the subscript used to reference an ...
user avatar
128 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 ...
user avatar
  • 38.2k
94 votes
Accepted

`Syntax error: "(" unexpected` when creating an array

When you use ./scriptname.sh it executes with /bin/bash as in the first line with #!. But when you use sh scriptname.sh it executes sh, not bash. The sh shell has no syntax to create arrays, but Bash ...
user avatar
62 votes
Accepted

Arrays in Unix Bourne Shell

/bin/sh is hardly ever a Bourne shell on any systems nowadays (even Solaris which was one of the last major system to include it has now switched to a POSIX sh for its /bin/sh in Solaris 11). /bin/sh ...
user avatar
58 votes

Is there a way of reading the last element of an array with bash?

Modern bash (v4.1 or better) You can read the last element at index -1: $ a=(a b c d e f) $ echo ${a[-1]} f Support for accessing numerically-indexed arrays from the end using negative indexes ...
user avatar
  • 69.1k
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/...
user avatar
42 votes
Accepted

Is there a reason why the first element of a Zsh array is indexed by 1 instead of 0?

Virtually all shell arrays (Bourne, csh, tcsh, fish, rc, es, yash) start at 1. ksh is the only exception that I know (bash just copied ksh). Most interpreted languages at the time (early 90s): awk, ...
user avatar
40 votes

sh + how to use array in sh script in order to print all values in array

Little late, but I don't see the ideal sh answer here so I'll chime in. If you don't need subscripting, then sh effectively does support arrays. It just supports them as space separated strings. You ...
user avatar
  • 641
37 votes
Accepted

Delete an array in awk

The syntax delete array is not in current versions in POSIX, but it is supported by virtually all existing implementations (including the original awk, GNU, mawk, and BusyBox). It will be added in a ...
user avatar
30 votes
Accepted

What is the difference between [@] and [*] when referencing bash array values?

The difference is subtle; "${LIST[*]}" (like "$*") creates one argument, while "${LIST[@]}" (like "$@") will expand each item into separate arguments, so: LIST=(...
user avatar
  • 8,456
29 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[@]:...
user avatar
  • 114k
28 votes
Accepted

How do I test if an item is in a bash array?

Use a different kind of array: rather than an integer-indexed array, use an associative array, so the key (index) is what you will be checking for. bash-4.0 or later is required for this. declare -A ...
user avatar
  • 9,241
28 votes
Accepted

parse one field from an JSON array into bash array

Using jq : $ cat json [ { "item1": "value1", "item2": "value2", "sub items": [ { "subitem": "subvalue" } ] }, { "item1": "value1_2", "item2": "...
user avatar
27 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)...
user avatar
26 votes
Accepted

Provide two arguments to one option using getopts

You cannot pass two arguments with single option using getopts. I recommend the following alternatives: Put quotes around multiple arguments In this case getopts will treat them as one argument, ...
user avatar
  • 43.1k
26 votes
Accepted

BASH associative array printing

I think you're asking two different things there. Is there a way to make bash print this info without the loop? Yes, but they are not as good as just using the loop. Is there a cleaner way to ...
user avatar
  • 114k
25 votes
Accepted

Single parenthesis in bash variable assignment

In your case parenthesis () are used as array definition, for example a=(one two three) # array definition echo "${a}" # print first element of array a echo "${a[0]}" # print first ...
user avatar
  • 43.1k
25 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 ...
user avatar
  • 11.2k
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 ...
user avatar
24 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: printf '%s\n' "${array[@...
user avatar
  • 43.1k
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 numbers=([0]=...
user avatar
  • 69.1k
21 votes

Is there a way of reading the last element of an array with bash?

bash array assignment, reference, unsetting with negative index were only added in bash 4.3. With older version of bash, you can use expression in index array[${#array[@]-1}] Another way, also work ...
user avatar
  • 143k
19 votes
Accepted

Print all words on lines of a file in reverse order

All examples presented below work for general case where there's an arbitrary number of words on the line. The essential idea is the same everywhere - we have to read the file line by line and print ...
user avatar
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 ...
user avatar
19 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 ...
user avatar
  • 88.8k
18 votes

How do I test if an item is in a bash array?

The straightforward way is to iterate with a loop : var=ab for item in "${array[@]}"; do [[ $var == "$item" ]] && echo "$var present in the array" done
user avatar
18 votes

Append (alter) each array element via parameter expansion (i.e. without printf)?

Use $^array. It turns the array into a sort of brace expansion of the array. As in when a=(foo bar baz), $^a would be a bit like {foo,bar,baz}. $ a=(foo bar baz) $ echo prefix${^a}suffix ...
user avatar
17 votes
Accepted

Go from a String to an Array of "words" in Bash

VotePedro="Vote for Pedro" votePedroArray=(${VotePedro}) Explanation: Arrays are usually declared using parentheses. For example votePedroArray=("Vote" "For" "Pedro") would give you an array of ...
user avatar
  • 580
16 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 ...
user avatar
  • 114k

Only top scored, non community-wiki answers of a minimum length are eligible