Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • 21
    Does not work with set -u: "unbound variable" - if the array is empty. Commented Apr 8, 2017 at 19:56
  • 1
    @Igor: Works for me in Bash 4.4. set -u; foo=(); [ ${#foo[@]} -eq 0 ] && echo empty. If I unset foo, then it prints foo: unbound variable, but that's different: the array variable doesn't exist at all, rather than existing and being empty. Commented Sep 17, 2017 at 4:22
  • 1
    Also tested in Bash 3.2 (OSX) when using set -u - as long as you declared your variable first, this works perfectly. Commented Aug 5, 2018 at 16:48
  • this one is more compatible for most shells, but found this arithmetic way also stackoverflow.com/a/65957757/1091853 Commented Sep 21, 2023 at 16:30
  • Why do I get a "unbound variable" if I declare the array using declare -a myarr, but it works if declared using myarr=() or declare -a myarr=()? Commented May 9, 2025 at 6:59