bash 中的重定向问题

问题描述 投票:0回答:1

所以我有一个表现得很奇怪的小测试脚本。这本来是我想做的一些测试的开始,但我什至无法让这个基本脚本正常运行。希望有人能发现这个问题,因为我已经尝试了很多其他方法来做到这一点,但它们都会导致同样的问题。

declare stdout_file=$(mktemp -u)
declare stderr_file=$(mktemp -u)
mkfifo "$stdout_file" "$stderr_file"

cleanup() {
    rm "$stdout_file" "$stderr_file" &>/dev/null
}

trap cleanup EXIT

sed 's/\(.*\)/    \1/' < "$stdout_file" &
sed 's/\(.*\)/    \1/' < "$stderr_file" >&2 &

fnc1() {
    echo "Executing function"
}

echo "Running test" 
fnc1 > $stdout_file 2> $stderr_file
echo "Done"

只需多次执行脚本即可获得各种输出。有趣的是,这些都不是正确的。

$ bash test.sh 
Running test
Done
    Executing function
$ bash test.sh 
Running test
Done
$     Executing function

是的,在上一个示例中,它实际上用脚本的输出替换了我键入的命令。

我每次都期待相同的结果,这本来应该是

$ bash test.sh 
Running test
    Executing function
Done
linux bash shell scripting
1个回答
0
投票

当您想将输出传递到应由函数处理的文件描述符或命名管道时,您应该使用

exec
语句。

这是一个简单的例子:

#!/usr/bin/env bash
fnc() { echo "Executing function"; }

echo "Running test"
# Make copies of stdout and stderr
exec 3>&1 4>&2
# Send stdout and stderr to sed
exec 1> >(sed 's/^/    /')
exec 2> >(sed 's/^/    /')
# execute function
fnc
# reset the file descriptors
exec 2>&4 1>&3
# close redundant file descriptors
exec 3>&- 4>&-
echo "Done"
© www.soinside.com 2019 - 2024. All rights reserved.