0

I have a bash script, let's call it myscript, that is supposed to accept files in the current working directory as variables and perform various actions on them.

I've been able to set up this:

#!/bin/bash

file=$1

command1 $file
command2 $file

that works fine, when I run myscript myfile1.ext it correctly executes command1 myfile1.ext and command2 myfile1.ext.

The problem is that I'd like to pass more filenames on the same instance, to speed up things, and be able to do this: myscript myfile1.ext myfile2.ext myfile3.ext myfile4.ext and have each one of these files be processed by the script. Right now, even if I pass more filenames, only the first one is processed.

How should I modify this script to sequentially work on multiple files?

1 Answer 1

2

A straightforward approach is like this:

#!/bin/sh

for file in "$@"; do
   command1 "$file"
   command2 "$file"
done

Notes:

  • The code is not Bash-specific, it works in sh (hence my shebang).
  • Quote variables like I did.

You can implement more complex logic with shift shell builtin. See the documentation or help shift in Bash.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .