Parsing Command Line Arguments
- This is somewhat Appendix B
- As you have seen, many programs take command line arguments.
- gcc -o file -o2 -g .... file.cpp
- ls -alrt
- cp oldfile newfile
- These are passed to c/c++ programs as parameters to main.
- There are three possible parameters to main
-
int argc
the number of command line arguments.
-
char * argv[]
or char ** argc
the array of argument strings.
-
char * envp[]
or char ** envp
the array of environment variables.
-
envp
should be null terminated.
- Please see args.cpp
- They are also available in python.
- And in bash
- The variable $# is the number of arguments
- The variable $@ contains all of the arguments.
- The variable $0 is argv[0],
- The variable $1 is argv[1]
- Shift shifts $1 to $n to the left and decrements $#
- Please see args.bashfile
- A few comments (Hopefully we covered these while looking at the scripts but ...)
- The extensions should be .py and .sh but
- I don't know how to keep the web server from executing these files with this name.
- That may change later.
- Command line arguments are subject to shell expansion
- * will be replaced with all files in the directory
- ? will be replaced by any single character
- ~ will be replaced with the path to your home directory
- ~user will be replaced with the path to a user's home directory
- Strings will be broken on space unless inside quotes.
- |, ; && ||, io redirect ...
- There are others but these are the big ones.
- We will see later that to make a script file executable we need to
- Make the first line a structured comment in the form
- We also can run it two ways
-
interpreter script args
-
bash args.bashfile args
-
python pyArgs.pythonfile args
- Or we can make it executable and run it as a command