6

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?

MerseyViking
  • 14,543
  • 1
  • 41
  • 75
user4526
  • 63
  • 1
  • 3

2 Answers2

5

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
MerseyViking
  • 14,543
  • 1
  • 41
  • 75
4

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.

Ian Turton
  • 81,417
  • 6
  • 84
  • 185
  • There is not much screwy about this: Variables in double quotes " are expanded in Bash. Variables in single quotes ' are not expanded. You can also escape single quotes with \'. – j08lue May 01 '17 at 06:30