AlanW
AlanW

Reputation: 105

Run Command on Multiple of Files or Single File

I needed to convert several pnm image files to jpeg with pnmtojpeg. So I used this script, which I named 'pnm2jpg':

for f in *.pnm;
  do pnmtojpeg -quality=85 "$f" > "${f%.pnm}.jpg";
done

This works very nicely. However, I would like to adapt it further so that it can be used for a single file as well.

In other words, if no files are specified in the command line, then process all the files.

$ pnm2jpg thisfile.pnm  # Process only this file.

$ pnm2jpg  # Process all pnm files in the current directory.

Your insight is greatly appreciated- Thank you.

Upvotes: 0

Views: 129

Answers (1)

user3439894
user3439894

Reputation: 7565

Something like:

#!/bin/bash

if [[ -z "$1" ]]; then
    for f in *.pnm; do
        pnmtojpeg -quality=85 "$f" > "${f%.pnm}.jpg"
    done
else
    pnmtojpeg -quality=85 "$1" > "${1%.pnm}.jpg"
fi

If you execute pnm2jpg without an argument the if block is processed.

if you execute pnm2jpg thisfile.pnm the else block is processed.

Upvotes: 1

Related Questions