3

I use FreeBSD

> uname -sr
FreeBSD 6.3-RELEASE

When I query

> grep `whoami` /etc/passwd

It shows me the information I want:

enter image description here

But when I try getting it in a tcsh script:

#!/bin/tcsh
set login = `whoami`
echo $login

set query = `grep $login /etc/passwd`
echo $query

it brings me the following:

dolg_gr
echo: No match.

Why 'No match' ? How can I get the string it provides me at the command shell in the $query variable?

8
  • Can't you just use getent passwd `whoami` ?
    – Kusalananda
    Feb 28, 2021 at 11:51
  • Kusalananda, unfortunately, I'm told to get the string from /etc/passwd file.. I have to get it inside a variable from that file exactly. Feb 28, 2021 at 11:58
  • Are you aware that version 6.x was end-of-life over 10 years ago and we will be on version 13 any day now?
    – Rob
    Feb 28, 2021 at 12:22
  • It's all I've got, Rob. Feb 28, 2021 at 12:25
  • getent passwd would get it from the /etc/passwd file. It's safer as your grep would pick out irrelevant entries if your username was something like roo or nolo.
    – Kusalananda
    Feb 28, 2021 at 12:46

1 Answer 1

5

This isn't a problem with grep - it's a problem with the unquoted variable expansion in

echo $query

and the fact that the matched line returned by grep contains the globbing character *. In tcsh, the default behavior for unsuccessful globs is similar to bash's failglob option - the error is telling you that there is no filename match for your passwd string:

$ tcsh -c 'echo dol_gr:*:3291'
echo: No match.

As mentioned by Stéphane Chazelas, the right way to quote variable expansions in (t)csh is to use the q modifier. Also note that tcsh's `...` splits on SPC, TAB and NL when unquoted and on NL only when quoted:

set query = "`grep $login:q /etc/passwd`"
echo $query:q
3
  • Just to clarify, in general, it should be echo $query:q. echo "$query" won't work for values of $query that contain newline characters. echo "$query:q" won't work if it contains backslash followed by newline (and avoid echo for the usual reasons). But maybe the better advise here would be to stay away from (t)csh. Feb 28, 2021 at 16:42
  • Thanks @StéphaneChazelas - answer updated Feb 28, 2021 at 16:53
  • (for the record, that $login:q is not guaranteed to quote properly when inside those quoted backticks. See for instance: a=$'a\\\nb c' tcsh -c 'printf "<%s>\n" "`printf %s\\n $a:q`"' which removes the backslash and splits into a, b and c. I don't even know if it's possible to get it right here and have given up on tcsh for this kind of reason over 25 years ago). Feb 28, 2021 at 18:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .