I'm currently working through a series of exercises in an attempt to improve my bash scripting knowledge.

The exercise I am working on is as follows: Write a script called encrypt.sh that's used to encrypt files. Here are the requirements for the script:

  1. It must use openssl to encrypt files.
  2. It must take the name of a file to encrypt as a parameter
  3. When it encrypts a file it must put the encrypted version in a file with the same name but ".enc" appended.
  4. It must be safe to run on a system with other users. That is, it must not pass any passwords as command line arguments.
  5. It must read the password to use from an environment variable called ENCRYPTION_KEY.
  6. If that environment variable is not set, it should prompt the user to enter a password and use that instead.
  7. It should display an error if no parameter is provided and exit with exit code 2.
  8. It should display a message if the user calls the script with a --help switch.
  9. It should work with files with spaces in the name.

I feel as if my current script has satisfied requirements 1-5,7-8. However I am somewhat floundered as to 6 and 9.

Any feedback on my current workings, or solutions to my missing requirements would be greatly appreciated.

Thank you in advance.

usage="Usage: Enter the name of the file you would like to encrypt as a parameter, eg. $0 words"
openssl enc -e -aes256 -in "$1" -out "$1".enc -pass env:ENCRYPTION_KEY
if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
    echo $usage

if test -z ${1}
        echo "${0} :ERROR: No parameters provided. Please see -h or --help for usage." 1>&2
        exit 1

#DECODE (script is not required to decode, just here for testing purposes)
#openssl enc -d -aes256 -in words.enc -out words.enc.dec -pass env:ENCRYPTION_KEY
  • you should put the checks for the --help switch and for no arguments before, not after the openssl enc command. You should also change if test -z ${1} to if test -z "$1" in order to satisfy point 9. – mosvy Oct 9 '18 at 1:56
  • also, you shouldn't override ENCRYPTION_KEY if you want to be able to pass it to the script via the environment; btw, though that's a requirement, it's usually a stupid idea to pass password via the environment. – mosvy Oct 9 '18 at 1:58

For #6, the read bash builtin will be helpful. For #9, make sure that the variable names are in double quotes everywhere you use them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.