View and vote on the article here: Shell Programming Series (V)
Shell Programming Series (V)| Category | | | Summary | | You can also get the information from the user by reading arguments included on the command-line. The shell automatically stores command line arguments in special variables. No programming is required to actually read the arguments. Up to nine arguments c |
| | Body | Handling Command-Line Arguments
The FreeBSD POSIX shell also allows additional arguments that be accessed with ${10}, ${11}, and so on. But this should be avoided if these programs will need to run on other systems because the traditional Bourne shell can only handle $1-$9. The variable $0 contains the name of the program itself, the variable $@ contains all the arguments, and the variable $# contains the number of arguments that were passed to the program. For example:
#!/bin/sh
echo
echo ?The name of the program is: $0?
echo ?The total number of arguments received is: $#?
echo ?The complete argument string is: $@?
echo ?Your first name is: $1?
echo ?Your last name is: $2?
echo
exit 0
And here is a sample run:
bash$ ./name Ismail Hasanov
The name of the program is: ./name
The total number of arguments received is: 2
The complete argument string is: Ismail Hasanov
Your first name is: Ismail
Your last name is: Hasanov
bash$
The POSIX shell that FreeBSD uses also supports the getopts command, which is a more versatile way of handling command-line arguments with a shell program. We will discuss this command when we talk about the advanced features of Korn shell programming. If you are writing Bourne shell programs (that use sh) for other UNIX platforms, however, it is best to avoid the use of getopts because it is not a standard part of the traditional Bourne shell, and may cause the program not to work on some systems.
Command Substitution
Among other things, command substitution allows you to run a command and assign the output to a variable. The command to be run should be enclosed in the `. Be careful not to confuse this with the single quote. The ` is a backward quote. For example:
TodayDate=`date`
will run the date command and assign its output to the variable TodayDate. You can then access the information in this variable just as you can access the information in any other variable.
|
|
This article was imported from zZine. (original author: ismail)
There are no replies to this post yet.
|