-1

As part of automation in gitlab ci.

I am running a terraform template and creating a linux machine.

After that, I need to run few commands on the remote machine. I am running those using the ssh remote command. But at the end, even if it is failure, it is showing as successful.

Please let me know how to setup this kind of environment. Installing any tool as a step is also feasible

Kalel
  • 134
  • 1
  • 4
  • 16

1 Answers1

1

To get the exit code of your command, please add echo $? to your command. If value of echo $? is greater than 0, this means command was not successful. In Linux, $? holds the exit code of the preceding command. This is best way to understand if the command succeeded and hence used in all the system level scripts designed for OS working.

Let's say your command is 'ifconfig'. To get proper status , please run the below command:

if ifconfig; 
then
  echo "Command successful"
else
  echo "Command exited with non-zero status code, failed"
fi

I hope this works for you.

nightWolf
  • 108
  • 6
  • 2
    [Why is testing “$?” to see if a command succeeded or not, an anti-pattern?](https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern) – tripleee Jun 06 '22 at 10:16
  • Yes, In Linux, `$?` holds the exit code of the preceding command. This is best way to understand if the command succeeded and hence used in all the system level scripts designed for OS working. – nightWolf Aug 19 '23 at 17:28
  • No, the linked question explains exactly why this is quite literally the _worst_ way. It's unnecessarily verbose and clunky when the shell already has built-in facilities for succinctly and idiomatically checking whether a command succeeded or not. – tripleee Aug 20 '23 at 06:50
  • @tripleee I have gone through the link and the method they have suggested is exactly using `$?` in backend. `if` checks the command's exit code only and based on that runs the next statement. And about the TRAPs, I don't think the output of `if` statement will be any different than that based of `$?`. If you check the below system script, it is using `$?` to capture exit code and then taken a decision based on the value captured in exit code variable. https://github.com/dracutdevs/dracut/blob/master/modules.d/35network-legacy/ifup.sh – nightWolf Aug 20 '23 at 10:23
  • I'm afraid I don't understand your comment. Are you agreeing with what I wrote, or trying to refute it? Unlike your answer here, the code you link to seems to generally use the normal idiomatic `if ifconfig` style. – tripleee Aug 20 '23 at 13:01
  • (... though the function `do_ipv6link` seems to have a bug; it fails to ever set `ret` to anything.) – tripleee Aug 20 '23 at 13:04