Link to home
Start Free TrialLog in
Avatar of gs79
gs79

asked on

process file in a loop

Linux OS, ksh script

I have a shell script and  within this shell script there is a line that execute set of commands on a file in a folder. It is something like this

mycommand1 /home/joe/fileFolder xyzd_org1_500.tar.gz
mycommand2
mycommand3
..
..
mycommandn

Now the  requirement changed and the folder can have multiple files as follows

xyzd_org1_500.tar.gz
xyzd_org1_503.tar.gz
xyzd_org1_504.tar.gz
xyzd_org1_505.tar.gz

Now I want put all the commands in a function which accepts the file has a parameter, then call the function in a loop for each file (in ascending order), process 500, 503, 504 etc..
If there is a failure in the function, the shell script should exit with an error without processing the next files. How to do this?
Avatar of Pierre François
Pierre François
Flag of Belgium image

Try this:
folder="/home/joe/fileFolder"               # double quotes in case the path to the folder contains a space
files=$(cd "$folder"; ls xyzd_org1_*.tar.gz)
for file in $files ; do
  mycommand1 "$folder" $file || break       # quit the loop if mycommand1 failed
  mycommand2
  mycommand3
  ..
  ..
  mycommandn
done

Open in new window

Avatar of gs79
gs79

ASKER

Is there a way to put list of commands (command 1 to command n) that I need to run to process each file into a function and pass the file name to this function within a for loop?
ASKER CERTIFIED SOLUTION
Avatar of Pierre François
Pierre François
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gs79

ASKER

let me try this and get back to you
Avatar of gs79

ASKER

Thanks. The programs works