Shell--引用变量带不带""的区别
在shell脚本中,引用变量时有几种形式: $dir "$dir" "${dir}" ,每种形式的含义不同
$dir
: 这种形式的变量名是最简单的形式,表示直接引用变量的值。在这种情况下,如果变量的值包含空格或特殊字符,则会被解释为单个参数。"$dir"
: 表示引用变量的值,并保留其中的空格和特殊字符。双引号将变量的值看作一个整体。这种形式通常用于需要保留空格、特殊字符或对变量进行字符串插值的情况。- "${dir}": 使用
${}
来引用变量,这种形式通常用于在变量名后面紧跟其他字符,以明确指示变量名的边界。${dir}
也可以用于在变量名中包含特殊字符,或在字符串中嵌入变量.
实例:
#!/bin/bash dir="path/to/directory" file_name="my file.txt" # 不使用引号 echo $dir # 输出:path/to/directory # 使用双引号 echo "$dir" # 输出:path/to/directory echo "$file_name" # 输出:my file.txt # 在变量名后面紧跟其他字符 echo "${dir}name" # 输出:path/to/directoryname # 用于在变量名中包含特殊字符 echo "${dir}_suffix" # 输出:path/to/directory_suffix # 用于在字符串中嵌入变量 echo "The file is: ${dir}/${file_name}" # 输出:The file is: path/to/directory/my file.txt