0

I have a working script that parses a text file and creates a new file from the output. How do I run this script against a single file OR a directory of files instead? Below is a general overview of the working script. Thank you for the help.

#!/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 
codeforester
  • 28,846
  • 11
  • 78
  • 104
Nick
  • 27
  • 1
  • 4
  • 1
    Possible duplicate of [Using if elif fi in shell scripts](https://stackoverflow.com/q/2359270/608639), [Bash script with logical ands, and ors in an if elif else statement](https://stackoverflow.com/a/29644160/608639), [Check if a directory exists in a shell script](https://stackoverflow.com/q/59838/608639), [Check if passed argument is file or directory in Bash](https://stackoverflow.com/q/4665051/608639), etc. – jww Jun 29 '18 at 05:04

2 Answers2

0

You could check if the passed argument is a directory and if so, write a loop to process the files in that directory:

#!/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 
codeforester
  • 28,846
  • 11
  • 78
  • 104
-1

An easier solution (which also recurses) is making it X-dimensional:

#!/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 
Jonas Bjork
  • 160
  • 3