Bash tips – batch file processing

Since some of our servers are running Linux, it is common that we are writing bash scripts (or shell scripts in general) to perform various actions.

In this article, I want to save a few tips for future me. They are related to the batch processing of image files.

Batch convert of AI images

The first one is the script to convert AI images to JPG. I want to perform such an operation for all files in the current directory. My script looks like this:

for i in *.ai;
  gs -dNOPAUSE -r512 -sDEVICE=jpeg -dJPEGQ=92 -dBATCH -dEPSFitPage -sOutputFile=${i/.ai/.jpg} $i  

The script is performing an action for all files with “ai” extension. In the loop, I use GhostScript to generate JPG. The important element is the search/replace part. I want to save the file with the “jpg” extension, but preserve the file name. This is why I used this replace statement:


It takes the variable of “i”, searches for “.ai” and replaces to “.jpg”. Easy and effective.

Distinguish between RGB and CMYK

As the next step, I create thumbnails for the JPG images. Some AI files are saved in CMYK color space. The default conversion is causing issues with colors on the output image. To prevent them, I check if the image is saved using RGB or CMYK color space:

for i in *.jpg;
        cspace=$(identify -format %[colorspace] $i)
        if [ $cspace = "sRGB" ]
                convert $i -resize 1024x1024  ./1024/$i 
                convert $i -profile USWebCoatedSWOP.icc -resize 1024x1024 -profile AdobeRGB1998.icc ./1024/$i

The above script is first identifying the image, retrieving colorspace information. Based on this, one of the conversion methods is used. The first one is handling RGB images and is much simpler. The second one is taking care of CMYK images. There are two color profiles used – the first one is taking care of the image read, the second one is in use during the image save process.


The above scripts were meant to perform a particular operation and not to be used again. During the execution, they were monitored and they were working on a copy of the actual image files. If you want to use such scripts in the regular batch job or a part of the cron job, you have to take care of the security. Error handling and reporting is the minimum you should consider.