0

It has been awhile since I scripted. I was never good to begin with..

I am working on a script that would test an oracle DB connection.

testDB() {
    [[ $(tnsping $tnsName | grep -c WRONG)==1 ]] && return 1
    return 0
}

testDB
status="${?}"
echo "Status value= " $status

I am expecting a 0 value from my echo but somehow my status is showing 1 in my echo.

What am I doing wrong here?

EDIT2:

My original code was:

testDB() {
    [[ $(tnsping $tnsName | grep -c OK) -eq 1 ]] && return 1
    return 0
}

my $tnsName contains a correct value and the grep count would be 1, yet my functions returns 0.

sjsam
  • 21,411
  • 5
  • 55
  • 102
Kyle
  • 915
  • 8
  • 18
  • 34
  • Your intension with `[[ $(tnsping $tnsName | grep -c WRONG)==1 ]] && return 1` is not very clear. – sjsam Aug 05 '16 at 04:42
  • basically, i am hoping to grep -c OK from the tnsping. the count will be 1 if the tnsping is successful. the TNSPING should not contain any word called WRONG in the result.. so the count would be 0. – Kyle Aug 05 '16 at 04:43
  • 1
    @sjsam The immediate problem the OP wa having was the lack of whitespace around the equals signs, wasn't it? Your edit turns it into a different question; code edits in questions are always problematic - is the problem still reproducible after your change? – tripleee Aug 05 '16 at 07:27
  • @tripleee : Hmm,, Indeed i didn't notice that.. ;) – sjsam Aug 05 '16 at 07:37

2 Answers2

4

Variables not needed, nor grep -c. Just use grep -q (no output), to return a true/false flag:

testDB() {
    tnsping $tnsName | grep -q OK
    }

testDB
echo "Status value= " $?
agc
  • 7,973
  • 2
  • 29
  • 50
  • The `-q` option is handy ++ – sjsam Aug 05 '16 at 05:01
  • tried [[ $(tnsping $tnsName | grep -q WRONG) ]] && return 1 || return 0 . Function still returns 1/true even when it should be false – Kyle Aug 05 '16 at 05:32
  • The `[[` is completely superfluous. You want simply `testDB` or in longhand `if tnsping "$tnsName" | grep -q OK; then mumble; else dont; fi` – tripleee Aug 05 '16 at 06:13
  • @Kyle, with a util that's designed to return true and false exit codes, logic like `... && return1 || return 0` is *always* unnecessary. Suppose a util returns *true/false*, (e.g. `echo foo | grep -q bar && echo yes || echo no`), and you need *false/true*, just prefix a `!` (logical *not*) where needed, (e.g. `! echo foo | grep -q bar && echo yes || echo no`). – agc Aug 05 '16 at 12:02
0

Its the second line &&. It is a way to execute multiple statements together and works like the Boolean "and" in many other languages. This instructs the bash session to execute both the compound test command and the return 1 statement together.

I understand your intention is to return 1 is the test is true else return 0. If thats the case just write it that way.

testDB() { if [[ $(tnsping $tnsName | grep -c WRONG)==1 ]]; then return 1 else return 0 fi }

I hope that helps.

joydeep bhattacharjee
  • 1,249
  • 4
  • 16
  • 42