3

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:

#!/bin/csh

set echo

grep -n -m 1 "HR${4}" Tossed/length${1}/TL${1}D2R${2}-${3}TT.txt | cut -d : -f 1

To_Start=$((grep -n -m 1 "HR${4}" Tossed/length${1}/TL${1}D2R${2}-${3}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?

Jeff
  • 695
  • 1
  • 8
  • 19
  • One problem: `set echo` is clearing whatever arguments you are passing to your script and setting `$1` to the string `echo`. It's not obvious what you intend by that line. – chepner Oct 05 '16 at 01:06
  • 1
    Your question is tagged [tag:bash] and your title includes the word "Bash" but your script seems to be using `csh`. At least, that's what the shebang line invokes. Could you please clarify and fix either the tag/title or the shebang so that they are consistent. – rici Oct 05 '16 at 03:39

2 Answers2

4

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 $().

Jeff
  • 695
  • 1
  • 8
  • 19
2

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

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

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

To_Start=$(grep -n -m 1 "HR${4}" Tossed/length${1}/TL${1}D2R${2}-${3}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
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Did it work for you? (of course using a different string and file) I still can't get it to work :( – Jeff Oct 04 '16 at 22:32
  • in a way: `$ To_Start=$(grep -n -m 1 "HR${4}" Tossed/length${1}/TL${1}D2R${2}-${3}TT.txt | cut -d : -f 1) grep: Tossed/length/TLD2R-TT.txt: No such file or directory.` I have added a standalone example to prove my point. ` – Jean-François Fabre Oct 04 '16 at 22:32
  • It works. It all works when I type it out on the command line but it doesn't work when I use it inside the script... What could that mean? And thank you for your help so far. – Jeff Oct 04 '16 at 22:40
  • @Jeff: Does *it doesn't work* mean that you still get *Illegal variable name*? If so, post your corrected script, otherwise it is impossible to discuss the issue. – user1934428 Oct 05 '16 at 06:24
  • @Jeff must be the next issue then. Noone said you only had _one_ problem :) – Jean-François Fabre Oct 05 '16 at 08:02