我刚刚分配了一个变量,但 echo $variable 显示了其他内容 [英] I just assigned a variable, but echo $variable shows something else

查看:20
本文介绍了我刚刚分配了一个变量,但 echo $variable 显示了其他内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一系列情况,其中 echo $var 可以显示与刚刚分配的值不同的值.无论分配的值是双引号"、单引号"还是不带引号,都会发生这种情况.

Here are a series of cases where echo $var can show a different value than what was just assigned. This happens regardless of whether the assigned value was "double quoted", 'single quoted' or unquoted.

如何让 shell 正确设置我的变量?

How do I get the shell to set my variable correctly?

星号

预期的输出是 /* Foobar is free software */,但我得到了一个文件名列表:

The expected output is /* Foobar is free software */, but instead I get a list of filenames:

$ var="/* Foobar is free software */"
$ echo $var 
/bin /boot /dev /etc /home /initrd.img /lib /lib64 /media /mnt /opt /proc ...

方括号

期望值是[a-z],但有时我会得到一个字母!

The expected value is [a-z], but sometimes I get a single letter instead!

$ var=[a-z]
$ echo $var
c

换行(换行)

预期值是一列单独的行,但所有值都在一行上!

The expected value is a a list of separate lines, but instead all the values are on one line!

$ cat file
foo
bar
baz

$ var=$(cat file)
$ echo $var
foo bar baz

多个空格

我希望有一个仔细对齐的表格标题,但多个空格要么消失要么折叠成一个!

I expected a carefully aligned table header, but instead multiple spaces either disappear or are collapsed into one!

$ var="       title     |    count"
$ echo $var
title | count

标签

我希望有两个制表符分隔值,但我得到了两个空格分隔值!

I expected two tab separated values, but instead I get two space separated values!

$ var=$'key	value'
$ echo $var
key value

推荐答案

在上述所有情况下,变量设置正确,但读取不正确!正确的方法是在引用时使用双引号:

In all of the cases above, the variable is correctly set, but not correctly read! The right way is to use double quotes when referencing:

echo "$var"

这给出了所有示例中的预期值.始终引用变量引用!

This gives the expected value in all the examples given. Always quote variable references!

为什么?

当一个变量不加引号时,它会:

  1. 进行字段拆分,其中将值拆分为多个单词空格(默认):

  1. Undergo field splitting where the value is split into multiple words on whitespace (by default):

之前:/* Foobar 是免费软件 */

之后:/*Foobarisfreesoftware, */

这些词中的每一个都将经历路径名扩展,其中模式是扩展为匹配的文件:

Each of these words will undergo pathname expansion, where patterns are expanded into matching files:

之前:/*

之后:/bin/boot/dev/etc/home, ...

After: /bin, /boot, /dev, /etc, /home, ...

最后,所有参数都传递给 echo,它把它们写出来 用分隔符单个空格,给

Finally, all the arguments are passed to echo, which writes them out separated by single spaces, giving

/bin /boot /dev /etc /home Foobar is free software Desktop/ Downloads/

而不是变量的值.

当变量被引用时,它会:

  1. 替换为它的值.
  2. 没有第 2 步.

这就是为什么您应该总是引用所有变量引用,除非您特别需要分词和路径名扩展.shellcheck 之类的工具可以提供帮助,并且会在上述所有情况下警告缺少引号.

This is why you should always quote all variable references, unless you specifically require word splitting and pathname expansion. Tools like shellcheck are there to help, and will warn about missing quotes in all the cases above.

这篇关于我刚刚分配了一个变量,但 echo $variable 显示了其他内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆