问题描述
我有一个非常简单的脚本,称为test.sh
.
I have a very simple scripts called test.sh
.
#!/bin/bash
echo $(cat './data')
while read line
do
data=$data' '$line
done < './data'
echo $data
和data
文件:
1 * 1 = 1
但是实际上bash(4.3.11)/dash(sh 0.5.7)会扩展星号本身.它打印出来
But actually bash(4.3.11)/dash(sh 0.5.7) expands asterisk itself. It prints out
1 test.sh data 1 = 1
1 test.sh data 1 = 1
Zsh(5.0.2)不会这样.
Zsh(5.0.2) won't act like this.
我不知道为什么.如何使用bash打印出
I don't know why. How can I print out using bash
1 * 1 = 1
谢谢.
推荐答案
规则1,引用您的变量!
Rule #1, quote your variables!
echo "$(cat data)"
和
data="$data $line"
和
echo "$data"
尽管在下面的注释(已删除)中指出了 gniourf_gniourf ,但三项更改中的第二项是实际上没有必要,因为在变量分配过程中不会发生全局扩展.
Although as gniourf_gniourf pointed out in the comments below (since removed), the second of the three changes is actually unnecessary, as glob expansion does not occur during variable assignment.
也就是说,如果您只想打印文件的内容,则根本不需要使用命令替换或read
循环.为什么不只使用cat data
?
That said, if you just want to print the contents of the file, there's no need to use a command substitution or read
loop at all. Why not just use cat data
?
或者,要将文件的内容存储到变量中,只需使用data="$(cat data)"
(这里的引号很重要),或者如上面的注释中gniourf_gniourf data="$(< data)"
所建议的那样.
Alternatively, to store the contents of the file to a variable, just use data="$(cat data)"
(the quotes are important here), or as suggested in the comments above by gniourf_gniourf, data="$(< data)"
.
这篇关于Bash:混淆以星号扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!