简体   繁体   English

读取终端线Bash脚本

[英]Reading Terminal Line Bash Script

I created a basic bash script to run another script I do not have control over. 我创建了一个基本的bash脚本来运行另一个我无法控制的脚本。

This second script will output the terminal text such as error codes that I want to use as input to the rest of my script. 第二个脚本将输出终端文本,例如我要用作其余脚本输入的错误代码。 I am very new to coding with bash scripts. 我对使用bash脚本编码非常陌生。 Is there a built in function that will read in whatever was just outputted onto the terminal and set it equal to an internal variable. 是否有一个内置函数可以读取刚刚输出到终端的任何内容,并将其设置为等于内部变量。

You could use '|' 您可以使用“ |” as suggested by beroe in the comments, and that will get the output of the first script as an input to the second script, but it will not be shown in the terminal anymore. 正如beroe在评论中所建议的那样,它将获得第一个脚本的输出作为第二个脚本的输入,但是它将不再显示在终端中。

Another option would be 'tee', which would also give it as an input to the rest of the script while still having it appear in the terminal. 另一个选项是“ tee”,它还可以将其作为脚本其余部分的输入,同时仍将其显示在终端中。

If you want to read the output of the other script line-by-line, you can do 如果要逐行读取其他脚本的输出,可以执行

/path/to/other/script.sh 2>&1 | while IFS= read -r line; do
    do_something_with "$line"
    # ...
done

There is lots of great information about bash here: https://stackoverflow.com/tags/bash/info 这里有很多有关bash的重要信息: https : //stackoverflow.com/tags/bash/info

You're asking about command substitution , a syntax in Bash and other shell languages that let you capture the stdout of a command pipeline. 您在询问命令替换 ,Bash和其他Shell语言中的语法,该语法可让您捕获命令管道的标准输出。

For example, this will capture the output of date and then output it as part of a larger string. 例如,这将捕获date的输出,然后将其作为较大字符串的一部分输出。

the_date=$(date)
echo "The current date is ${the_date}. What a time to be alive!"

You could even skip the variable assignment, and put the command substitution right in the string: 您甚至可以跳过变量分配,并将命令替换项直接放在字符串中:

echo "The current date is $(date). What a time to be alive!"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM