0

I was doing some reading here and it suggested that I wrap my variables in quotes just in case the value contains spaces.

If I have the following script:

#!/bin/bash

function checkDirectory()
{
    local checkDir=$1

    if [[ -d $checkDir ]] ; then 
        echo "File is directory"
    fi


}


checkDirectory "/home/someuser/Downloads/"

If I wrap my parameter, in this case, "/home/someuser/Downloads/" in quotes, do I still need to wrap $1 and checkDir in quotes as well?

Community
  • 1
  • 1

1 Answers1

1

No. You don't have to as $1 will be assigned to checkDir correctly and bash's [[ ]] won't do word splitting and your script will work as expected.

However, in case if you use sh test [ .. ] then you'll have a problem with:

if [ -d $checkDir ] ; then 
    echo "File is directory"
fi

So it's always good practice to quote your variables rather than having to remember it matters and when not.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • The right side of an assignment and *some* places in `[[ ]]` are about the only places its safe to leave the quotes off. Much simpler to just always use quotes than to keep track of where it's safe to omit them. – Gordon Davisson Mar 15 '15 at 17:22