Bash 变量格式

标签 bash shell scripting

关于使用 BASH 编写脚本,以下变量之间有什么区别:

$var
"$var"
${var}
"${var}"

最佳答案

$var${var} 之间没有区别 "$var" 之间没有区别"${var}",但在某些情况下,当您使用以前的版本时,解析器可能无法识别您的意图。考虑:

foo=hello
echo "$fooworld"
echo "${foo}world"

第一个 echo 什么都不打印,因为变量 fooworld 没有定义。第二个打印 helloworld 因为 shell 能够确定您正在引用 foo 变量。

$var"$var" 之间的区别在于,未加引号的变量扩展在扩展后由 shell 计算。因此:

var='ls /'
$var

列出 /,因为在扩展之后 shell 将空间评估为标记分隔符,而

var='ls /'
"$var"

结果 ls/: No such file or directory 因为在用户环境中没有名为 ls/ 的命令可用。

关于Bash 变量格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10388599/

相关文章:

bash - 读取文件中的每一行,替换变量并将输出发送到文件 bash

c++ - 通过命令行c++传递带括号的参数

linux - FInd patternf 用于多个文件模式

python - 使用来自 cron 的日志文件重定向 stderr

php - Filemtime/cachetime 我哪里出错了?

linux - 将命令输出存储到 shell 脚本中的数组

linux - 从 bash 中的文件相乘的单行命令

c++ - 查找命令行参数数组中的元素数量?

scripting - 如何使用Powershell监视命令的特定收件箱?

linux - awk : how to use variable value