PS I skipped filtering "0.0" as I don't think a user would disable a setting by setting this, but feel free to extend the filter if you need it. Now, I can be sure that the variable exists with a content or not, so I can use a usual condition like this: if ] then So in the script section itself I do this: # check user settings The users of the script should be able to set it as they like: dry_run= Imagine you have a bash script with a settings section like this: # enable test mode But instead of using a separate function, I use a "filter" which finally allows using usual bash conditions. For example, a shell script could set a user-defined variable. I prefer the way how PHP checks for an empty variable as Luca mentioned in his answer, too. Variables were originally invented for Badges as a way for users to embed text in a badge. Having said that in a bash logic the checks on zero in this function can cause side problems imho, anyone using this function should evaluate this risk and maybe decide to cut those checks off leaving only the first one. # Return true if var is 0.0 (0 as a float) # Return true if var is zero (0 as an integer or "0" as a string) a declared variable or array but without a value is passed var is a null string ("" as empty string) Of course the null and false cases cannot be converted in bash, so they are omitted. a variable declared, but without a value. The question asks how to check if a variable is an empty string and the best answers are already given for that.īut I landed here after a period passed programming in php and what I was actually searching was a check like the empty function in php working in a bash shell.Īfter reading the answers I realized I was not thinking properly in bash, but anyhow in that moment a function like empty in php would have been soooo handy in my bash code.Īs I think this can happen to others, I decided to convert the php empty function in bashĪ variable is considered empty if it doesn't exist or if its value is one of the following: The following are examples of how you can test the various possibilities, and it works in bash or any POSIX-compatible shell: if because the first argument to [ is erroneously interpreted as the -n operator, not a string. Most of the time you only need to know if a variable is set to a non-empty string, but occasionally it's important to distinguish between unset and set to the empty string. A variable in bash (and any POSIX-compatible shell) can be in one of three states:
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |