3

I have files whose extension is .AH. For example:

aa.AH
bb.AH
cc.AH
dx.AH
tmz.AH
lght.AH

I want to select all of these files, but not one by one because I use saclst (it's a command to read and write seismogram headers), and it needs all files for comparison for NPTS (which is the number of points). So I use this code:

for file in *AH
   do

   nptsAH=$(saclst npts f ${file}* > nptsAH.txt | awk '{print $2}' nptsAH.txt | sort -n | head -1)
   declare -i nptsAH

   sac << !
   r $file
   interpolate NPTS $nptsAH
   w over
   q
   !
   done

Which form is correct for bash scripting?

3
  • 1
    In a for loop, you loop over the files one by one. How would you want to pick the files, but not one by one if you want to loop over them? – Ljm Dullaart Jul 14 '20 at 8:51
  • It's not clear what you want to do with the files. You may want to add your usage scenario. – pLumo Jul 14 '20 at 8:54
  • @pLumo I edited my question, thanks – curious Jul 14 '20 at 9:02
6

A variable cannot hold multiple files or a pattern. But you may use an array:

files=(*.AH)

or

files=()
for file in *.AH; do
   files+=("$file")
   ...
   some_command using "$file"
done
...
some_command using "${files[@]}"

See also.

2
  • second one is working, thanks @pLumo – curious Jul 14 '20 at 9:04
  • ITYM you can use an array variable instead of a scalar variable. In Korn-like shells, var=value is a scalar variable assignment. It can only store one value. In zsh/ksh93-like shells, var=(...) is either a compound, array or associate array variable assignment depending on the shell and whether a type was given to the variable with typeset beforehand. In any case those are all variables (though with different types). – Stéphane Chazelas Jan 28 at 11:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.