简体   繁体   中英

Bash Script - Wrapping Variables in Quotes

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM