[英]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? 如果我将参数包装起来,在这种情况下,用引号将
"/home/someuser/Downloads/"
括起来,是否还需要将$ 1和checkDir括在引号中?
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. 不需要。您不必这样做,因为
$1
会正确分配给checkDir
,bash的[[ ]]
不会进行单词拆分,并且脚本可以按预期运行。
However, in case if you use sh
test [ .. ]
then you'll have a problem with: 但是,如果使用
sh
test [ .. ]
则会遇到以下问题:
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. 因此,始终最好引用变量,而不用记住变量是否重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.