This question is the first follow-up of: Shell POSIX OpenSSL file decryption script
Please read it before you continue reading this. Thank you.
I only have one new problem solved and I would like you to have a look.
That problem being accepting one option -o output_directory
.
I have little idea if I did this the best way, but it works.
The code follows:
#!/bin/sh bold=$(tput bold) red=$(tput setaf 1) yellow=$(tput setaf 3) nocolor=$(tput sgr0) bold_red=${bold}${red} bold_yellow=${bold}${yellow} print_usage_and_exit() { echo "Usage: $0 [-o output_directory] filename_to_decrypt" exit 1 } print_error_and_exit() { echo "${bold_red}$1 Exit code = $2.${nocolor}" 1>&2 exit "$2" } while getopts ":o:" option do case "${option}" in o) given_output_directory=${OPTARG} ;; h | *) print_usage_and_exit ;; esac done shift $((OPTIND - 1)) [ "$#" -eq 0 ] && print_usage_and_exit [ "$#" -gt 1 ] && print_error_and_exit "Multiple files are not supported." 2 [ ! -f "$1" ] && print_error_and_exit "The given argument is not an existing file." 3 input_filename="$1" [ ! -r "$input_filename" ] && print_error_and_exit "Input file is not readable by you." 4 input_filepath=$(dirname "$input_filename") if [ -z ${given_output_directory} ] then output_directory="$input_filepath" else output_directory="$given_output_directory" fi [ ! -w "$output_directory" ] && print_error_and_exit "Destination directory is not writable by you." 5 filename_extracted_from_path=$(basename "$input_filename") filename_without_enc_extension="${filename_extracted_from_path%.enc}" if [ "$filename_extracted_from_path" = "$filename_without_enc_extension" ] then # the file has a different than .enc extension or no extension at all # what we do now, is that we append .dec extention to the file name output_filename="$output_directory/$filename_extracted_from_path".dec else # the file has the .enc extension # what we do now, is that we use the file name without .enc extension output_filename="$output_directory/$filename_without_enc_extension" fi [ -f "$output_filename" ] && print_error_and_exit "Destination file exists." 6 if ! pv -W "$input_filename" | openssl enc -aes-256-cbc -md sha256 -salt -out "$output_filename" -d 2> /dev/null then [ -f "$output_filename" ] && rm "$output_filename" print_error_and_exit "Decryption failed." 7 else echo "${bold_yellow}Decryption successful.${nocolor}" exit 0 fi
Uploaded on GitHub: https://git.io/fxslm