#!/bin/bash # this script rotates JPEG files # you can use the --rotate/-r argument to specify the angle, or you # can use symlinks that have various bits of text in them to set the # default. This script is designed to interact with nautilus nicely. # default angle angle=90 # set defaults by $0 so symlinks just do the right thing case $0 in *270*) angle=270 ;; *CCW*) angle=270 ;; *180*) angle=180 ;; *USD*) angle=180 ;; *90*) angle=90 ;; *CW*) angle=90 ;; # must be listed after CCW for obvious reasons esac message () { if [ -n "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" ] ; then # we must be running as a nautilus script, report errors... nautilus-error-dialog --message="$@" --title="Rotation script failure" else echo "$*" >&2 fi } usage () { message $1 $(echo -e '\n') "usage: $0 [-a ] " } [ -x /usr/bin/jpegtran ] || { message "$0: /usr/bin/jpegtran program not available" exit 1 } filelist= ignorelist= while [ $# -gt 0 ] ; do case $1 in --a*|-a*|--r*|-r*) shift; case $1 in 90) angle=90 ;; 180) angle=180 ;; 270) angle=270 ;; *) usage "unrecognized angle" exit 1 ;; esac ;; --h*|-h*) shift; usage exit 0 ;; *) if file "$1" | grep JPEG > /dev/null 2>&1 ; then filelist="$filelist $1" else ignorelist="$ignorelist $1" fi ;; esac shift done if [ -n "$ignorelist" ] ; then message "ignoring unrecognized non-JPEG file(s) $ignorelist..." fi for file in $filelist ; do dirname=$(dirname $file) # Create temp file in the same directory so that it's guaranteed to be # on the same filesystem. This makes the final move work TMP=$(mktemp $dirname/.$(basename $file).XXXXXX) || { message "$0: failed to create temporary file" } jpegtran -rotate $angle -copy all $file > $TMP || { message "$0: jpegtran failed on file $file" exit 2 } # Keep the old timestamp touch -r $file $TMP || message "$0: failed to save timestamp for $file" # Nautilus depends on timestamps for its thumbnails, so manually remove # any old thumbnails thumbnail=$dirname/.thumbnails/$(basename $file) rm -f $thumbnail.png rm -f $thumbnail.png.x # Use mv, since it atomically replaces destination. This way we never get # Bad data in the file. mv $TMP $file || { message "$0: rename failed on file $file, $file rotated version available as $TMP" exit 3 } thumbnail=$dirname/.thumbnails/$(basename $TMP) rm -f $thumbnail.*.png rm -f $thumbnail.*.png.x done # only on successful exit... rm -f $TMP exit 0