Do loop doesn't iterate

I'm trying to send the file list as parameter to another job and execute it.
But the loop doesn't work, the inner job is running only once and not twice as expected

for filelist in $(ls -rt *.txt | tail -2)
do
echo $filelist
export filelist
cmd="$Program -config $configfile -autoexec $autoexecfile -log $LogFile -sysin $SourceDir/Load.sas"

done

I don't see that it would execute even once, your loop never does anything but declare variables.

At least the "echo" statement should be executed, no?

At first, make shure there are indeed at least 2 files fitting the globbing expression in the PWD. (In case you have overseen it: the "ls" uses no path, so it works in the current directory.)

Second: you should use "tail -n 2" instead of "tail -2".

I hope this helps.

bakunin

Also see if this makes a difference:

ls -rt *.txt | tail -n 2 |
while read filelist
do
  printf "%s\n" "$filelist"
done

Good catch: if some filenames contain control characters the original construct with the subshell "$(...)" might result in somewhat obfuscated output because this is interpreted by the shell a second time.

It will be a good idea to test which output ls -rt *txt | tail -n 2 really produces.

I hope this helps.

bakunin

I tried all the option specified here but nothing works still the loop only iterates one time.

You set a variable called cmd. Then what? Where do you "run" it? And what is $Program?

Set xtrace/verbose, run your script and post the output:

#/bin/your_shell -xv

Replace your_shell with ksh, bash whatever that your are using.

The variables in cmd are

LogFile=LOADS_DIR/devl/logs/LOAD_$(date +%Y%m%d_%H:%M:%S).log
configfile=LOADS_DIR/devl/scripts/SASV9.CFG
autoexecfile=LOADS_DIR/devl/bin/LOAD_autoexec.sas
SourceDir=LOADS_DIR/devl/bin
Program=/usr/local/SAS/SASFoundation/9.2/sas

We are running a SAS job whose input table name changes every time so to solve this we are exporting this as a UNIX variable and inside the SAS job convert again to a SAS variable .
This works fine if the list contains only one variable.

Thanks

You are not using $filelist in your cmd definition, so - if at all - that one identical command is executed twice. And, $filelist will hold one single file name per loop, so the name may be misleading. Why don't you deploy Yoda's advice and post the output of your script executed with xtrace/verbose options?

It is working now, forgot to add the exec command with in the do loop.

eval $(exec $cmd $*)

Thanks everybody for your valuable inputs...

What is wrong with running it just as $cmd - there's nothing to evaluate, and $Program (sas) is already executable. And why store the command ($cmd) in a variable at all?