1
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
4

1 回答 1

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"
...
于 2012-10-11T09:19:26.370 回答