Salim
Salim

Reputation: 5

How to use if inside a command in bash script?

I am writing a script in bash, and I have a problem with it:

select opt in "${options[@]}"
do
    case $opt in
        "1) Check Cassandra Status.")
         ssh skyusr@"$IP" "export JAVA_HOME=/opt/mesosphere && /var/lib/mesos/slave/slaves/*/frameworks/*/executors/*/runs/latest/apache-cassandra-3.0.10/bin/nodetool -p 7199 status" | sed -n '6,10p' | awk '{print $1,$2}' | DN="$(grep DN)" | [[if [[!DN]]; echo "All Good" else "Node(s) "$DN" is Down" ;fi]]
            ;;
        "2) Run Repair on all nodes.")
            echo "you chose choice 2"
            ;;
        "3) Run Refresh on specific keyspace/Table.")
            echo "you chose choice 3"
            ;;
        "4) Optional")
            echo "This option disabled"
            ;;
        "Quit")
            break
            ;;
        *) echo invalid option;;
    esac
done

It gives me

error:line 16: [[if: command not found

All was working until I added this if command, I need to echo a message if $DN is empty else echo another message .

Upvotes: 0

Views: 195

Answers (2)

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5591

Change your if condition like below. Your if condition syntax is not correct and then part is also missing. I have just corrected the if condition rest you need to check again.

if [[ DN == "" ]]; then echo "All Good" else echo "Node(s) $DN is Down" ; fi

Upvotes: 0

Micha Wiedenmann
Micha Wiedenmann

Reputation: 20823

You seem to be confused about some of Bash's basic concepts like pipelines (|) versus compound commands (if and [[). For example awk '{print $1,$2}' | DN="$(grep DN)" does probably not do what you expect:

$ echo $'a\nb'
a
b

$ echo $'a\nb' | B=$(grep a)
$ echo $B

Note how the variable B is not set to "a".

Furthermore your syntax DN="$(grep DN)" | [[if [[!DN]]; echo "All Good" is complete nonsense. You best start by reading some introduction. Then you can continue along the lines of:

A=$(....)
[[ -z $A ]] && echo "A is empty"
# or
if [[ -z $A ]] then echo "A is empty"; else echo "A is not empty"; fi

Upvotes: 2

Related Questions