如何将echo语句从被调用的shell脚本传递到调用者脚本中方法的参数中

时间:2019-04-29 10:34:52

标签: linux bash shell

我有2个Shell脚本。 script_1.shscript_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"

问题:
echoscript_1.sh的所有内容都会进入theLogFile。但是显然script_2.sh中什么也没有。我的问题是如何从script_2.sh调用script_2,以便将echo中的所有script_2.sh语句也添加到theLogFile中,并使用方法{{1 }}来自script_1 。
我应该做这样的事情吗?

log

还是有更好的方法?

2 个答案:

答案 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