0
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# array=()
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# for i in 1 2 3 4
> do
> array+=($i)
> done
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# echo $array
1
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# for i in 1 2 3 4; do array+=( $i ); done
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# echo $array
1
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# for i in 1 2 3 4; do array+=( $i ); done
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# for i in 1 2 3 4; do
> array=( "${array[@]}" "$i" )
> done
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# echo $array
1
root@kali-linux:~/Softwares/Softwares/Tools/dirsearch# 

How to add/remove an element to/from the array in bash? I tried to add like as said in this question still it doesnt work and print 1

terdon
  • 242,166
Machine Yadav
  • 189
  • 1
  • 3
  • 15

1 Answers1

4

Your loop is fine (except that you forgot to quote $i), the problem is in your echo $array, which doesn't print all the elements of the array in bash.

bash has copied the awkward array design of ksh instead of that of zsh, csh, tcsh, rc...

In ksh, $array is short for ${array[0]} (expands to the contents of the element of indice 0 or an empty string if it's not set).

To expand to all the elements of the array, you need:

$ printf ' - "%s"\n' "${array[@]}"
 - "1"
 - "2"
 - "3"
 - "4"

For the first element of the array (which may not be the one with indice 0 as ksh/bash arrays are sparse):

$ printf '%s\n' "${array[@]:0:1}"
1

And for the element of indice 0 (which in your example is going to be the same as the first element):

$ printf '%s\n' "$array"
1

or:

$ printf '%s\n' "${array[0]}"
1

To print the definition of a variable, you can also use typeset -p:

ksh93u+$ typeset -p array
typeset -a array=( 1 2 3 4 )
bash-5.0$ typeset -p array
declare -a array=([0]="1" [1]="2" [2]="3" [3]="4")
bash-5.0$ unset 'array[0]'
bash-5.0$ typeset -p array
declare -a array=([1]="2" [2]="3" [3]="4")
bash-5.0$ printf '%s\n' "$array"

bash-5.0$ printf '%s\n' "${array[@]:0:1}" 2