1

My question is pretty straight forward but it seems like I can't seem to be able to find an answer with google :(

How do I specify parameters for a function with - parameter for a function I wrote.

For example I wrote this .sh file for bash but it will take 5-6 inputs so it is likely that a user might mess up the order. so how can I make the function run like:

function -m [email protected] -d dataset.csv -f filter ...

instead of having to write all the parameters in right order for $1, $2, etc.

Thanks

1
  • 2
    sounds like getopt/getopts is what you need.
    – Gray
    Commented Jul 15, 2013 at 20:04

1 Answer 1

2

Try using getopts(). I think the reason you had trouble was your search terms. You needed stuff like options, switches, and arguments rather than parameters and functions.

Here is a quick and dirty example.

while getopts "h?vf:" opt; do
    case "$opt" in
        h|\?)
            show_help
            exit 0
            ;;
        v)  verbose=1
            ;;
        f)  output_file=$OPTARG
            ;;
    esac
done

source

2
  • #! /usr/bin/bash optget() { while getopts "a:b:" opt; do case "$opt" in a) out="$OPTARG" ;; b) out2="$OPTARG" ;; esac done echo "test if we get $out . And this one $out2" } this does take in -a but -b automatically becomes OPTARG.So the output of optget -a this -b too ,is: test if we get this . And this one OPTARG can you help?
    – yatici
    Commented Jul 16, 2013 at 14:54
  • @yatici Hey, I can't really tell why that is not working (it looks like it should), and I don't currently have access to a linux terminal (at work). Maybe try posting it as another question? Only thing is to double check you wrote b) exactly the same way that you wrote a).
    – Gray
    Commented Jul 16, 2013 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.