It appears that 7z can't write to a pipe, so I wrote the following bash function to emulate this functionality.
I know this is a simple problem, but this is my first bash function and I feel like it's really easy to write faulty code in bash, so any feedback is appreciated.
function 7z2pipe () (
local out_dir=$(mktemp -d)
local out_file="${out_dir}"/temp.7z
local log_file="${out_dir}"/"outz.txt"
7z -p"weak_password" -mhe=on a "${out_file}" "$@" &> "${log_file}"
if [ $? -ne 0 ]; then
cat "${log_file}"
return $?
fi
cat "${out_file}"
)
1 Answer 1
Do you want to make persistent temporary files?
Note that while the default settings for mktemp
put things in /tmp so that it will eventually get garbage collected, it doesn't immediately get garbage collected. Things can persist in /tmp for days.
cat
has a return code
I'm not sure why are returning the return code from cat
. Wouldn't it make more sense to return the return code from 7z
?
Alternative code
local return_code=$?
if [ ${return_code} -ne 0]; then
cat "${log_file}"
else
cat "${out_file}"
fi
rm -rf ${out_dir}
return ${return_code}
That will leave things as you found them, with no extra temporary directories or files.
It will always return the return code from 7z
.
It will output either the log file or the output file, as you originally did it.
Redirect to stderr
I'm not sure that your approach is what I would do. An alternative to creating the log file would be to redirect stdout
to stderr
.
local out_file=$(mktemp --suffix .7z)
7z -p"weak_password" -mhe=on a "${out_file}" "$@" 1>&2
local return_code=$?
cat "${out_file}"
rm -f ${out_file}
return ${return_code}
Now stdout
will contain the compressed file and stderr
will have all the output from the command.
Note: I do not normally use Bash functions, so don't take anything I say as validation of function syntax.
-
\$\begingroup\$ Actually,
mktemp
will put its file into$TMPDIR
if that's set (this is howpam_tmpdir
implements per-user temporary directories). The point still stands that it's good practice to add atrap
to clean up, of course. \$\endgroup\$Toby Speight– Toby Speight2021年09月05日 11:01:55 +00:00Commented Sep 5, 2021 at 11:01