Difference between revisions of "Bash test missing variables"
Jump to navigation
Jump to search
(Created page with "https://unix.stackexchange.com/questions/463034/bash-throws-error-line-8-1-unbound-variable ``` n particular, one could use [ -n "${1-}" ] (that is, with an empty default valu...") |
|||
Line 1: | Line 1: | ||
+ | |||
+ | |||
+ | ``` | ||
+ | if ! [ -n "${myvar-}" ]; then | ||
+ | echo $myvar not exist | ||
+ | fi | ||
+ | ``` | ||
+ | |||
+ | https://tldp.org/LDP/abs/html/comparison-ops.html | ||
+ | ``` | ||
+ | -n | ||
+ | string is not null. | ||
+ | |||
+ | Caution | ||
+ | The -n test requires that the string be quoted within the test brackets. Using an unquoted string with ! -z, or even just the unquoted string alone within test brackets (see Example 7-6) normally works, however, this is an unsafe practice. Always quote a tested string. [1] | ||
+ | ``` | ||
+ | |||
https://unix.stackexchange.com/questions/463034/bash-throws-error-line-8-1-unbound-variable | https://unix.stackexchange.com/questions/463034/bash-throws-error-line-8-1-unbound-variable | ||
``` | ``` |
Latest revision as of 13:32, 29 March 2023
if ! [ -n "${myvar-}" ]; then echo $myvar not exist fi
https://tldp.org/LDP/abs/html/comparison-ops.html
-n string is not null. Caution The -n test requires that the string be quoted within the test brackets. Using an unquoted string with ! -z, or even just the unquoted string alone within test brackets (see Example 7-6) normally works, however, this is an unsafe practice. Always quote a tested string. [1]
https://unix.stackexchange.com/questions/463034/bash-throws-error-line-8-1-unbound-variable
n particular, one could use [ -n "${1-}" ] (that is, with an empty default value) to see if the parameter is set and non-empty; or [ "${1+x}" = x ] to see if it's set, even if empty. – ilkkachu Aug 16, 2018 at 18:30 I still get unbound variable error despite using if [[ -n ${1-default} ]] – Chaitanya Bapat Dec 7, 2019 at 2:59 5 @ChaitanyaBapat I was still getting unbound variable as well until I used :- instead of -. So, for me at least, the ${1:-default} no loner raised the error. – Adam Badura Apr 9, 2020 at 11:26 As a side note, if you are trying to access an array element with an index out of range, you get the same error (with syntax ${my_array[$index]}).