Search code examples
bashencryptionshgetopts

How do I pass arguments to my functions in a zsh/bash script?


I am trying to combine these two functions in a script. The idea is to pass the flags -E to encrypt, and -D to decrypt. So far the flags are working. I get the different usages for encrypt, decrypt and help. Problem: The functions aren't getting the arguments and I get the usage message every time. How do I pass the arguments to the functions? e.g.:

./cript.zsh -E filetoencript out.des3
#!/usr/bin/env zsh

# TODO, make it a script. Flags -E to encrypt -D to decrypt.
# Usage: $1 = input $2 = output
function encrypt() {
  if [ -z "$1" ]; then
    echo Usage: encrypt '<infile>' '[outfile]'
    return
  fi
  if [ -z "$2" ]; then
    out="$1".des3
  else
   
...

}

# Usage: $1 = input $2 = output
function decrypt() {
  if [ -z "$1" ]; then
    echo Usage: decrypt '<infile>' '[outfile]'
    return
  fi
  if [ -z "$2" ]; then
    
...

}

function main() {
# -E = encrypt
# -D = decrypt
# FIXME
while getopts ":E:D:" opt; do
  case $opt in
    E)
        encrypt
        ;;
    D)
        decrypt
        ;;
    *)
        help
        exit 1
        ;;
  esac
done
}

main "$@"

Solution

  • Solution:

    function main() {
    # -E = encrypt
    # -D = decrypt
    while getopts ":E:D:" opt; do
      case $opt in
        E)
            shift
            encrypt "$@"
            ;;
        D)
            shift
            decrypt "$@"
            ;;
        *)
            help
            exit 1
            ;;
      esac
    done
    }