Check the output of "make" and exit the bash script if it does not work

However, I'm no more than bash. I wrote a bash script that will execute my cmake, make and C ++ executable.

#! /bin/bash cmake . make ./pcl_visualizer_demo <-- This is my executable 

This works fine if my code is not compiled, it executes the old executable and leaves me in a mess. I was hoping to output the output of make to an if statement, which only runs the executable when make is successful. I have tried many bash things from other posts here on stackoverflow. Some problems look like this: the output of make is not a string, for example:

 OUTPUT = make echo $OUTPUT 

gives:

 [100%] Built target pcl_visualizer_demo 

But does not work with:

 if [`expr match "$OUTPUT" '[100%] -eq 5]; then ./pcl_visulizer_demo; fi 

Not to mention that there may be several errors in this line. I also tried:

 if [diff <(echo "$OUTPUT") <(echo '[100%] Built target pcl_visualizer_demo' -n]; then ./pcl_visulizer_demo; fi 

Again, perhaps I am not implementing it correctly. Any help

+6
source share
4 answers

Just check the make exit code:

 cmake . || exit 1 make || exit 1 ./pcl_visualizer_demo 
+18
source

you can use

 set -e 

at the beginning of your shell script

 #!/bin/bash set -e cmake . make ./pcl_visualizer_demo 

From 'help set'

 -e Exit immediately if a command exits with a non-zero status. 

What the default means: for any error

+3
source

You should probably check the make exit code, for example.

 if [ $? -eq 0 ] then echo "Successfully made" else echo "Could not compile" >&2 fi 

and exit accordingly. By convention, exit code 0 indicates success. If you have multiple executables and want to help out if someone returns an unnecessary exit code, you can tell bash to do this only with the -e option, for example.

  #!/usr/bin/bash -e 

Just make sure the executables ( make and cmake ) comply with this convention. See here for more information on exit codes.

+2
source

You can try to determine that the "exit status" of your previous bash command used "$?". Usually, an assembly that is unsuccessful will end with a non-zero status. Double check that this is true in your case, an echo of '$?'

Then use the normal if statement to work correctly.

$? reads the exit status of the last command executed. After the function returns, $? gives the exit status of the last command executed in a function. This is a bash way of providing functions a "return value".,.
After the script completes, $? from the command line gives the status script, i.e. the last command executed in a script, which, by agreement, is 0 for success or an integer in the range 1 - 255 on error.

Source: http://www.tldp.org/LDP/abs/html/exit-status.html

0
source

Source: https://habr.com/ru/post/989354/


All Articles