0

I have a shell script (let's say test.sh) which prints out 16 values on screen and sometimes error messages on screen (because of upstream hardware issues). I want to count the number of lines on the screen and then save only when I have valid outputs. I am unable to do the both at same time.

I am new to the shell scripting , so I did something pretty basic

./test.sh | tee -a output1.txt       
A=./test.sh | wc -l

When I do this it doesn't save the length in A

./test.sh | tee -a output1.txt       
A=./test.sh | wc -l
John1024
  • 109,961
  • 14
  • 137
  • 171
Jani
  • 3
  • 2

1 Answers1

0

You can't do both at the same time. But you can do them one at a time.

I think you want to check whether ./test.sh prints 16 lines, and if so, save its output to a file. This does that:

output=$(./test.sh)  # Capture output from "./test.sh" as "$output"
line_count=$(wc -l <<< "$output")  # Count lines in "$output"

if (( line_count = 16 )); then  # Check if "$line_count" is 16
    tee -a output1.txt <<< "$output"  # Append "$output" to "output1.txt" and stdout
fi

Notes

  • cmd <<< str does the same thing as echo str | cmd.
  • (( line_count = 16 )) does the same thing as [[ $line_count -eq 16 ]]
wjandrea
  • 28,235
  • 9
  • 60
  • 81