0

I currently have two bash functions, one which uploads, and another that downloads a file. I would like to create a bash script that allows users to specify which of the two they would like to do.

The issue I am having is the upload and download function run no matter what. For example:

function upload() {
    var=$1
    #something goes here for upload
}

function download() {
    var=$1
    #something here for download
}

main() {
        case "$1" in
            -d) download "$2";;
            -u) upload "$2";;
            *) "Either -d or -x needs to be selected"
        esac
}

I cannot get main() to run only and suppress download and upload until needed.

5
  • have a look to select.
    – pLumo
    Commented Sep 9, 2020 at 12:03
  • 1
    you don't need the main(), or if you want to keep it, call main "$@" in the end
    – annahri
    Commented Sep 9, 2020 at 12:15
  • Not sure I understand the problem. Do you just need to set a variable from each of the -d and -u cases, and then use that variable to choose what function to actually call later on? Commented Sep 9, 2020 at 12:23
  • How are you calling main?
    – Kusalananda
    Commented Sep 9, 2020 at 12:37
  • It is not possible for the script in your question to always run the upload() and download() functions as you say it does even if you did add a line to call main(). Show us a script that can reproduce your problem if you;d like help debugging it.
    – Ed Morton
    Commented Sep 9, 2020 at 13:28

2 Answers 2

7

You need to call the main function too, and pass the script's command line arguments to it:

#!/bin/sh

upload() {
    echo "upload called with arg $1"
}
download() {
    echo "download called with arg $1"
}

main() {
    case "$1" in
        -d) download "$2";;
        -u) upload "$2";;
        *) echo "Either -d or -u needs to be selected"; exit 1;;
    esac
}

main "$@"

No need for the ksh-style function foo declarations here, use foo() instead, as it's standard and more widely supported.

2

You might consider using getopts for your option parsing, and ask the user to select a function if the option is not present:

usage() {
    echo "usage: $0 ..." >&2
    exit $1
}

main() {
    local func opt

    while getopts 'hdu' opt; do
        case $opt in
            h) usage 0 ;;
            d) func=download ;;
            u) func=upload ;;
            *) usage 1 ;;
        esac
    done
    shift $((OPTIND - 1))

    [[ $# -eq 0 ]] && usage 1

    # get the user to select upload or download
    if [[ -z $func ]]; then
        PS3='Choose a function: '
        select func in upload download; do
            [[ -n $func ]] && break
        done
    fi

    # now, invoke the function with the argument
    "$func" "$1"
}

main "$@"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .