Still getting the hang of bash scripting...
I have a function that resizes images and calculates how much to scale it based on the file size. I need to pass this percentage as an argument to the convert command, but I can't remove the return from the end of the string.
When I run the function, I get:
2.362413
%
How can I concatenate these on one line without a return or newline char? Piping to tr with '\r' or '\d' doesn't seem to work.
shrinkImg() {
FILENAME=$(basename "$1")
EXTENSION="${FILENAME##*.}"
sz=$(stat -c '%s' $1)
PRODUCT=echo bc <<< "scale = 10; ( 100 / ( $sz / 350000))";
PRODUCT=echo ${PRODUCT} | tr -d '\r'
PERCENT=%
TARGET=echo $TARGET
TARGET=$PRODUCT$PERCENT
echo $TARGET;
if [ $sz -ge 350000 ] && [ $EXTENSION == 'png' ] ; then
convert $1 -resize $TARGET $1
elif [ $sz -ge 350000 ] && [ $EXTENSION == 'PNG' ] ; then
convert $1 -resize $TARGET $1
elif [ $sz -ge 350000 ] && [ $EXTENSION == 'jpg' ] ; then
convert $1 -resize $TARGET $1
elif [ $sz -ge 350000 ] && [ $EXTENSION == 'JPG' ] ; then
convert $1 -resize $TARGET $1
fi
}
Also any other tips would be appreciated!
100 / ( $sz / 350000)
? What's wrong with35000000 / $sz
? (Unless of course you want the additional rounding errors introduced by the first formula: try both withsz=1000000
.) You should be aware that the conversion you are applying will reduce the file size by a lot more than you may intend (maybe100*sqrt(350000/$sz)
is better?). It's worth mentioning that if you are happy with rounding to the nearest integer percent you can use$((35000000/$sz))
without using an external program. Note also that the filter to remove new-lines istr -d '\n'
, nottr -d '\r'
.