Search code examples
tcsh

tcsh couldn't echo word with square bracket


I have a list of data below

%cat data
a
b[1]
c[2]
d

and i try to echo each line using the command below:

%foreach aa ( `cat data` )
foreach? echo $aa
foreach? end
a
echo: No match

can somebody explain what is going on with the echo cmd and how to fix it? Thanks.


Solution

  • When you do

    echo $aa
    

    and $aa contains b[1], the shell tries to handle the [ and ] metacharacters after it expands the value of the variable. Since you (probably) have nothing in your current directory that matches b[1], you get an error.

    You need to quote the variable reference. Replace

    echo $aa
    

    by either

    echo "$aa"
    

    or

    echo $aa:q
    

    (The :q syntax is specific to csh and tcsh; double quotes work similarly in most shells, including csh-derived shells and sh-derived shells like bash).