如何在shell脚本中使用if语句基于变量

时间:2017-04-13 19:39:55

标签: linux shell if-statement

对于shell脚本,变量是表名。

If the table name is test then execute

while IFS=',' read a; do drop.sh $a; done < abc

or else execute 

while IFS=',' read a; do create.sh $a; done < abc

我如何在Linux中实现这一目标

2 个答案:

答案 0 :(得分:1)

对于相同类型的多个条件,您还可以使用case

for table in test bla something; do

    case "$table" in
        test)
            echo actions for $table
            ;;
        bla)
            echo another actions for $table
            ;;
        *)
            echo actions for anything other as test or bla eg for $table
            ;;
    esac

done

从上面输出

actions for test
another actions for bla
actions for anything other as test or bla eg for something

e.g。对于你的情况,你可以写

table="test"

while IFS=, read -r a; do
        case "$table" in
                test) drop.sh "$a"  ;;
                *)  create.sh "$a"  ;;
        esac
done < abc

一些注意事项:

  • 除非您知道为什么不想要read -r
  • ,否则请始终使用-r
  • 始终引用"$a"
  • 等变量
  • while read - 对于这两种情况都是相同的abc,所以DRY(不要重复自己)并将while read...移到您的境外......

答案 1 :(得分:0)

你可以像这样使用if - else语句;

<div>
  <p>
    some text on here 1
    <i>
      some italic 
      <b>text</b>
      here
    </i> text text text
  </p>
  <b>
    some bold text on here
  </b>
</div>

<pre></pre>

在你的情况下

AddLastNameToAll()

有关详细信息,请参阅here,它是特定于bash的,但主要用于其他Linux shell。

修改正如comments中所述,以下是其他一些资源: