Kaveen K
Kaveen K

Reputation: 33

Check for errors in a script command

How do I check for an error in a command before I run it, for example, if i wanted to run an iptables command, but say someone input something wrong into the variable of the script I made, for example "asdiojaosdi" for the $port variable, and when the script tries to plug that into the iptables command, it returns an error, I want it to echo "Error"

I want syntax to check this HUGE command

    iptables -t nat -A PREROUTING -p tcp -d $filip --dport $port -j DNAT --to-destination $cusip && iptables -A FORWARD -p tcp -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT && iptables -t nat -A POSTROUTING -d $cusip -j SNAT --to-source $secip && iptables -t nat -A POSTROUTING -j SNAT --to-source $filip

Upvotes: 0

Views: 148

Answers (1)

alk
alk

Reputation: 70981

In IXish environments, programs commonly return a value different from 0 in case of failure. Error messages are expected to be logged to standard error, which can be captured via redirecting file descriptor 2.

You can test for this like so:

#!/bin/bash

program option1 option2 2>error.log.$$
result=$? 
if [ $result -ne 0 ]; then
  echo program failed with result=$result: $(cat error.log.$$)
  rm error.log.$$
fi

Upvotes: 1

Related Questions