当前位置: 动力学知识库 > 问答 > 编程问答 >

linux - How to duplicate stdin into file

问题描述:

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"
分享给朋友:
您可能感兴趣的文章:
随机阅读: