使用给定目录的输入运行某个程序的脚本

时间:2012-05-11 19:43:23

标签: testing maven for-loop sh

所以我需要运行一堆(maven)测试,并将testfiles作为maven任务的参数提供。

这样的事情:

mvn clean test -Dtest=<filename>

测试文件通常被组织到不同的目录中。所以我正在尝试编写一个执行上述“命令”的脚本,并自动将给定目录中所有文件的名称提供给-Dtest

所以我开始使用名为'run_test'的shellcript:

#!/bin/sh
if test $# -lt 2; then
    echo "$0: insufficient arguments on the command line." >&1
    echo "usage: $0 run_test dirctory" >&1
    exit 1
fi
for file in allFiles <<<<<<< what should I put here? Can I somehow iterate thru the list of all files' name in the given directory put the file name here?
     do mvn clean test -Dtest= $file  

exit $?

我遇到的部分是如何获取文件名列表。 谢谢,

2 个答案:

答案 0 :(得分:1)

#! /bin/sh
# Set IFS to newline to minimise problems with whitespace in file/directory 
# names. If we also need to deal with newlines, we will need to use
# find -print0 | xargs -0 instead of a for loop.
IFS="
"
if ! [[ -d "${1}" ]]; then
  echo "Please supply a directory name" > &2
  exit 1
else
  # We use find rather than glob expansion in case there are nested directories.
  # We sort the filenames so that we execute the tests in a predictable order.
  for pathname in $(find "${1}" -type f | LC_ALL=C sort) do
    mvn clean test -Dtest="${pathname}" || break
  done
fi
# exit $? would be superfluous (it is the default)

答案 1 :(得分:1)

假设$1包含目录名称(用户输入的验证是一个单独的问题),那么

for file in $1/*
do
    [[ -f $file ]] && mvn clean test -Dtest=$file
done

将对所有文件运行命令。如果要递归到子目录,则需要使用find命令

for file in $(find $1 -type f)
do
    etc...
done