3

I want to pipe the output of one command to another script. In this other script I want to check whether the input was empty or just consists of spaces. If this is the case, I'll ignore it. Otherwise, I want all the input to be forwarded to another few commands.

For more clarity, I'll run something like cat input.txt | ./script.sh where input.txt looks like

line 1
line 2
line 3

and script.sh currently looks like:

read input_text

if [ -z "$input_text" ]
    # ignore emtpy input
    then exit 0
else
    # do something here with the input
fi

The problem is that in this scenario, the first line of the input "line 1" is read into the input_text variable and therefore not forwarded with the rest of the input (which then solely consists of lines 2 and 3) into the code following after else.

So, how can I first check whether the input consists of more than just empty spaces and then forward the whole input to another command?

2

That would mean you want to forward the input as soon as you see a non-blank character.

awk -v cmd='otherCommand' '
  forward {print | cmd; next}
  {initial_output = initial_output $0 "\n"}
  NF {printf "%s", initial_output | cmd; forward = 1}'

Example:

$ printf '%b\n' ' ' '' '\t' | awk -v cmd='echo START; sed "s/.*/<&>/"' '
  forward {print | cmd; next}
  {initial_output = initial_output $0 "\n"}
  NF {printf "%s", initial_output | cmd; forward = 1}'
$ printf '%b\n' ' ' '' '\t' something | awk -v cmd='echo START; sed "s/.*/<&>/"' '
  forward {print | cmd; next}
  {initial_output = initial_output $0 "\n"}
  NF {printf "%s", initial_output | cmd; forward = 1}'
START
< >
<>
<       >
<something>
  • This looks like it does what I want it to do. Would you provide a short explanation of what's happening there? – Matthias Nov 27 '15 at 18:14
0
#!/bin/sh
{   tee /dev/fd/3 <&4&:|
    grep -q '[^[:space:]]' &&
    cat - /dev/fd/4 <&3
}   3<<"" 4<&0 | another_few_commands

# cause i dont know how else to end this with a blank line
-1

how about using a loop? (this will end on any empty or space-only lines)

#!/bin/sh
while read input_text; do
  [ -z "$input_text" ] && break
  # do something with the non-blank input
done
exit 0
  • It is necessary that the input is forwarded "en block" to the next command, not just line by line. Is there a way accomplish that? – Matthias Nov 27 '15 at 12:28
  • This strips off whitespace at the beginning and at the end of each line, and also performs some backslash expansion. – Gilles Nov 27 '15 at 22:32

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.