0

I have sophisticated bash script that uses "read -p"(stderr output) very often. And now I need to duplicate all script input from terminal into log file.

   tee file.log | script.sh

this command does'nt work carefully because ignores output to user. Example:

#!/bin/sh
echo "start"
read -p "input value: " val
echo $val
echo "finish"

Terminal run:

start
input value: 3
3
finish

Tee run:

# tee file.log | ./script.sh
start
3
3
finish
Andrey Burykin
  • 700
  • 11
  • 23

1 Answers1

2

No idea why you're using tee here. What I suspect is happening is it needs input, so waits for it, then pipes 3 to stdout

-p prompt
Display prompt, without a trailing newline, before attempting
to read any input. The prompt is displayed only if input is coming from a
terminal.

However input isn't sent from tty here so prompt is never printed. Still feels very weird for me to use tee here, but you can just use echo -n instead of the -p flag for read and it should work.

#!/bin/sh
echo "start"
echo -n "input value: "
read val
echo $val
echo "finish"

e.g.

> tee file.log | ./abovescript
start
input value: 3
3
finish

> cat file.log
3

Also not sure how to get tee to terminate properly from in-script here, so you need to press return key at end which of course causes newline.

That said, since it's an extra line each time anyway, seems worse than just be doing echo "$val" >> file.log each time, though a better option would be just to use a function

#!/bin/bash
r() {
  read -p "input value: " val
  echo "$val" >> file.log
  echo "$val"
}

echo "start"
val=$(r)
echo "$val"
echo "finish"
Reinstate Monica Please
  • 11,123
  • 3
  • 27
  • 48
  • you are right but maybe there is another way through exec 5>&0 at the beginning of script – Andrey Burykin Jan 23 '14 at 08:04
  • @andr3y How would you use fd 5? Edit: ok I think you mean read from fd 5 into the variable ... might work to print the prompt but you still have the problem of `tee` not terminating properly. – Reinstate Monica Please Jan 23 '14 at 08:10
  • Example for stdout duplicating: exec 5>&1 npipe=test.pipe trap "rm -f $npipe" EXIT mknod $npipe p tee <$npipe temp.tmp &exec 1>&- exec 1>$npipe – Andrey Burykin Jan 23 '14 at 08:15
  • @andr3y Honestly, you've lost me. Whatever it is, I'm of the opinion that using `tee` like this is way too hackish to ever be practical or where you can ever be positive of the results. function seems simple enough, and if it isn't I might switch to a language that has something like a dedicated `tee` module, ala perl – Reinstate Monica Please Jan 23 '14 at 08:22