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

1
  • Declare -a also doest work Commented Jun 25, 2020 at 9:57

1 Answer 1

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
8
  • Can you show how to make a array containing (0 1 2 3 4) from for loop when array is empty at first @Stephane Chazelas Commented Jun 25, 2020 at 9:59
  • @DipeshSunrait, see edit. Commented Jun 25, 2020 at 10:01
  • still it doesnt work : imgur.com/a/PgXMnet i have quoted both array and i Commented Jun 25, 2020 at 10:06
  • @DipeshSunrait, try reading my answer again (maybe after refreshing the page). The problem is with your echo $array, not with your loop. Commented Jun 25, 2020 at 10:07
  • OH I FORGOT THAT ITS PRINTING FIRST CHARACTER Commented Jun 25, 2020 at 10:07

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.