dearN
dearN

Reputation: 1276

Using a variable in a bash script for loop

I have a file which has the number of .pdfs in my folder. I assign this number to a variable, fileNum like so:

fileNum=$(ls -l *.pdf | wc -l)

echo $fileNum returns this number without any problem. Now I need to use fileNum in a for loop and I am having problems with it.

My for loop is:

for i in {1..$fileNum}
do
 var=$(awk 'NR=='$i 'pdfs.file')

 gs \
 -sOutputFile="exgs_"$var \
 -sDEVICE=pdfwrite \
 -sColorConversionStrategy=Gray \
 -dProcessColorModel=/DeviceGray \
 -dCompatibilityLevel=1.4 \
 -dNOPAUSE \
 -dBATCH \
$var

done

The $ at the beginning of fileNum gives me an error message which is:

awk: line 1: syntax error at or near {

Things are fine when I actually use the number itself (which in this case is 17). Obviously, awk doesn't like this because of ... something.... I don't know what. What should I do about this?

I tried other forms such as $(fileNum) and filenum with the single quotes around it. Is it something to do with strings?

Upvotes: 0

Views: 200

Answers (3)

geirha
geirha

Reputation: 6181

I'd use bash to read the file instead of running awk for every line.

while read -r file; do
    gs -sOutputFile="exgs_$file" \
       -sDEVICE=pdfwrite \
       -sColorConversionStrategy=Gray \
       -dProcessColorModel=/DeviceGray \
       -dCompatibilityLevel=1.4 \
       -dNOPAUSE \
       -dBATCH \
       "$file"
done < pdfs.file

See also http://mywiki.wooledge.org/BashFAQ/001

Otherwise, for the general case where you want to iterate from 1 to n, I'd use a C-style for-loop.

n=10
for (( i=1; i <= n; i++)); do
   ...
done

Upvotes: 4

Stephane Rouberol
Stephane Rouberol

Reputation: 4384

I would rather write:

for i in $(seq $fileNum)
do
  ....
done

Upvotes: 0

Buggabill
Buggabill

Reputation: 13901

This is because Bash will do the expansion on the braces before the variable. You need to use eval in this case so that Bash expands the variable first.

for i in $(eval echo {1..$fileNum})
do
 var=$(awk 'NR=='$i 'pdfs.file')

 gs \
 -sOutputFile="exgs_"$var \
 -sDEVICE=pdfwrite \
 -sColorConversionStrategy=Gray \
 -dProcessColorModel=/DeviceGray \
 -dCompatibilityLevel=1.4 \
 -dNOPAUSE \
 -dBATCH \
$var

done

Upvotes: 2

Related Questions