Timeline for Check if array is empty in Bash
Current License: CC BY-SA 3.0
14 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Apr 14, 2023 at 6:22 | comment | added | dimo414 | -1, please don't go around treating arrays like scalars, it's just going to confuse people (and will be wrong in all sorts of cases). | |
| Jan 20, 2023 at 20:52 | comment | added | kdubs | this is only check if the first element is empty, not the array. | |
| Jul 24, 2019 at 14:22 | comment | added | Shardj | This answer is straight up wrong, why does it have 8 points? It believes the array is incorrectly empty for many different cases | |
| Jun 18, 2019 at 17:35 | comment | added | Peter Cordes | @Michael: Added an answer that does this. | |
| Jun 18, 2019 at 16:57 | comment | added | Peter Cordes | @Michael: Crap, you're right. It only works with a 1-element array of an empty string, not 2 elements. I even checked older bash and it's still wrong there; like you say set -x shows how it expands. I guess I didn't test that comment before posting. >.< You can make it work by setting IFS='' (save/restore it around this statement), because "${array[*]}" expansion separates elements with the first character of IFS. (Or space if unset). But "If IFS is null, the parameters are joined without intervening separators." (docs for $* positional params, but I assume same for arrays). | |
| Jun 18, 2019 at 16:37 | comment | added | Michael come lately | @PeterCordes I don't think that works. The expression evaluates to a single space character, and [[ -n " " ]] is "true," which is a pity. Your comment is exactly what I want to do. | |
| Sep 19, 2017 at 15:21 | comment | added | Peter Cordes | [[ -n "${array[*]}" ]] interpolates the entire array as a string, which you check for non-zero length. If you consider array=("" "") to be empty, rather than having two empty elements, this might be useful. | |
| Sep 14, 2016 at 14:46 | history | edited | wget | CC BY-SA 3.0 | bad assumptions |
| S May 2, 2016 at 18:38 | history | suggested | Alfredo Capobianchi | CC BY-SA 3.0 | added case in which all array elements are checked |
| May 2, 2016 at 16:00 | review | Suggested edits | |||
| S May 2, 2016 at 18:38 | |||||
| Aug 17, 2015 at 23:25 | comment | added | musiphil | [ -z "$array" ] or [ -n "$array" ] doesn't work. Try array=('' foo); [ -z "$array" ] && echo empty, and it will print empty even though array is clearly not empty. | |
| Jun 23, 2015 at 10:45 | review | Late answers | |||
| Jun 23, 2015 at 11:09 | |||||
| Jun 23, 2015 at 10:30 | review | First posts | |||
| Jun 23, 2015 at 10:43 | |||||
| Jun 23, 2015 at 10:29 | history | answered | wget | CC BY-SA 3.0 |