Questions tagged [bash-array]
The bash-array tag has no summary.
83 questions
38
votes
15
answers
51k
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
23
votes
3
answers
11k
views
How to remove new line added by readarray when using a delimiter?
VAR=a,b,c,d
# VAR=$(echo $VAR|tr -d '\n')
echo "[$VAR]"
readarray -td, ARR<<< "$VAR"
declare -p ARR
Result:
[a,b,c,d]
declare -a ARR=([0]="a" [1]="b" [2]="c" [3]=$'d\n')
How can I tell ...
17
votes
4
answers
18k
views
Run a command using arguments that come from an array
Suppose I have a graphical program named app. Usage example: app -t 'first tab' -t 'second tab' opens two 'tabs' in that program.
The question is: how can I execute the command (i.e. app) from within ...
9
votes
3
answers
26k
views
How to unset range of array in Bash
I'm trying to delete range of array element but it's fail..
My array
root@ubuntu:~/work# echo ${a[@]}
cocacola.com airtel.com pepsi.com
Print 0-1 array looks ok
root@ubuntu:~/work# echo ${a[@]::2}
...
7
votes
2
answers
10k
views
Find array length in zsh script
Is there a way to find the length of the array *(files names) in zsh without using a for loop to increment some variable?
I naively tried echo ${#*[@]} but it didn't work. (bash syntax are welcome ...
7
votes
1
answer
365
views
Cannot delete bash associative array element
Consider an associative array in bash (versions 5.2.15(1)-release and 5.2.21(1)-release):
declare -A ufs=(); ufs["one"]=1; ufs["two"]=2; ufs["three"]=3
printf '> %s\n' ...
7
votes
1
answer
430
views
Bash 4.4 local readonly array variable scoping: bug?
The following script fails when run with bash 4.4.20(1)
#!/bin/bash
bar() {
local args=("y")
}
foo() {
local -r args=("x")
bar
}
foo
with error line 3: args: readonly ...
5
votes
2
answers
15k
views
How to pass an array as function argument but with other extra parameters?
The following post solution works as expected:
How to pass an array as function argument?
Therefore - from his answer:
function copyFiles() {
arr=("$@")
for i in "${arr[@]}"...
5
votes
1
answer
566
views
How to pipe multiple results into a command?
I have a piece of code which works, something like this (note this is inside CloudFormation Template for AWS auto deployment):
EFS_SERVER_IPS_ARRAY=( $(aws efs describe-mount-targets --file-system-id ...
4
votes
2
answers
1k
views
Bash's read builtin errors on a string-based timeout option specification but not an array-based one. Why?
In reading through the source to fff to learn more about Bash programming, I saw a timeout option passed to read as an array here:
read "${read_flags[@]}" -srn 1 && key "$REPLY&...
4
votes
1
answer
4k
views
Why is "${ARRAY[@]}" expanded into multiple words, when it's quoted?
I don't understand why "${ARRAY[@]}" gets expanded to multiple words, when it's quoted ("...")?
Take this example:
IFS=":" read -ra ARRAY <<< "foo:bar:baz"
for e in "${ARRAY[@]}"; do echo $...
4
votes
1
answer
2k
views
What is the difference between ${array[*]} and ${array[@]}? When use each one over the other? [duplicate]
With the following code:
#! /bin/bash
declare -a arr=("element1"
"element2" "element3&...
4
votes
2
answers
2k
views
How to slice an indexed array to obtain all elements between the first and last index?
I have an array tokens which contains tokens=( first one two three last ). How do I obtain the values ( one two three ) if I do not know how many numbers are in the array? I want to access everything ...
3
votes
3
answers
4k
views
How do I split a string by a delimiter resulting in an unknown number of parts and how can I collect the results in an array?
I need to process some strings containing paths. How do I split such a string by / as delimiter resulting in an unknown number of path-parts and how do I, in the end, extract the resulting path-parts?
...
3
votes
4
answers
3k
views
How do I select an array to loop through from an array of arrays?
#!/usr/bin/bash
ARGENT=("Nous devons économiser de l'argent."
"Je dois économiser de l'argent.")
BIENETRE=("Comment vas-tu?" "Tout va bien ?")
aoarrs=("${...
3
votes
3
answers
8k
views
Find second largest value in array
I have an array like this:
array=(1 2 7 6)
and would like to search for the second largest value, with the output being
secondGreatest=6
Is there any way to do this in bash?
3
votes
2
answers
754
views
Iterating over array elements with gnu parallel
I have an input file, names.txt, with the 1 word per line:
apple
abble
aplle
With my bash script I am trying to achieve the following output:
apple and apple
apple and abble
apple and aplle ...
3
votes
2
answers
2k
views
How to extract and delete contents of a zip archive simultaneously?
I want to download and extract a large zip archive (>180 GB) containing multiple small files of a single file format onto an SSD, but I don't have enough storage for both the zip archive and the ...
2
votes
5
answers
4k
views
echoing value in same indexes of 2 arrays simulataneously
I have 2 arrays to prcoess in bash script simultaneously.
First array contains sort of lables.
Second array contains values, as under
LABELS=(label1 label2 label3 labe4 )
VALUES=(91 18 7 4)
What's ...
2
votes
3
answers
495
views
Replace prefix string from lines in a file, and put into a bash array
In the file groupAfiles.txt are the lines:
file14
file2
file4
file9
I need a way to convert them to remove file and add /dev/loop and put them all in one line with a space between them.
/dev/loop14 /...
2
votes
1
answer
329
views
Why does printing an array with @ using printf in bash only print the first element?
I have an array
snapshots=(1 2 3 4)
When I run
printf "${snapshots[*]}\n"
It prints as expected
1 2 3 4
But when I run
printf "${snapshots[@]}\n"
It just prints
1
without a ...
2
votes
1
answer
445
views
How can I take a sub-array in bash of the first N elements of a string array with elements containing spaces?
This question is similar to this one but it differs from it:
Consider this array with string elements which may contain spaces:
a@W:$ arr=("eins" "zwei" "eins plus zwei" &...
2
votes
1
answer
114
views
How to access further members of an array when using bash variable indirection?
Consider the following example, it seems it's working fine with the index 0:
$ a1=(1 2 3)
$ a2=(a b c)
$ for x in a1 a2; do echo "${!x}"; done
1
a
$ for x in a1 a2; do echo "${!x[0]}"; done
1
a
...
2
votes
1
answer
345
views
What happens if I start a bash array with a big index?
I was trying to create a bash "multidimensional" array, I saw the ideas on using associative arrays, but I thought the simplest way to do it would be the following:
for i in 0 1 2
do
...
2
votes
2
answers
9k
views
Shell script-How to return maximum value in array?
I have a array:
ARRAY=(12.5 6.2)
I wish to return the maximum value in ARRAY which Output is 12.5
Anyone can share me ideas?
I have try this:
max=0
for v in ${ARRAY[@]}; do
if (( $v > $max )...
2
votes
1
answer
3k
views
Bash - mix/merge/combine two different arrays with same length
I have two different arrays with the same length:
s=(c d e f g a b c)
f=(1 2 3 1 2 3 4 5)
how can I mix/merge/combine this two arrays, so I would get this output:
c1 d2 e3 f1 g2 a3 b4 c5
2
votes
1
answer
248
views
Bash array only executes first index
I am working with a server running Ubuntu 18.01 LTS and I'm trying to automate the backup of multiple virtual machines.
I have the VM names in an array and then a for loop to shut down, backup and ...
2
votes
1
answer
75
views
Why isn't the `else` arm executed in this Bash script (for loop through an array)?
The following code is meant to look for subdirectories in ~/Downloads. I run it with . ./script.sh. It will find them even when the user submits an incomplete name.
#!/usr/bin/bash
echo -e "\...
2
votes
1
answer
953
views
Can't access elements of an array built from readarray
I'm trying to build a basic REPL in bash.
The script dynamically populates a list of files in a directory for the user to run.
File space:
|
|\ scripts/
|| script1.sh
|| script2.sh
|
\ shell/
| ...
2
votes
0
answers
308
views
for loop and appending over list of arrays
I am new to Bash scripting and presently find myself dealing with a small problem in working with for loops, arrays and variable assignment/substitution which I do not know how to solve. Since I am ...
1
vote
2
answers
3k
views
gnu parallel with bash array
I trying to run command recon-all with GNU parallel freesurfer preproc i have a bash array of list of patients to run 8 patents simultaneously:
root@4d8896dfec6c:/tmp# echo ${ids[@]}
G001 G002 G003 ...
1
vote
2
answers
2k
views
Array Declaration: Double Quotes & Parentheses
Perhaps this is a stupid question but two hours on Google hasn't turned up anything on point.
Simply, does a difference exist in Bash between:
X="
a
b
c
"
and
X=(
a
b
c
)
The former ...
1
vote
2
answers
2k
views
Why isn't $ARRAY+=$var working for me?
I am trying to add an element to a bash array. I looked at this question and tried to follow its advice.
This is my code:
selected_projects=()
for project_num in ${project_numbers[@]}; do
...
1
vote
1
answer
1k
views
Creating and appending to an array, mapfile vs arr+=(input) same thing or am I missing something?
Is there a case where mapfile has benefits over arr+=(input)?
Simple examples
mapfile array name, arr:
mkdir {1,2,3}
mapfile -t arr < <(ls)
declare -p arr
output:
declare -a arr=([0])="1&...
1
vote
1
answer
6k
views
linux + how to convert variable to array
we want to set variable that includes words as array
folder_mount_point_list="sdb sdc sdd sde sdf sdg"
ARRAY=( $folder_mount_point_list )
but when we want to print the first array value we get all ...
1
vote
3
answers
4k
views
Bash: converting a string with both spaces and quotes to an array
I have a function (not created by me) that outputs a series of strings inside of quotes:
command <args>
“Foo”
“FooBar”
“Foo Bar”
“FooBar/Foo Bar”
When I try to assign it to an array (Bash; BSD/...
1
vote
1
answer
346
views
Completed stumped by trying to use a decimal value in an array for Bash
Here is some simple test code.
#!bin/bash
cpm=(0 1 0.094)
lv=1
attack=5
defense=9
stamina=16
echo $((cpm[lv]))
mycpm=$((cpm[lv]))
#mycpm=`echo "0.094" | bc -l`
cq=`echo "$attack*$...
1
vote
2
answers
193
views
Getting an array into a parallel bash script
I'm having a bit of difficulty understanding parallel procedures. Atm I'm trying to mass wipe hard drives, so have created a script, however it won't run in parallel.
for i in "${!wipe[@]}"; ...
1
vote
1
answer
386
views
How to reference an array with a function prior to bash4.3
If we:
Define an array; and then..
Define a function; and want to..
Call that array from inside the function..
We can. Like so:
Input:
myArray=('1' '2' '3' '4' '5')
myFunction ()
{
local -n myList=...
1
vote
2
answers
389
views
Why can't I convert a string variable into an array when some items include spaces?
For example, in the snippet below, (how) is it possible to make array2 identical to array1 while still using a str variable?
~$ { str='a "b c" d'; array1=(a "b c" d); array2=( $str )
echo "${array1[...
1
vote
1
answer
1k
views
Array only returns one element
i'm trying to generate a script that ftp some files to a server using lftp. when i run these commands in shell:
DBNAME=TESTDB
ls -t /data*/${DBNAME,,}Backup/$DBNAME.0.db21.DBPART000.`date +%Y%m%d`...
1
vote
2
answers
2k
views
Merge duplicate keys in associative array BASH
I've got an array that contains duplicate items, e.g.
THE_LIST=(
"'item1' 'data1 data2'"
"'item1' 'data2 data3'"
"'item2' 'data4'"
)
Based on the above, I want to create an associative array that ...
1
vote
1
answer
1k
views
Array inside an Array: Different syntax for Array in bash
I found the following example from here. But I can't understand how is array arr is being defined.
a='domain.de;de;https'
$ arr=(${a//;/ })
What is the advantage of defining it like this?
Actually, ...
1
vote
1
answer
410
views
Access values of associative array whose name is passed as argument inside bash function
I've some associative arrays in a bash script which I need to pass to a function in which I need to access the keys and values as well.
declare -A gkp=( \
["arm64"]="ARM-64-bit" ...
1
vote
1
answer
970
views
How to separate long string into a string array with IFS and read, or any other method
I have a long line that comes as output from a git command: a=$(git submodule foreach git status). It looks like this:
a = "Entering 'Dir1/Subdir' On branch master Your branch is up to date with '...
1
vote
2
answers
528
views
Pass the name of an array in command line to reference the array in a function
I'm trying to learn more bash by updating my bash_profile so that I can quickly do some adb commands that I usually have to copy-paste. I found I was creating many similar functions that all looked ...
1
vote
2
answers
224
views
Counting and adding if some arrays has element at some index
Can the below code be easily achieved with minimum coding.
$ cluster1=(x y)
$ cluster2=(a b)
$ cluster3=(m)
$ my=$((${cluster1[0]+1}+${cluster2[0]+1}+${cluster2[0]+1}))
$ echo $my
3
$ my=$((${...
1
vote
0
answers
110
views
bash transfer multiple files in seq and uniq to sub folders
I have thousands or more than thousands of files like
A20200727.2015+0200-2030+0200_SubNetwork=ppp,MeContext=xxx23,celltracefile_DUL1_3.bin.gz
A20200727.2015+0200-2030+0200_SubNetwork=ppp,MeContext=...
1
vote
1
answer
101
views
issue with bash arrays containing both commands and paths
I'm trying to write a script to tailor my dotfile setup to each machine using git update-index -skip-worktree
but it keeps chopping up the paths. I'm passing arrays starting with commands where every ...
1
vote
0
answers
301
views
Assigning array values while running a loop to a variable dynamically
The values present in indexArray are: 1 4 3 2
Below is the code snippet(This is not the complete code):
while read -r line;do
position=${indexArray[$counter]} # No value is assigned to "position" ...