質問

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
役に立ちましたか?

解決

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"
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top