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?

2 Answers 2


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


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

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
    wclause = kepnev="$kep"
    mask = ${kep/.tif}_masked.tif
    gdalwarp -cutline mask.shp -cwhere '$wclause' -crop_to_cutline $kep $mask

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

  • 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 1, 2017 at 6:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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