-2

Let's take example. There are 2 scripts,

  1. main.sh
  2. invoke.sh

I want to execute invoke.sh script from main.sh. When the script invoke.sh executes from main.sh, invoke.sh produces below output on Linux terminal,

jbhaijy@ubuntu:~$./main.sh

Resources available on this system:
  CPU TYPE: x86_64
  Num cores: 4
  Total RAM: 15979 MB
  Avail RAM: 13299 MB
  Total disk: 343 GB
  Avail disk: 60 GB
  GPU Type: None
  State: unregistered

I want to check specific string i.e. State: registered or State: unregistered from the above(invoke.sh) output & returned State to main.sh. Based on the State string, main.sh will inform the user that device is registered or unregistered.

Questions:

  1. How we can check particular State string i.e. "registered" or "unregistered"?
  2. How we can returned State string to main.sh?

Hope my question gives enough clarity to you.

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
Yunus
  • 3
  • 3
  • Hints: `grep -q pattern`. Its exits status is OK if the pattern occurs. Use it in main.sh to call invoke.sh and check its output like `if ./invoke.sh | grep -q unregistered; then echo "do something here"; else echo "do something else"; fi;`. – Peter - Reinstate Monica Sep 01 '22 at 10:53
  • Thanks @Peter-ReinstateMonica. It seems string search is working but I am not getting the invoke.sh script whole output on the console. Pls suggest how can we modify your command to get whole output along with particular string output. Thanks again. – Yunus Sep 01 '22 at 13:37
  • So you want the entire output visible on the console to the user but *also* take some action? – Peter - Reinstate Monica Sep 01 '22 at 13:43
  • I wrote an answer for that. – Peter - Reinstate Monica Sep 01 '22 at 14:02

1 Answers1

0

In order to determine whether a program or script output contains a string you pipe it through grep. grep -q is normally used for that; it will by design not output anything but only indicate by its exit status whether anything was found:

if ./invoke.sh | grep -q unregistered
    then echo "do something for an unregistered machine"
    else echo "do something else for a registered one"
fi

If you additionally want the entire output from invoke.sh on the screen, this answer suggested to tee it to /dev/tty. tee is a command that "splits" output, like a T-intersection, into two parts: One continues to stdout, the other one is written to a file. (This is often used to save output while at the same time watching it in real time.) Now unfortunately we need the stdout for grep, and we don't want any files; but *nix treats almost everything as a file, including your teletype console. The console is the pseudo file /dev/tty to which you can let tee write:

if ./invoke.sh | tee /dev/tty | grep -q unregistered
    then echo "do something here"
    else echo "do something else"
fi
Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62