shell - how to properly use comparison operators within an if-then statement -
what best way perform check/test output comes query called within shell script?
for example, have variable performs query:
export chk=`psql -h localhost -p 5432 -u foo foobar --tuples-only -c "select 1 result pg_database datname='foo_bar_1234'";` it return either 1=exist or empty string=not exist.
i tried code, doesn't work expected keeps going db not exist everytime if value empty string. tried "1" still same results.
if [ "$chck" = 1 ]; echo "db exists." exit 1 else echo "db not exist." fi how correct and/or better way check this?
from comments sounds output of 1 may surrounded whitespace, 1 solution trim leading , trailing whitespace first, using read:
#!/usr/bin/env bash export chck=$(psql -h localhost -p 5432 -u foo foobar --tuples-only -c "select 1 result pg_database datname='foo_bar_1234'") # remove leading , trailing whitespace value. read -r chck <<<"$chck" # whitespace trimmed, comparison string '1' should work intended. if [[ $chck == '1' ]]; echo "db exists." exit 1 else echo "db not exist." fi - note unless need add
$chckenvironment child processes can see it, there's no need useexport. read -r chck <<<"$chck"takes advantage of factreaddefault removes leading , trailing whitespace input when reading single variable:-rensures\instances in input left untouched - not strictly necessary here, practice in general.<<<so-calledbashhere-string, sends argument via stdin command @ hand -readreads from.<<<single-line alternative posix-compliant here-documents.
another option use bash's regex-matching operator, =~, bypasses need trim whitespace first:
if [[ $chck =~ ^[[:space:]]*1[[:space:]]*$ ]]; # ... less stringently, if presence of 1 anywhere in string sufficient, using bash's pattern matching:
if [[ $chck == *1* ]]; # ... even less stringently, if string empty (as opposed blank, meaning composed of whitespace characters) in non-existence case:
if [[ -n $chck ]]; # ... matches *any nonempty* string since question generically tagged shell, here's posix-compliant equivalent of first solution:
export chck=$(psql -h localhost -p 5432 -u foo foobar --tuples-only -c "select 1 result pg_database datname='foo_bar_1234'") # remove leading , trailing whitespace value. read -r chck <<eof $chck eof # whitespace trimmed, comparison string '1' should work intended. if [ "$chck" = '1' ]; echo "db exists." exit 1 else echo "db not exist." fi - note use of here-document (
<<) instead of bash-specific here-string (<<<), ,[ ... ](single-bracket) conditional form double-quoted variable reference.
Comments
Post a Comment