Bash:非法变量名错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39862587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:15:36  来源:igfitidea点击:

Bash: illegal variable name error

bashshellgrepnaming-conventions

提问by Jeff

I am trying to extract a field from a text file using grep. I want to store the line number into a bash variable for later, but I am getting an illegal variable name error. This is part of my script:

我正在尝试使用 grep 从文本文件中提取一个字段。我想将行号存储到 bash 变量中以备后用,但我收到了非法变量名错误。这是我的脚本的一部分:

#!/bin/csh

set echo

grep -n -m 1 "HR" Tossed/length/TLD2R-TT.txt | cut -d : -f 1

To_Start=$((grep -n -m 1 "HR" Tossed/length/TLD2R-TT.txt | cut -d : -f 1))

This is the output:

这是输出:

[maurerj1@rucc-headnode Tenengolts_Generate]$ ./flow_LBBH.sh 7 0 0 0
grep --color=auto -n -m 1 HR0 Tossed/length7/TL7D2R0-0TT.txt
cut -d : -f 1
1                          #This is the right number
Illegal variable name.     #why is this not working?

From what I've read, uppercase, lowercase and underscores are allowed in bash variable names, so what am I doing wrong?

从我读过的内容来看,bash 变量名中允许使用大写、小写和下划线,那么我做错了什么?

回答by Jean-Fran?ois Fabre

the $(( expr ))syntax is used for calculations hence the confusing message.

$(( expr ))语法用于计算因此混淆消息。

ex: echo $((4+4))yields 8

例如:echo $((4+4))产量 8

you want to evaluate the result of a command, simple parenthesis will do:

你想评估一个命令的结果,简单的括号就可以了:

To_Start=$(grep -n -m 1 "HR" Tossed/length/TLD2R-TT.txt | cut -d : -f 1)

Simple reproducer to prove my point:

简单的复制器来证明我的观点:

To_Start=$(echo a:b | cut -d : -f 1)
echo $To_Start

yields:

产量:

a

回答by Jeff

I fixed the issue by changing from csh to bash, removing set echo (caused some weird issue by making all input variables into "echo")and changing from $(()) to $().

我通过从 csh 更改为 bash、删除 set echo(通过将所有输入变量设置为“echo”而导致一些奇怪的问题)以及从 $(()) 更改为 $()​​ 来解决该问题。