测试是否已写入stdout

时间:2012-02-11 20:43:58

标签: bash shell sh

我有一个循环打印的脚本。我希望循环在第一次打印时与其他所有时间不同(即,如果有任何打印的话,它应该以不同的方式打印)。我想一个简单的方法是检查是否还有任何打印(即stdout已被写入)。有没有办法确定?

我知道我也可以写一个变量并测试它是否为空,但如果可以,我想避免使用变量。

3 个答案:

答案 0 :(得分:1)

我认为这会做你需要的。如果您在echo# THE SCRIPT ITSELF之间# ENDTHE FOLLOWING DATA HAS BEEN WRITTEN TO STDOUT将会打印STDOUT HAS NOT BEEN TOUCHED其他...

#!/bin/bash

readonly TMP=$(mktemp /tmp/test_XXXXXX)

exec 3<> "$TMP"   # open tmp file as fd 3
exec 4>&1         # save current value of stdout as fd 4
exec >&3          # redirect stdout to fd 3 (tmp file)

# THE SCRIPT ITSELF

echo Hello World

# END

exec >&4          # restore save stdout
exec 3>&-         # close tmp file

TMP_SIZE=$(stat -f %z "$TMP")
if [ $TMP_SIZE -gt 0 ]; then
    echo "THE FOLLOWING DATA HAS BEEN WRITTEN TO STDOUT"
    echo
    cat "$TMP"
else
    echo "STDOUT HAS NOT BEEN TOUCHED"
fi

rm "$TMP"

因此,脚本输出为:


THE FOLLOWING DATA HAS BEEN WRITTEN TO STDOUT

Hello World

如果您删除echo Hello World行:

STDOUT HAS NOT BEEN TOUCHED

如果你真的想在运行脚本时测试它,你也可以这样做: - )

#!/bin/bash

#FIRST ELSE
function echo_fl() {
    TMP_SIZE=$(stat -f %z "$TMP")
    if [ $TMP_SIZE -gt 0 ]; then
        echo $2
    else
        echo $1
    fi  
}

TMP=$(mktemp /tmp/test_XXXXXX)

exec 3 "$TMP"   # open tmp file as fd 3
exec 4>&1         # save current value of stdout as fd 4
exec >&3          # redirect stdout to fd 3 (tmp file)

# THE SCRIPT ITSELF

for f in fst snd trd; do
    echo_fl "$(echo $f | tr a-z A-Z)" "$f"
done

# END

exec >&4          # restore save stdout
exec 3>&-         # close tmp file

TMP_SIZE=$(stat -f %z "$TMP")
if [ $TMP_SIZE -gt 0 ]; then
    echo "THE FOLLOWING DATA HAS BEEN WRITTEN TO STDOUT"
    echo
    cat "$TMP"
else
    echo "STDOUT HAS NOT BEEN TOUCHED"
fi

rm "$TMP"

输出是:

THE FOLLOWING DATA HAS BEEN WRITTEN TO STDOUT

FST
snd
trd

如您所见:只有第一行(FST)有限制。这就是echo_fl函数为你做的事情:如果它是输出的第一行,如果回显第一个参数,如果它不是它回应第二个参数: - )

答案 1 :(得分:1)

很难说你在这里尝试做什么,但如果你的脚本打印到stdout,你可以简单地将它传递给perl:

yourcommand | perl -pe 'if ($. == 1) { print "First line is: $_" }'

这完全取决于您尝试进行的更改。

答案 2 :(得分:0)

您无法将-f选项与%z一起使用。行TMP_SIZE=$(stat -f %z "$TMP")生成一个长字符串,该字符串未通过if [ $TMP_SIZE -gt 0 ]中的测试。