0

I need to catch any invalid credentials while connecting to MariaDB, and overwrite the stderr stream explaining the error.

I have tried to use the following since it seemed to be the easiest and shortest code, but the database throws it's own error instead of displaying mine so I do not think the condition is even working.

right after the mysql command

if [ "$?" -eq 0 ]; then
    echo "There is something wrong with the arguments provided">&2
    exit 2
else
    : #some code
fi

TABLES=$(mysql --skip-column-name -u $USER -pPASSWORD $DB -e "SHOW TABLES;" | grep -v '+' | cut -d' ' -f2)

if [ "$?" -eq- 0 ]; then
    echo "There is something wrong with the arguments provided">&2
    exit 2
else
    : #some code
fi

I was expecting to see my stderr message appearing instead it is showing the mariadb error message on the screen.

1 Answers1

1

The exit status of a pipeline is the status of the last command in the pipeline. So in your case, it's the status of cut, not mysql.

You can use the PIPESTATUS array to get the exit status of other commands in the pipeline. However, this is tricky when the pipeline is in a command substitution, because you need PIPESTATUS from the subshell. See Pipe status after command substitution

If you don't want to see the database error message, you need to redirect stderr.

You need to check if the status is not 0. In the shell, 0 means success.

TABLES=$(mysql --skip-column-name -u $USER -pPASSWORD $DB -e "SHOW TABLES;" 2>/dev/null | grep -v '+' | cut -d' ' -f2; echo ": ${PIPESTATUS[0]}")
status=${TABLES##*: }
if [ $status -ne 0 ]
then
    echo "There is something wrong with the arguments provided">&2
    exit 2
else
    # Remove the appended status
    TABLES=${TABLES%:*}
    TABLES=${TABLES%$'\n'}
fi
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • thanks, it is now working. However what about a mysql command which has a > $TABLE.desc near the end, can i just check the $? or will it also report the > $TABLE.desc operation ? – Novice Programmer Aug 08 '19 at 00:30
  • That should work as desired. `$?` will be `0` if the command is successful AND it was able to write to the file. If either fails you'll get a non-zero, status. – Barmar Aug 08 '19 at 00:33