The preceding image_help.sh script accepts these arguments:
- -source: This specifies the source directory of the images.
- -dest: This specifies the destination directory of the converted image files. If -dest is not specified, the destination directory will be the same as the source directory.
- -ext: This specifies the target file format for conversions.
- -percent: This specifies the percentage of scaling.
- -scale: This specifies the scaled width and height.
- Both the -percent and -scale parameters may not appear.
- The script starts by checking the number of command arguments. Either four, six, or eight parameters are valid.
The command line is parsed with a while loop and the case statement and values are assigned to appropriate variables. $# is a special variable that contains the number of arguments. The shift command shifts the command arguments one position to the left. With this, every time the shifting happens, we can access the next command argument as $1 rather than using $1, $2, $3, and so on.
The case statement is like a switch statement in the C programming language. When a case is matched, the corresponding statements are executed. Each match statement is terminated with ;;. Once all the parameters are parsed into the variables percent, scale, source_dir, ext, and dest_dir, a for loop iterates through each file in the source directory and the file is converted.
Several tests are done within the for loop to fine-tune the conversion.
If the variable ext is defined (if -ext is given in the command argument), the extension of the destination file is changed from source_file.extension to source_file.$ext.
If the -dest parameter is provided, the destination file path is modified by replacing the directory in the source path with the destination directory.
If -scale or -percent are specified, the resize parameter (-resize widthx or -resize perc%) is added to the command.
After the parameters are evaluated, the convert command is executed with proper arguments.