2

I have a executable shell script name project2. Following is one of the instruction my teacher gave me on the project.

This script must accept at least one command line parameter: the directory where its output is to be placed. If that directory is not given on the command line, the script should use a reasonable default directory.

Can you please tell me how can I make my script accept a command line. I haven't done anything like that before. Any help would be greatly appreciated. Thanks a lot.

1
  • I'm assuming that you are using bash, and not some other shell, right? Commented Nov 15, 2010 at 6:43

2 Answers 2

5

For bash, command line parameters are stored in $1, $2, and so on, while $# will give you the count. In addition, shift can be used to shift them all "left" by one position and drop the count.

The following script is a good starting point for understanding how the parameters work:

echo $#
while [[ $# -gt 0 ]] ; do
    echo "$1"
    shift
done

When you run it with:

./myprog.sh hello there my name is "pax     diablo"

the output is:

6
hello
there
my
name
is
pax     diablo

The basic idea of your assignment is:

  • check the parameter count to see if it's zero.
  • if it is zero, set a variable to some useful default.
  • if it isn't zero, set that variable based on the first parameter.
  • do whatever you have to do with that variable.
Sign up to request clarification or add additional context in comments.

1 Comment

wow, thanks for the detailed information pax. Now I understand how it works. Thanks a lot.
1

Take a look at this section of Advanced Bash Scripting guide.

I recommend you to read whole guide.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.