Handle isql Login failed in Bash script

61 views Asked by At

I want to catch the login failed in my shell script

Code looks like below

retval=`isql -S$envServer -U$GCMS_USERNAME -h -b << ENDSQL | grep -vE "^Password: $"
$GCMS_PASSWORD
set nocount on
GO
USE "mydb"
GO
USE "SELECT tname from MYTABLE"
GO
ENDSQL`
echo retval

So if Login fails i get Msg 4002, Level 14, State 1: Server 'MYSERVER': Login failed. CT-LIBRARY error: ct_connect(): protocol specific layer: external error: The attempt to connect to the server failed.

I want to catch this, so when this error comes is do exit and if it is sucess i can perform my other operations.

2

There are 2 answers

0
markp-fuso On

A quick test for the Msg string:

if [[ "${retval}" =~ "Msg" ]]
then
    # do stuff with error message (eg display to console, write to log file, etc)
    exit
fi

If the data from MYTABLE could contain the string Msg you can expand the test to a pattern that's sufficiently unique to match on just errors:

regex='Msg.*Level.*State'

if [[ "${retval}" =~ ${regex} ]]                # do *NOT* wrap ${regex} is double quotes otherwise the quotes will be processed literally
then
    # do stuff with error message (eg display to console, write to log file, etc)
    exit
fi
1
Anthony Albertina On

Every bash command has an exit code. "0" is good, anything else means the last run command errored. Therefore, you can check if it failed by adding this after the isql command:

if [[ $? -ne 0 ]]; then
  # Do something about it
fi