运行脚本以针对目录或文件。
运行脚本以针对目录或文件。
我有一个能解析文本文件并从输出中创建新文件的工作脚本。我该如何将此脚本针对单个文件或文件目录运行?以下是工作脚本的一般概述。谢谢您的帮助。
#!/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
admin 更改状态以发布 2023年5月21日
一种更简单的解决方案(也是递归的)是将其变为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
您可以检查传递的参数是否是一个目录,如果是,就编写一个循环来处理该目录中的文件:
#!/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