motam79 motam79 - 5 months ago 30
Bash Question

Running a shell script on several files as inputs

I have a shell command with the following format:

my_cmd -I file1.inp -O file1.out

Where some processing is done on
and the results are stored in

In my main directory, I have many files with the format:
and I would like to run this command for all of them and the store the results to
. Can I only use shell script to achieve this?


You can use a simple loop:

for file in *.inp ; do
    my_cmd -I "${file}" -O "${file%%.inp}.out"

${file%%.inp} is a so called parameter expansion. It will effectively remove the extension .inp from the input filename.

One thing (thanks Jean-Fran├žois Fabre). If the folder does not contain any .inp files the above loop would run once with $file having the literal value *.inp. To avoid that you need to set the nullglob option:

shopt -s nullglob # set the nullglob option
for file in *.inp ; do
    my_cmd -I "${file}" -O "${file%%.inp}.out"
shopt -u nullglob # unset the nullglob option