简体   繁体   中英

Reading Terminal Line Bash Script

I created a basic bash script to run another script I do not have control over.

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. 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.

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.

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

You're asking about command substitution , a syntax in Bash and other shell languages that let you capture the stdout of a command pipeline.

For example, this will capture the output of date and then output it as part of a larger string.

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!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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