Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you push variables in quotes in boolean conditions?

Tags:

linux

bash

Are the following two boolean expressions the same?

if [ -n $1 ] ; then   
if [ -n "$1" ] ; then

And these two

if [ $? == 0 ] ; then
if [ "$?" == 0 ] ; then

If not - When should you put a variable in quotes?

like image 773
user784637 Avatar asked Dec 01 '22 05:12

user784637


1 Answers

put variables in quotes when there is any chance that the value may contain white spaces, or in general NOT be a continuous string of characters. So

as $? should always be something between 0 and 255, you don't need to quote that because it is a return value set after each sub-process returns. It is NOT possible to break that by assigning a string value directly, i.e.

$?=Is of course wrong and should be

 ?=Bad value assigment

because a user variable name must start with [A-Za-z_] , so don't do that ;-)

Whereas for $1, if a value is passed in like

myscript "arg1 with spaces"

the test

if [ -n $1 ] ; then

will blow up,

but the test

if [ -n "$1" ] ; then  

will succeed.

IHTH

like image 131
shellter Avatar answered Dec 06 '22 09:12

shellter