Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: What is the purpose of using `/` in a list?

Tags:

bash

list

Defining a list:

arr=(2 3 4)

Then changing it like that:

arr=${arr[@]/4}

Printing it:

echo ${arr[@]} => 2 3 3 4

Why is this the result and what is the purpose of this slash?

like image 608
Omer H Avatar asked Nov 22 '25 17:11

Omer H


1 Answers

${arr[@]/4} will remove entry with value 4 from original array.

Similarly ${arr[@]/3} will remove 3

Examples:

arr=(2 3 4)

echo ${arr[@]/4}
2 3

echo ${arr[@]/3}
2 4

echo ${arr[@]/2}
3 4

echo ${arr[@]/5}
2 3 4

Explanation of OP's problem:

arr=${arr[@]/4}

is equivalent of:

arr[0]=${arr[@]/4}

which is assigning 2 3 to very first element in array hence making it:

2 3 3 4

declare -p will make it crystal clear:

declare -p arr
declare -a arr='([0]="2 3" [1]="3" [2]="4")'

Not 2 3 at 1st position of this array.

Correct way of array assignment is:

arr=("${arr[@]/4}")
like image 134
anubhava Avatar answered Nov 25 '25 08:11

anubhava