Search code examples
bashnamed-pipes

Invalid identifier for named pipe ... "not a valid identifier"


I have the following call to create a named pipe:

mkfifo "$HOME/.quicklock/ql_named_pipe";

then I read from the named pipe:

while read line; do ql_on_named_pipe_msg "$line" "$$"; done < "$HOME/.quicklock/ql_named_pipe" &

but I get this error message:

./scripts/tsc.sh: line 23: read: `/Users/alexamil/.quicklock/ql_named_pipe': not a valid identifier

anyone know why that shouldn't work?


Solution

  • If you read the comments carefully, it turns out that the original code looked something like:

    my_named_pipe="$HOME/.quicklock/ql_named_pipe"
    
    …
    
    while read $my_named_pipe
    do
        …
    done < $my_named_pipe   # This redirection not 100% clearly stated
    

    This would indeed lead to the error 'invalid identifier'. The read command expects to be given variable names as arguments. When given the $my_named_pipe, it sees:

    while read /Users/whoever/.quicklock/ql_named_pipe
    

    and that most definitely is not a valid variable name.

    As proposed in the self-answer, a mostly reasonable alternative is:

    while read line
    do
        …
    done < $my_named_pipe
    

    The 'mostly' is there because there are issues with read in the POSIX sh — see also the Bash manual for read. You might prefer to use read -r (or there again, maybe you wouldn't).