How to put command line parameter to shell script
I have a executable shell script name project2. Following is one of the i开发者_JAVA百科nstruction 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.
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.
Take a look at this section of Advanced Bash Scripting guide.
I recommend you to read whole guide.
精彩评论