1. Command-line arguments
1.1 Parameters space-delimited, format: $+position, e.g. $, $, $, where $ $ represents the script name, more than 10 parameters, e.g. the 10th parameter is represented by ${10};
1.2 Simple example:
1.3 Through the establishment of a soft connection, the same script, according to different script names, run different script content, e.g.:
2. Handling of command-line parameter variables
2.1 Pass the condition judgment, error detection:
2.2 Move the position parameters with the shift command:
2.3 Command line parameter option processing:
2.3.1 simple options handling, e.g.:
2.3.2 separation options and parameters, e.g.:
#!/bin/shwhile [-N "$"]do case "$" in- a) echo "Option a";; -B) echo "Option B";; -c) echo "Option C";; --) shift break ;; Esac Shiftdoneecho "The param is: $*"
2.3.3 processing with value options, e.g:
#!/bin/shwhile [-N "$"]do CA- a) echo "Option a";; -b) value= "$" shift echo "Option B, value is $value";; -c) echo "Option C";; --) shift break ;; Esac Shiftdoneecho "The param is: $*"
(Note: e.g.--AB cannot be processed when the option is merged if the above operation can only handle a single option)
2.3.4 getopt command, for option formatting, e.g:
The colon after #!/bin/sh# B indicates that the B option has parameter set--' getopt ab:c ' [email protected] ' while [-N ' $ ']do case ' $ ' in-a ) echo ' Opt Ion a ";; -b) value= "$" echo "Option B, Value is $value" shift; -c) echo "Option C";; --) shift break ;; Esac Shiftdoneecho "The param is: $*"
2.3.5 when the parameter value has a space, the getopt command cannot be parsed, it needs to use the getopts command, e.g:
#!/bin/shwhile getopts ab:c optdo case "$opt" in a) echo "option A";; b) echo "option B, value is: $OPTARG";; c) echo "option C";; *) echo "unknown option: $opt";; Esacdoneshift $[$OPTIND -1]count=1for param in "[email protected] ' do echo ' param $count is: $param" count=$[$cou Nt+1]done
Note:
Optind:getopts uses Optind as an index to process the next parameter to be processed, recording the current state;
Optarg: In the above loop, a A, a, a, a, b two parameters each have a colon, the colon indicates that the input parameter is followed by a parameter value, when the colon is found getopts, will process the user input parameter values, this parameter value is saved in Optarg.
3. Get user input in the script (read by redirection and Pipeline command, respectively)
Shell Scripting Learning Notes-user input processing