if else条件多次安装

时间:2014-05-22 08:49:38

标签: bash shell

我正在尝试使用此shell脚本创建蓝图,以在不同系统上安装不同的rpms并匹配系统类型。在这个例子中,我有两个名为centos1和suse1的系统。每个系统都有一个相应的资源ID存储在变量" id"并应运行与每个匹配的命令。所有系统名称都从名为vm.txt的文本文件中读取。

~]# cat vm.txt
centos1
suse1

~]# ./myscript.sh vm.txt

        #!/bin/bash
        for node in `cat $1`
        do
          # id is the resource id for each system listed in vm.txt
          id=`./test.sh get resource id --platform=$node`
          if [ $node == centos1 ]
          then
            echo `./install.sh resource $id centos1-httpd`
            echo `./install.sh resource $id centos1-gcc`
          elif [ $node == suse1 ]
          then
            echo `./install.sh resource $id suse1-httpd`
            echo `./install.sh resource $id suse1-gcc`
          else 
            echo "No packages found"
          fi
        done

展望未来我将不得不在脚本文件和安装标准中添加数百个系统。我不确定在这个脚本中使用if-else条件会导致编写更多代码行导致以后难以管理。有没有更好的方法来处理这个问题?我应该使用与if-else不同的条件来实现此目的吗?

PS:对不起这个基本问题。我仍然试着亲自动手编写脚本。

2 个答案:

答案 0 :(得分:0)

怎么样:

   #!/bin/bash
    while read -d $'\n' -r node;
    do
      # id is the resource id for each system listed in vm.txt
      id=`./test.sh get resource id --platform=$node`
      echo `./install.sh resource $id ${node}-httpd`
      echo `./install.sh resource $id ${node}-gcc`
    done < "$1"

为了取悦@choroba

   #!/bin/bash
    known_nodes=" centos1 suse1 " # leading and final space are important

    while read -d $'\n' -r node
    do
      if [[ " $node " =~ "$known_nodes" ]]; then
        # id is the resource id for each system listed in vm.txt
        id=`./test.sh get resource id --platform=$node`

        echo `./install.sh resource $id ${node}-httpd`
        echo `./install.sh resource $id ${node}-gcc`
      else
        echo "Don't know node ${node}. Skipping."
      fi
    done < "$1"

答案 1 :(得分:0)

您可以使用caseelseif更容易添加发行版:

tiago@dell:/tmp$ cat myscript.sh 
#! /bin/bash

for node in $(cat $1); do
    id=$(./test.sh get resource id --platform=$node)
    case $node in
        centos1)
            echo "./install.sh resource $id centos1-httpd"
            echo "./install.sh resource $id centos1-gcc"    
        ;;

        suse1)
            echo "./install.sh resource $id suse1-httpd"
            echo "./install.sh resource $id suse1-gcc"
        ;;    

        *)
            echo "No Packages found"
        ;;
    esac
done

执行:

tiago@dell:/tmp$ bash myscript.sh  <(echo -e 'centos1\nsuse1\nfedora')
./install.sh resource  centos1-httpd
./install.sh resource  centos1-gcc
./install.sh resource  suse1-httpd
./install.sh resource  suse1-gcc
No Packages found