将参数传递给bash脚本

时间:2012-10-11 09:15:46

标签: bash shell

linux 3.5.6-1.fc17.x86_64
GNU bash, version 4.2.37

您好,

我有以下bash脚本文件。我用来测试我的程序。但是,我希望能够使用和不使用valgrind进行测试。所以我从命令行'valgrind'得到参数并在if语句中进行比较。但是,我的测试用例会随着时间的推移而变大,我将不得不在if-else中重复大量代码。有没有办法尽量减少这个if-else?

非常感谢任何建议,

#!/bin/bash

# Abort on error
set -e

echo $1

if [ "$1" == "valgrind" ]; then
    echo "TEST STARTED RUNNING WITH VALGRIND"
    echo "TEST CREATE DATABASE"
    valgrind ./db db.dat c
    echo "TEST CREATE DATABASE OK"

    echo "TEST INSERT"
    valgrind ./db db.dat s 1 steve steve@mail.com
    valgrind ./db db.dat s 2 ben ben@live.com
    valgrind ./db db.dat s 3 lisa lisalow@mailcity.com
    echo "TEST INSERT OK"

    echo "TEST LIST"
    valgrind ./db db.dat l
    echo "TEST LIST OK"

    echo "TEST DELETE"
    valgrind ./db db.dat d 2
    echo "TEST DELETE OK"

    echo "TEST LIST"
    valgrind ./db db.dat l
    echo "TEST LIST OK"

    echo "TEST FETCH"
    valgrind ./db db.dat g 2
    valgrind ./db db.dat g 3
    echo "TEST FETCH OK"

    echo "TEST COMPLETED OK"
else
    echo "TEST STARTED"
    echo "TEST CREATE DATABASE"
    ./db db.dat c
    echo "TEST CREATE DATABASE OK"

    echo "TEST INSERT"
    ./db db.dat s 1 steve steve@mail.com
    ./db db.dat s 2 ben ben@live.com
    ./db db.dat s 3 lisa lisalow@mailcity.com
    echo "TEST INSERT OK"

    echo "TEST LIST"
    ./db db.dat l
    echo "TEST LIST OK"

    echo "TEST DELETE"
    ./db db.dat d 2
    echo "TEST DELETE OK"

    echo "TEST LIST"
    ./db db.dat l
    echo "TEST LIST OK"

    echo "TEST FETCH"
    ./db db.dat g 2
    ./db db.dat g 3
    echo "TEST FETCH OK"

    echo "TEST COMPLETED OK"
fi

1 个答案:

答案 0 :(得分:4)

我会这样做

VALGRIND=""
if [ "$1" == "valgrind" ]
then
  VALGRIND="valgrind"
fi

echo "TEST STARTED"
echo "TEST CREATE DATABASE"
$VALGRIND ./db db.dat c
echo "TEST CREATE DATABASE OK"
...