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 – Machine Yadav Jun 25 '20 at 9:57
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 – Machine Yadav Jun 25 '20 at 9:59
  • @DipeshSunrait, see edit. – Stéphane Chazelas Jun 25 '20 at 10:01
  • still it doesnt work : imgur.com/a/PgXMnet i have quoted both array and i – Machine Yadav Jun 25 '20 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. – Stéphane Chazelas Jun 25 '20 at 10:07
  • OH I FORGOT THAT ITS PRINTING FIRST CHARACTER – Machine Yadav Jun 25 '20 at 10:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.