我有一个工作脚本,该脚本分析文本文件并从输出中创建一个新文件。如何针对单个文件或文件目录运行此脚本?以下是工作脚本的一般概述。谢谢您的帮助。
#!/usr/bin/env bash
if [ -f "$1" ]; then
*Run Some Commands against file* "$1" >> NewFile.txt
echo "Complete. Check NewFile.txt"
else
echo "Expected a file at $1, but it doesn't exist." >&2
fi
答案 0 :(得分:0)
您可以检查传递的参数是否为目录,如果是,则编写循环以处理该目录中的文件:
#!/usr/bin/env bash
if (($# = 0)); then
echo "No arguments given" >&2
exit 2
fi
arg=$1
if [ -f "$arg" ]; then
*Run Some Commands against file* "$1" >> NewFile.txt
echo "Complete. Check NewFile.txt"
elif [ -d "$arg" ]; then
shopt -s nullglob
for file in "$arg"/*; do
# run command against "$file"
done
else
echo "Expected a file or directory as $1, but it doesn't exist." >&2
fi
答案 1 :(得分:-1)
一个更简单的解决方案(也可以递归)是使其具有X维度:
#!/usr/bin/env bash
if [ -d $1 ]; then
for i in $1/*; do
# start another instance of this script
$0 $1/$i
done
fi
if [ -f "$1" ]; then
*Run Some Commands against file* "$1" >> NewFile.txt
echo "Complete. Check NewFile.txt"
else
echo "Expected a file at $1, but it doesn't exist." >&2
fi