From 2497e27b04003ae1c1d19bbce9c5bc804534c067 Mon Sep 17 00:00:00 2001 From: Dan Church Date: Mon, 27 Mar 2023 11:02:50 -0500 Subject: [PATCH 1/3] Avoid creating temp files until necessary For instance, if one ran "optipdf --help" it would create and delete an empty directory in /tmp. --- optipdf | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/optipdf b/optipdf index 4ef798c..7aca076 100755 --- a/optipdf +++ b/optipdf @@ -42,12 +42,6 @@ KEEP_BACKUP_SUFFIX= FORCE_OVERWRITE=0 ENCODE_THRU_WARNINGS=0 -TEMP_DIR=$(mktemp -d -t "${0##*/}.XXXXXX") -cleanup() { - rm -fr -- "$TEMP_DIR" -} -trap 'cleanup' EXIT - FILES=() NO_MORE_FLAGS=0 for ARG; do @@ -104,6 +98,8 @@ for ARG; do fi done +TEMP_DIR= + if [[ ${#FILES[@]} -eq 0 ]]; then USAGE >&2 exit 1 @@ -159,6 +155,16 @@ hr_size() ( printf '%g %s\n' "$HR_VAL" "$HR_UNIT" ) +setup_tempdir() { + if [[ -z $TEMP_DIR ]]; then + TEMP_DIR=$(mktemp -d -t "${0##*/}.XXXXXX") + cleanup() { + rm -fr -- "$TEMP_DIR" + } + trap 'cleanup' EXIT + fi +} + # copies $2 over to $1 if $2 is smaller than $1 use_smaller() { # if `$TEMP' isn't empty and it's of a smaller size than `$FILE', @@ -250,6 +256,7 @@ fi ERRORS=0 FREED_TOTAL=0 for FILE in "${FILES[@]}"; do + setup_tempdir TEMP=$(mktemp -p "$TEMP_DIR" -t 'file.XXXXXX') rm -f -- "$TEMP" BEGIN_FILESIZE=$(file_size "$FILE") From 4dd8e17f0b05e2931155a3531ab3c561318be55f Mon Sep 17 00:00:00 2001 From: Dan Church Date: Mon, 27 Mar 2023 11:03:24 -0500 Subject: [PATCH 2/3] Fix inconsistent script exit codes Exit 2 always in invalid argument situations. --- optipdf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/optipdf b/optipdf index 7aca076..9755940 100755 --- a/optipdf +++ b/optipdf @@ -102,7 +102,7 @@ TEMP_DIR= if [[ ${#FILES[@]} -eq 0 ]]; then USAGE >&2 - exit 1 + exit 2 fi file_size() { From 8dcfacd5d7a706c7c1d19577c37d1a84d8ec1e58 Mon Sep 17 00:00:00 2001 From: Dan Church Date: Mon, 27 Mar 2023 11:32:18 -0500 Subject: [PATCH 3/3] Update 'mktemp' invocation Turns out using "-t TEMPLATE" instead of "TEMPLATE" is causing TMPDIR to override the setting from `-p`, which is the opposite of what the man page says it does. --- optipdf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/optipdf b/optipdf index 9755940..fc32636 100755 --- a/optipdf +++ b/optipdf @@ -257,7 +257,7 @@ ERRORS=0 FREED_TOTAL=0 for FILE in "${FILES[@]}"; do setup_tempdir - TEMP=$(mktemp -p "$TEMP_DIR" -t 'file.XXXXXX') + TEMP=$(mktemp -p "$TEMP_DIR" 'file.XXXXXX') rm -f -- "$TEMP" BEGIN_FILESIZE=$(file_size "$FILE")