写入输出流并从Shell脚本函数返回值 [英] write to output stream and returning value from shell script function

查看:277
本文介绍了写入输出流并从Shell脚本函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在shell脚本中,echo可用于从函数返回值. 但是,如果这些功能要打印一些消息. 然后,可以通过将其重定向到错误流来完成此操作. 下面是一个简化的示例:-

In shell script, echo can be used to return values from functions. But, if those functions want to print some messages. Then, this can be done by redirecting it to error stream. Below is a simplified example :-

#this is a function that returns a value, as well as
#print some messages
function logic(){
    echo >&2 "start of logic"
    echo >&2 "perform logic, to get value"

    echo "ok"
}

function smain(){
    local result=$(logic)

    echo "result is >$result<"

    if [ "$result" == "ok" ];then
        echo "script successful"
    else
        echo "script failed"
    fi
}

smain

下面是示例执行输出:-

Below is the sample execution output :-

sh sample.sh
start of logic
perform logic, to get value
result is >ok<
script successful

那很好. 但是当此脚本用作autosys作业时. 然后来自逻辑功能的消息最终会在错误流文件触发警报中出现.

That works fine. But when this script is used as a autosys job. then messages from logic functions ends up in error stream file triggering alerts.

有什么办法,可以将逻辑函数中的消息写入输出流,而不必将消息与返回值混合.

Is there any way, messages from logic function can be written to output stream and not mixing messages with return value.

-

#!/usr/bin/env bash

function Return(){
    printf -v "$1" '%s' '$*'
}

function logic() {
    local arg=$1
    local system=$2
    echo "start of logic"
    echo "all params are >$*<"
    echo "perform logic, to get value"
    echo >&2 "logic successfully completed"
    printf -v "$1" '%s' 'abraKaDabra'
}

function main() {
    local result='' ;  logic "$@" result

    printf 'result is >%s<\n' "$result"

    if [ "$result" = "ok" ]; then
        echo "script successful"
    else
        echo "script failed"
    fi

    echo >&2 "end of main"
}

main "$@"

输出:-

$

sh returnValueWithDebugging.sh abc xyz > out.log 2>err.log

$

cat err.log
logic successfully completed
end of main

$

cat out.log
start of logic
all params are >abc xyz result<
perform logic, to get value
result is ><
script failed

推荐答案

这项工作可以吗?:

#this is a function that returns a value, as well as                            
#print some messages                                                            
function logic(){
    echo "start of logic"
    echo "perform logic, to get value"

    echo "ok" >&2
}

function smain(){
    { local result=$( { { logic ; } 1>&3 ; } 2>&1); } 3>&1

    echo "result is >$result<"

    if [ "$result" == "ok" ];then
        echo "script successful"
    else
        echo "script failed"
    fi
}

smain

这篇关于写入输出流并从Shell脚本函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆