如果在bash脚本中使用命令?

时间:2018-04-17 08:36:27

标签: bash

我正在用bash编写脚本,我遇到了问题:

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

它给了我

  

错误:第16行:[[if:command not found

一切正常,直到我添加了这个if命令,如果$DN为空,我需要回显一条消息,否则回显另一条消息。

2 个答案:

答案 0 :(得分:2)

您似乎对Bash的一些基本概念(如管道(|)与复合命令(if[[)感到困惑。例如,awk '{print $1,$2}' | DN="$(grep DN)"可能无法达到预期效果:

$ echo $'a\nb'
a
b

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

请注意变量B未设置为"a"

此外,您的语法DN="$(grep DN)" | [[if [[!DN]]; echo "All Good"完全是胡说八道。最好先阅读一些介绍。然后你可以继续:

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

答案 1 :(得分:0)

更改您的if条件,如下所示。您的if条件语法不正确,then部分也缺失。我刚刚纠正了你需要再次检查的if条件。

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