0

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.

1

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.

| 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-James W 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/… – Der Hochstapler 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-James W Oct 1 '13 at 12:17
2

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).

| improve this answer | |

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.