1

Want to have a script to process screen prints as grep.
I can run it like: cat file.txt | my_script

Tried below script, it didn't print out anything.

#!/bin/bash
line=$@
echo $line 
11
  • I don't quite understand what it is you want to do. Do you want to implement grep purely as a shell script? Your script, if you invoke it like you show, does output something: an empty line.
    – Kusalananda
    Commented Jul 15, 2021 at 8:48
  • How to receive previous command piping output?
    – Fisher
    Commented Jul 15, 2021 at 9:20
  • Depends on what you want. One can use read to read from stdin. If you want to use the data in another command, which reads from stdin, you can simply call it.
    – ibuprofen
    Commented Jul 15, 2021 at 9:43
  • In the script: cat /dev/stdin or grep -o '.' /dev/stdin. Do not forget to specify the path to the script: ./my_script
    – nezabudka
    Commented Jul 15, 2021 at 9:58
  • why? why not just use grep in your script?
    – cas
    Commented Jul 15, 2021 at 10:50

2 Answers 2

0

Same idea as @glemco's answer but this version should be safe for special characters (excluding a NULL byte):

#!/bin/bash
while IFS= read -r line
do
  printf '%s\n' "$line"
done
  • IFS= is to prevent trimming the leading and trailing whitespace
  • -r is used to prevent backslash escapes to be processed
  • The quotes " around "$line" are to prevent glob expansion, and to prevent replacing whitespace sequences with a single space
0

You are trying to read from command line arguments ($@) while you should be reading from stdin. Basically the pipe attaches the first command's stdout to the second's stdin. A simple way how to do what you wanted in bash would be to use the read built-in command, line by line as in the example.

#!/bin/bash
while read line
do
  echo $line
done

Of course you can do whatever you want instead of echo.

1
  • 4
    A single cat as the body of the script would be safer, if you just want to pass the output through. Your code would remove flanking whitespace, multiple whitespace characters between words, and it would potentially also expand filename globbing patterns if these were fed into the script. Additionally, echo may interpret certain escape sequences, like \t and \n etc.
    – Kusalananda
    Commented Jul 15, 2021 at 9:54

You must log in to answer this question.

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