Bash:混淆以星号扩展 [英] Bash: Confused by expanding asterisk

查看:116
本文介绍了Bash:混淆以星号扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的脚本,称为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:混淆以星号扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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