我有2个Shell脚本。 script_1.sh
和script_2.sh
都具有可执行权限。
我在script_1.sh
中有一种方法可以将echo语句记录到日志文件中。
以下是script_1.sh
#!/bin/sh
log() {
/bin/echo $1 >> /path/to/theLogFile
}
TEST_VALUE=10
log "Logging a test value which says $TEST_VALUE"
# Calling script_2
/path/to/script_2
以下是script_2.sh
#!/bin/sh
echo "This is logging from script 2"
问题:
echo
中script_1.sh
的所有内容都会进入theLogFile
。但是显然script_2.sh
中什么也没有。我的问题是如何从script_2.sh
调用script_2,以便将echo
中的所有script_2.sh
语句也添加到theLogFile
中,并使用方法{{1 }}来自script_1 。
我应该做这样的事情吗?
log
还是有更好的方法?
答案 0 :(得分:1)
如果要通过脚本功能处理script2中的所有标准输出,请在script1.sh
中使用bash
:
#!/usr/bin/env bash
logit() {
command echo "$@" >> theLogFile
}
# export function definition
declare -fx logit
# Calling script_2 and redirect all stdout to logit function
(exec > >(logit "$(cat)"; exit); ./script2.sh)
# this will still be on stdout
echo "foo bar"
答案 1 :(得分:1)
替代方法:
script_1.sh
#!/bin/sh
exec >> theLogFile # redirect all stdout (I recommend stderr too... just add 2>&1)
TEST_VALUE=10
echo "Logging a test value which says $TEST_VALUE"
# Calling script_2
. script_2.sh # source the second script so it runs with the same env
script_2.sh
#!/bin/sh
echo "This is logging from script 2"
输出:
Logging a test value which says 10
This is logging from script 2
script_1.sh
#!/bin/sh
log() { echo "$@"; } >> theLogFile
TEST_VALUE=10
log "Logging a test value which says $TEST_VALUE"
# Calling script_2
log "$(script_2.sh)" # pass ALL the output as a single formatted string