【问题标题】:Run script against a directory or a file针对目录或文件运行脚本
【发布时间】:2018-12-08 05:13:00
【问题描述】:

我有一个可以解析文本文件并从输出中创建新文件的工作脚本。如何针对单个文件文件目录运行此脚本?以下是工作脚本的一般概述。谢谢你的帮助。

#!/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 

【问题讨论】:

标签: bash shell


【解决方案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 

【讨论】:

  • 想评论否决票?我是否不小心引入了某种错误?
【解决方案2】:

您可以检查传递的参数是否是目录,如果是,则编写一个循环来处理该目录中的文件:

#!/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 

【讨论】:

  • 反对者,如果这里有问题请告诉我。
猜你喜欢
  • 2021-02-19
  • 1970-01-01
  • 2011-05-02
  • 2011-05-13
  • 2018-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多