Search a multi-line shell command output and execute logic based on result

The following is a multi-line shell command example:

$cargo build
   Compiling prawn v0.1.0 (/Users/ag/rust/prawn)
error[E0433]: failed to resolve: could not find `setup_panix` in `human_panic`
  --> src/main.rs:14:22
   |
14 |         human_panic::setup_panix!();
   |                      ^^^^^^^^^^^ could not find `setup_panix` in `human_panic`

error[E0412]: cannot find type `DGConfig` in crate `prawn`
  --> src/main.rs:25:27
   |
25 |     let db_config: prawn::DGConfig = envy::from_env().unwrap_or_else(|err| {
   |                           ^^^^^^^^ help: a struct with a similar name exists: `DBConfig`

error: aborting due to 2 previous errors

What I would like to accomplish here is to use the above multi-lines returned by cargo build command. Search all multi-lines for error[] substrings and store the count in a variable so the result can be used to handle another case logic.

Ideally, I want to accomplish something along the following code block:

function cargo_watch_notify() {
  echo "Watching for .rs file changes..."

  count=0
  "$(echo cargo build | egrep -w 'error' | ls -c >>>$count)"
  if [ $count -ge 1 ]; then
    growlnotify --title "Error" --message "Compiler found $count errors!"
  else
    growlnotify --title "Success" --message "Cargo build compiled successfully!"
  fi
  exit 1;
}

I realize the above block is broken. This is just what I have to work with for the moment. The only difference in my example is that I need to search for error and brackets strings and not the error string by itself. i.e. error[E0412] the top cargo build command should return a count of 2

Hi, try something like:

count=$( cargo build 2>&1 | grep -c 'error\[' )
1 Like

Thanks, this works! :slight_smile:

--- Post updated at 09:54 PM ---

A bit of an unrelated question, the snippet mentioned by Scrutinizer works when calling cargo build . If I use a hot-reload tool such as cargo-watch as my initial command, it does not work. I was reading the documents for cargo-watch and it seems to be built on top of watchexec , not sure if that blocks I/O somehow? Does anyone know how I can get the grep command to work with cargo watch ? What is stopping it from functioning as intended?