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
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"
around "$line"
are to prevent glob expansion, and to prevent replacing whitespace sequences with a single spaceYou 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.
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.
grep
purely as a shell script? Your script, if you invoke it like you show, does output something: an empty line.read
to read fromstdin
. If you want to use the data in another command, which reads from stdin, you can simply call it.cat /dev/stdin
orgrep -o '.' /dev/stdin
. Do not forget to specify the path to the script:./my_script