Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Is there a way to make a bash script require a set of parameters when it's loaded, and if not, it will automatically spit out an echo to the screen giving instructions?

Looking at this example of a script called copy

user@localhost : user # ./copy  
Copy by SamplePerson  
Usage:  
copy [path/to/file] [path/to/destination]  
user@localhost : user #

I want it to make sure that if no parameters are given, it will automatically just spit out some predefined text on the echo.

I know how to ensure that the user enters correct values, but I just want the initial "usage" information be displayed for them.

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

I often use a construct like this:

case "$1" in
    'start')
        startProfile
        ;;

    'stop')
        stopProfile
        ;;

    'restart')
        stopProfile
        startProfile
        ;;

    *)
        echo "Usage $0 start|stop|restart <profile|application>"
esac

You have a switch-case that handles the normal cases and if none of them fit, then the default case prints the usage instructions.

share|improve this answer
    
Can you please add to your answer. I understand from: 'start'), doSomethingHere, ;;, *) I need to know how to add # other labels, can you add a secondary one for me too please? –  Danijel J Oct 1 '13 at 11:14
    
@DanijelJames: Done. If it helps you, you can also look at a more complex example, like this: github.com/oliversalzburg/typo3scripts/blob/master/… –  Oliver Salzburg Oct 1 '13 at 11:22
    
I feel so silly. I literally went looking around the net, and just found the answer. It was so simple, I don't know how I overlooked it. But thank your help. This has been really appreciated. :-) –  Danijel J Oct 1 '13 at 12:17
add comment

You may try something like this:

#!/usr/bin/bash

[ $# -eq 0 ] && cat <<XXX && exit 0;
Copy by SamplePerson
Usage:
copy [path/to/file] [path/to/destination]
XXX

echo Check args "$@"

Sample run:

# ./test.sh
Copy by SamplePerson
Usage:
copy [path/to/file] [path/to/destination]

# ./test.sh -x -y
Check args -x -y

You can process arguments on a very convenient way using the getopts built-in command. Or the external getopt(3) command (especially if You use long (e.g. --longopt) arguments).

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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