首页 > 解决方案 > 使用带有条件的选项标志(shell 脚本)

问题描述

我的 shell 脚本文件中有这个命令:

docker exec dev-wordpress $phpunitPath \
  --configuration $configurationPath \
  --testsuit $testsuit \
  --group $group \
  --testdox

如果我将“testsuit”和“group”设置为命令行选项,它就可以工作。'testsuit' 和 'group' 选项只有在这些变量有价值时才应该使用。'testdox' 的相同问题可以通过 'if-else' 解决,但当我想对 3 个不同的选项做同样的事情时,这不是一个好方法。

如果 $group 变量中没有值,如何避免使用“--group”选项?

#!/bin/zsh
phpunit="/var/www/html/wp-content/plugins/irea/api/src/vendor/bin/phpunit"
configuration="/var/www/html/wp-content/plugins/irea/api/tests/phpunit.xml"
testdox=
filter=
testsuite=
group=

while [ "$1" != "" ]; do
    case $1 in
        --group )       shift
                        group="--group $1"
                        ;;
        --testsuite )   shift
                        testsuite="--testsuite $1"
                        ;;
        --filter )      shift
                        filter="--filter $1"
                        ;;
        --testdox )     testdox="--testdox"
                        ;;
    esac
    shift
done

docker exec irea-wordpress $phpunit \
  --configuration $configuration \
  $testsuite \
  $group \
  $filter \
  $testdox

标签: bashshellcommand-linephpunit

解决方案


您可以使用参数扩展:

docker exec dev-wordpress "$phpunitPath" \
  --configuration "$configurationPath" \
  ${testsuit:+--testsuit "$testsuit"} \
  ${group:+--group "$group"} \
  --testdox

这个脚本应该适用于 $testsuit 和 $group。

我没有注意到您可能对其他两个变量有问题。

我更新了脚本,也许你可以再试一次。


推荐阅读