Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I would like mask several images in bash shell, gdalwarp works for me as a simple single line command:

gdalwarp -cutline mask.shp -cwhere 'kepnev="a.tif"' -crop_to_cutline a.tif a_masked.tif 

..but it dosen't work with for loop:

for kep in *.tif;do
    gdalwarp -cutline mask.shp -cwhere 'kepnev="$kep"' -crop_to_cutline $kep ${kep/.tif}_masked.tif;done

Please help. What am I doing wrong?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

It's because the $kep variable in the where filter is wrapped in quotes. You need to wrap it again in single quotes:

gdalwarp -cutline mask.shp -cwhere 'kepnev="'$kep'"' -crop_to_cutline $kep ${kep/.tif}_masked.tif;done

When I run with echo, I get this output, which looks good to me:

gdalwarp -cutline mask.shp -cwhere kepnev="res_highpass.tif" -crop_to_cutline res_highpass.tif res_highpass_masked.tif
gdalwarp -cutline mask.shp -cwhere kepnev="res_highpass2.tif" -crop_to_cutline res_highpass2.tif res_highpass2_masked.tif
gdalwarp -cutline mask.shp -cwhere kepnev="res_highpass3.tif" -crop_to_cutline res_highpass3.tif res_highpass3_masked.tif
gdalwarp -cutline mask.shp -cwhere kepnev="sj00dsm.tif" -crop_to_cutline sj00dsm.tif sj00dsm_masked.tif

Addendum

Actually, i got my quotes slightly wrong because you may need to wrap the entire where clause in single quotes. After a bit of educated guessing, I've come up with this:

gdalwarp -cutline mask.shp -cwhere "'"kepnev='"'$kep'"'"'" -crop_to_cutline $kep ${kep/.tif}_masked.tif;done

Which gives me this:

gdalwarp -cutline mask.shp -cwhere 'kepnev="sj00dsm.tif"' -crop_to_cutline sj00dsm.tif sj00dsm_masked.tif
share|improve this answer

It is probably a quoting problem - when ever bash " & ' occur things get screwy. The best way to debug this sort of thing is to stick echo at the start of the gdalwarp line and see what the -cwhere 'kepnev="$kep"' bit looks like after a trip through the shell.

Remember that you can use intermediate variables in the for loop so may be something like

for kep in *.tif
  do
    wclause = kepnev="$kep"
    mask = ${kep/.tif}_masked.tif
    gdalwarp -cutline mask.shp -cwhere '$wclause' -crop_to_cutline $kep $mask
  done

might work better (as you can use echo to check each variable as you go.

share|improve this answer
    
Ahh ok, thanks! –  user4526 Apr 25 '12 at 10:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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