Redirect error message to /dev/null in if condition [closed]

I have the following if statement:

if [ "$sourcelast" = "$maxhostlast" ] || [ "$sourcelast" = "$minhostlast" ] || [ "$sourcelast" < "$maxhostlast" ] || [ "$sourcelast" > "$minhostlast" ] ;then ... fi

Now I want that the error message is sent to /dev/null every time an error occur.

How can I do this?

Answer

Before going further, you have to fix your syntax. > and < are shell redirection operators, not comparison operator inside old test [...]. In some shells, you can escape them < and > to archive string comparison, or using new test [[...]].

It sounds like you want numeric comparison in this case, so you should stick with standard operator -lt, -le, -gt, -ge:

if [ "$sourcelast" = "$maxhostlast" ]   ||
   [ "$sourcelast" = "$minhostlast" ]   ||
   [ "$sourcelast" -lt "$maxhostlast" ] ||
   [ "$sourcelast" -gt "$minhostlast" ]
then
  : "Do something"
fi

To redirect all error message from all conditions, you can simply wrap them in a subshell:

if (
     [ "$sourcelast" = "$maxhostlast" ]   ||
     [ "$sourcelast" = "$minhostlast" ]   ||
     [ "$sourcelast" -lt "$maxhostlast" ] ||
     [ "$sourcelast" -gt "$minhostlast" ]
   ) 2>/dev/null
then
  : "Do something"
fi

Leave a Reply

Your email address will not be published. Required fields are marked *