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.

0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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 ?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.