0

I have written an example code for reading the content of a file maitaining the end of line format using hack from the internet. I have called the shell file "pipeTesting" and the text file to display "textExample". "pipeTesting" works if I call the file as an argument of the shell script.

However, there are cases when files are retrieved via pipelines; if I provide the text to pipeTesting using a cat command, there are no arguments at all since echo $@ does not print anything. To note that I had to use -p /dev/stdin to create a case for pipeline usage and one for argument usage.

Is there a way to display the content of the file maitaining the end of the line in case of a pipeline?

thank you.

The code looks something like this:

#!/bin/bash

if [ -p /dev/stdin ]; then
    echo $@
else
    while read
    do
        echo $REPLY
    done < $1
fi
exit 0

Its application is:

$ cat textExample.txt
Much I marvelled this ungainly fowl to hear discourse so plainly,
Though its answer little meaning- little relevancy bore;
For we cannot help agreeing that no living human being
Ever yet was blessed with seeing bird above his chamber door-
Bird or beast upon the sculptured bust above his chamber door,
With such name as "Nevermore."
$ pipeTester textExample.txt 
Much I marvelled this ungainly fowl to hear discourse so plainly,
Though its answer little meaning- little relevancy bore;
For we cannot help agreeing that no living human being
Ever yet was blessed with seeing bird above his chamber door-
Bird or beast upon the sculptured bust above his chamber door,
With such name as "Nevermore."
$ cat textExample.txt | pipeTester 
_
4
#!/bin/sh

infile=${1--}

cat "$infile"

That is, set the infile variable to the name of the first argument, but if that's not available, set it to -. cat with - as input file name will read from standard input (i.e. from a pipe or a redirection).


Shorter:

#!/bin/sh

cat -- "${1--}"

or, as Stéphane points out,

cat -- "$@"

which would additionally allow you to give multiple filenames on the command line.


Shorter still:

alias PipeTester=cat

What you're doing is more or less a reimplementation of cat. Your PipeTester script may in fact be replaced by cat and the above does that by means of an alias.

1
  • 1
    or cat -- ${1+"$1"} or cat -- "$@" (also exec cat -- "$@" for those sh implementations that don't do the optimisation by themselves). – Stéphane Chazelas Mar 12 '18 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.