用于输出函数结果的 Bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6627943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:20:10  来源:igfitidea点击:

Bash script to output function result

bashscriptinghudsonjenkins

提问by Greg R

I have a bash shell script executed by Jenkins / Hudson. For some reason when I create a function, the output of that function is not logged back to the console. This is an example of my code:

我有一个由 Jenkins / Hudson 执行的 bash shell 脚本。出于某种原因,当我创建一个函数时,该函数的输出不会记录回控制台。这是我的代码示例:

EDIT!!!- this culprit here is SSH... Is there a way to force its output back to console?

编辑!!!- 这里的罪魁祸首是 SSH... 有没有办法将其输出强制返回到控制台?

perform_task()
{
   ssh [email protected] pwd
}

echo "Starting a task";
perform_task || { echo "The Task Failed"; exit 1; } 

The output in the console is:

控制台中的输出是:

"Starting a task"

“开始任务”

if I move the commands outside of the function, I can see their output.

如果我将命令移到函数之外,我可以看到它们的输出。

Help on this would be greatly appreciated!

对此的帮助将不胜感激!

回答by Greg R

I partially solved the problem by getting the script to echo the command:

我通过让脚本回显命令部分解决了这个问题:

#!/bin/bash -ex

#!/bin/bash -ex

This still hides the output of that command, but at least I have insights about what's being run

这仍然隐藏了该命令的输出,但至少我对正在运行的内容有所了解

回答by Sagar

I just copied your function, added #!/bin/bash -eto the beginning of and pasted it into the "Execute Shell" of Jenkins.

我刚刚复制了您的函数,添加#!/bin/bash -e到的开头并将其粘贴到 Jenkins 的“执行外壳”中。

It worked fine!

它工作得很好!

Is your bash executable actually located at /bin? What OS are you running the script on?

您的 bash 可执行文件实际上位于/bin? 你在什么操作系统上运行脚本?

Building remotely on slave_1
[test] $ /bin/bash -xe /tmp/hudson1206345540964396738.sh
+ echo 'Starting a task'
Starting a task
+ perform_task
+ ssh slave_2 pwd
/home/jenkins
Finished: SUCCESS

回答by arkigos

Not sure about Jenkins or all that, but this worked for me:

不确定詹金斯或所有这些,但这对我有用:

perform_task()
{
    ls -al
    ps aux
    pwd
}

echo "Starting a task"
perform_task || ( echo "The Task Failed" ; exit 1 )

回答by Op De Cirkel

add #!/bin/bashas first line of the file The reason is the basic bourne shell(/bin/sh) does not support some of the features you use.

添加#!/bin/bash为文件的第一行 原因是基本的bourne shell(/bin/sh) 不支持您使用的某些功能。