Questions tagged [array]

A array is the simplest data-structure for storing items in continuously memory

Filter by
Sorted by
Tagged with
29
votes
4answers
38k views

Arrays in Unix Bourne Shell

I am trying to use arrays in Bourne shell (/bin/sh). I found that the way to initialize array elements is: arr=(1 2 3) But it is encountering an error: syntax error at line 8: `arr=' unexpected ...
9
votes
1answer
26k views

Provide two arguments to one option using getopts

In below code when I give option r then getopts requires one arguments: while getopts ":hr::l:" opt; do case $opt in r ) echo "Run Numbers - argument = $OPTARG " ;; l ) echo "...
29
votes
2answers
7k views

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

From my experience with modern programming and scripting languages, I believe most programmers are generally accustomed to referring to the first element of an array by 0 as index. Are there any ...
15
votes
5answers
72k views

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

Help for a simple script #!/bin/bash array1=( prova1 prova2 slack64 ) a="slack64" b="ab" if [ $a = $b ] then echo "$a = $b : a is equal to b" else echo "$a = $b: a is not equal to b" ...
9
votes
4answers
5k views

Indirect return of all elements in an array

The Bash man page describes use of ${!a} to return the contents of the variable whose name is the contents of a (a level of indirection). I'd like to know how to return all elements in an array using ...
8
votes
5answers
11k views

How to create an array of unique elements from a string/array in bash?

If I have a string "1 2 3 2 1" - or an array [1,2,3,2,1] - how can I select the unique values, i.e. "1 2 3 2 1" produces "1 2 3" or [1,2,3,2,1] produces [1,2,3] Similar to uniq but uniq seems to ...
0
votes
1answer
2k views

typeset -A is giving error in script

I was using associative arrays in my script, hence I used to declare them by the typeset -A <array_name> command, and it worked fine in the bash prompt But when I use it in my script, I get ...
2
votes
4answers
3k views

bash array with variable in the name

I'll appreciate your help with the following issue: I'm trying to set an array which contains a variable as part of the array name, example: Arr_$COUNTER (where $COUNTER is changed based on a loop ...
12
votes
5answers
16k views

Intersection of two arrays in BASH

I have two arrays like this: A=(vol-175a3b54 vol-382c477b vol-8c027acf vol-93d6fed0 vol-71600106 vol-79f7970e vol-e3d6a894 vol-d9d6a8ae vol-8dbbc2fa vol-98c2bbef vol-ae7ed9e3 vol-5540e618 vol-...
18
votes
1answer
13k views

Delete an array in awk

In awk, I can clear an array with a loop, making it an empty array, which is equivalent to deleting it. for (key in array) delete array[key]; Is there a simpler way? Can I completely delete an array,...
13
votes
4answers
33k views

Bash script wait for processes and get return code

I am trying to create a script which will start many background command. For each background command I need to get the return code. I have been trying the following script : #!/bin/bash set -x pid=(...
15
votes
1answer
8k views

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

This Bash guide says: If the index number is @ or *, all members of an array are referenced. When I do this: LIST=(1 2 3) for i in "${LIST[@]}"; do echo "example.$i " done Gives: example.1 ...
11
votes
2answers
1k views

Test for array support by shell

Is there a concise way of testing for array support by the local Bourne-like shell at command line ? This is always possible: $ arr=(0 1 2 3);if [ "${arr[2]}" != 2 ];then echo "No array support";fi ...
8
votes
3answers
16k views

What is the most correct way to pass an array to a function?

Consider I have a very large array $large_list, is there a way to write a function that will take the array as an argument? For example: echo_idx_array () { arr="$1" idx="$2" echo "${arr[...
6
votes
1answer
3k views

gnuplot shell variable substitution and arrays

I need to use shell variables in my gnuplot commands, for which I'm using the here document style. I also need to use loops inside the gnuplot code. Both these things are working. Now -- I want to ...
7
votes
1answer
236 views

Unexpected outcome of a=“$@”

I'm struggling with this situation: $ set -- 1 2 3 $ a="$@" $ echo "$a" 1 2 3 What I find unexpected is the assignment itself. man bash says this about the "$@" expansion: When the expansion ...
3
votes
1answer
4k views

Ordered by insertion Map in bash

Is there an ordered (by insertion) map in bash? I know there's an associative array data structure in bash, but when iterating over it, the order of the elements is not by insertion. Example below. ...
5
votes
2answers
823 views

Portable check for array

Gawk has "isarray": if (isarray(x)) print "is array" else print "is scalar" However Mawk and "gawk --posix" do not: fatal: function 'isarray' not defined This can cause problems: x x[1] fatal:...
72
votes
5answers
83k views

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

If I have an array with 5 elements, for example: [a][b][c][d][e] Using echo ${myarray[4]} I can see what it holds. But what if I didn't know the number of elements in a given array? Is there a way ...
54
votes
3answers
96k views

How to add/remove an element to/from the array in bash?

I have an array containing some elements, but I want to push new items to the beginning of the array; How do I do that?
40
votes
3answers
24k views

Transform an array into arguments of a command?

I have an array of "options" of a command. my_array=(option1 option2 option3) I want to call this command in a bash script, using the values from array as options. So, command $(some magic here with ...
16
votes
11answers
14k views

Bash - reverse an array

Is there a simple way to reverse an array? #!/bin/bash array=(1 2 3 4 5 6 7) echo "${array[@]}" so I would get: 7 6 5 4 3 2 1 instead of: 1 2 3 4 5 6 7
4
votes
2answers
6k views

How to sum a bash array of numbers (some in scientific notation)?

Since the following command using bc does not work for numbers in scientific notation, I was wondering about an alternative, e.g. using awk? sum=$( IFS="+"; bc <<< "${arrValues[*]}" )
1
vote
3answers
14k views

store the command output in an array and print one by one

This is my command: cat httpd.conf | grep ^LogFormat | awk -F\" '{print $(NF)}' Output of this: commonsess common or can be any number of values, I need to store these values in an array and print ...
7
votes
4answers
6k views

How can I prepend and append to each member of an array?

I have an array: CATEGORIES=(one two three four) I can prepend to each array member using parameter expansion: echo ${CATEGORIES[@]/#/foo } I can append to each array member the same way: echo ${...
6
votes
3answers
24k views

How to pass array to bash shell script?

How do I pass an array as a variable from a first bash shell script to a second script. first.sh #!/bin/bash AR=('foo' 'bar' 'baz' 'bat') sh second.sh "$AR" # foo sh second.sh "${AR[@]}" # foo ...
6
votes
2answers
41k views

C Shell Array Declaration Syntax, () vs {}

In my C-shell script (tcsh specifically) I have been trying to declare an array with six values: x, nx, y, ny, z, nz. After some trial and error I discovered three different ways of declaring the ...
4
votes
2answers
1k views

How do you preserve a space in a literal expression in an array value in bash and how to trim down results from a sort command?

In the context of searching for expressions in log files, I was wondering generally if there was a way to quantify and qualify the contents of the logs in /var/log in some way. In particular, does the ...
2
votes
3answers
484 views

List all word pairs that appear in a line together in a file

How can I use awk to run through a file written as: Sarah,Masha,Helen Connor,Jessica,Jennifer,Candace Betty,Sarah,Helen John,Harold,Frank,Daisy and put out all pairs that appeared in a line together ...
2
votes
1answer
170 views

Why does this code work in bash v4.4 but not bash v3.2?

I have the following bash script: #!/bin/bash encl0=( 0,0 0,1 0,2 0,3 0,4 0,5 0,7 0,8 0,9 0,10 0,11 0,12 0,13 0,14 0,15 ) MISSING_DISKS=() OLDIFS=$IFS IFS=$'\n' MISSING_DISKS+=($({ printf '0 %s\n' {...
10
votes
2answers
17k views

Count number of elements in bash array, where the name of the array is dynamic (i.e. stored in a variable)

Brief statement of the question: Is there built-in bash method to count number of elements in bash array, where the name of the array is dynamic (i.e. stored in a variable), without resorting to ...
9
votes
2answers
4k views

Gawk: Passing arrays to functions

Stuck with GNU awk 3.1.6 and think I've worked around its array bugs but still have what looks like a scope problem in a 600-line awk program. Need to verify understanding of array scope in awk to ...
5
votes
2answers
623 views

How can I get the positional parameters, starting from two, or more generally, `n`?

($@) Expands to the positional parameters, starting from one. How can I get the positional parameters, starting from two, or more generally, n? I want to use the positional parameters starting from ...
3
votes
4answers
159 views

bash command to create array with the 10 most recent images in a dir?

I'm writing a bash script and I need to create an array with the 10 most recent image files (from new to old) in the current dir. I consider "image files" to be files with certain extensions, like ....
3
votes
1answer
351 views

How to create a possibly empty array from filename glob?

With zsh, it is not difficult to create a possibly empty array from the results of a (possibly null) filename glob. For example: % pathlist=( /no/such/path/*(N) ); printf -- "%d\n" $#pathlist 0 ...
3
votes
1answer
3k views

How to initialize a read-only, global, associative array in Bash?

I execute the following code in Bash version "GNU bash, Version 4.2.39(1)-release (x86_64-redhat-linux-gnu)": function foobar { declare -rgA FOOBAR=([foo]=bar) } foobar declare -p FOOBAR # Output: ...
3
votes
2answers
227 views

Array assignment behaviour

In Bash, the arrays a=( 11 22 ) and b=$(echo "11 22") behave differently when printed. $ a=( 11 22 ) $ b=$(echo "11 22") $ echo $b 11 22 $ echo $a 11 If we want to print the full contents of a we ...
2
votes
3answers
6k views

Using case and arrays together in bash

Is it possible to check if a variable is contained inside an array using case? I would like to do something like ARR=( opt1 opt2 opt3 ); case $1 in $ARR) echo "Option is contained in the ...
2
votes
1answer
719 views

GNU Parallel: How can I reference array elements?

This is my case scenario: luis@Balanceador:~$ echo ${array[@]} a b luis@Balanceador:~$ echo ${array[1]} a luis@Balanceador:~$ echo ${array[2]} b luis@Balanceador:~$ parallel echo ${array[]} ::: 1 2 -...
2
votes
1answer
3k views

Bash array declared in a function is not available outside the function

on bash (v4.3.11) terminal type this: function FUNCtst() { declare -A astr; astr=([a]="1k" [b]="2k" ); declare -p astr; };FUNCtst;declare -p astr (same thing below, just to be easier to read here) ...
2
votes
1answer
2k views

Does readarray allow to specify line delimiter?

In bash read builtin has -d for us to specify line delimiter other than newline Does readarray provide some way to specify line delimiter? Is it correct that it has no an option for that purpose? ...
2
votes
1answer
246 views

How to sum numbers inside many 2D arrays

I need to sum numbers located in a file like this one: column1 column2 column3 row1 a(1,1) a(1,2) a(1,3) row2 a(2,1) a(2,2) a(2,3) row3 a(3,1) a(3,2) a(3,3) row4 a(4,1) a(4,2) ...
2
votes
3answers
1k views

why is an array variable not considered set if it is assigned `()`?

bash manual says: A parameter is an entity that stores values A variable is a parameter denoted by a name. A parameter is set if it has been assigned a value. An array variable is ...
1
vote
2answers
215 views

What's the idiomatic way of returning an array in a zsh function?

I have this function, rpargs () { local i args=() for i in "$@" do test -e "$i" && args+="$(realpath --canonicalize-existing -- "$i")" || args+="$i" done } And I ...
1
vote
4answers
110 views

Re-print an array in a certain format?

I wish to take 10 random lines of file, which is 100 lines long. First, I randomly generate 10 integers between 1 and 100 (inclusive) with ind=$(shuf -i 1-100 -n 10 | sort -n) Then, I wish to use ...
0
votes
0answers
54 views

How can I get a continent array from a country list in python?

I have a list of countries and I need to create an array of continents in which each country is. I already tried with geopy module but my console do not allow me to use it. Also, I can't use ...
0
votes
2answers
1k views

bash syntax error: invalid arithmetic operator (error token is “.google.com”) when parsing through array

I have an array of domains that I am attempting to iterate through and check if a string from a file matches any of the domains in the array. However, when the for loop starts, I get an error line ...
0
votes
2answers
1k views

Define a set of values for a variable in shell script

I want to define a set of values for a single variable. E.g. singleDigit={0,1,2,3,4,5,6,7,8,9} If the user gives 10 it should exit with an error. How can this be achieved without using a loop, but ...
0
votes
1answer
31 views

Different result for positional parameters expansion and custom array expansion

There is a difference in the output of commands that I don't understand, as stated below: INPUT="$@" echo "$INPUT ${#INPUT} ${#INPUT[@]} ${#@}" # outputs: a b c 5 1 3 arr=(a b c) echo "$arr ${#arr} $...
0
votes
2answers
2k views

Multiple variable expansion modifiers in the same expression

Why does the following idiom not work in bash 4.1.0? if [[ "${FUNCNAME[*]:1/$FUNCNAME/}" != "${FUNCNAME[*]:1}" ]] Here it is in context... function isCircularRef_test () { # ### Seems like this ...