13,420
edits
Changes
no edit summary
|- valign="top"
|
{{Admon/tip|Bash Shell Scripting Tips:|<br><ul><li>'''The case statement:'''<br><br>The case statement is a control-flow statement that works in a similar way as the if-elif-else statement (but is more concise). This statement presents scenerios or "cases" based on values or regular expressions (not ranges of values like if-elif-else statements). After action(s) are taken for a particular scenerio (or "case"), a break statement (''';;''') is used to "break-out" of the statement (and not perform other actions). A default case (*) is also used to catch exceptions.<br><br><u>'''Examples (try in shell script):'''</u><br><br>''read -p "pick a door (1 or 2): " pick<br>case $pick in<br> 1) echo "You win a car!" ;;<br> 2) echo "You win a bag of dirt!" ;;<br> *) echo "Not a valid entry"<br> exit 1 ;;<br>esac''<br><br>read -p "enter a single digit: " digit<br>case $digit in<br> [0-9]) echo "Your single digit is: $digit" ;;<br> *) echo "not a valid single digit"<br> exit 1 ;;<br>esac<br><br></li><li>'''The getopts function:'''<br><br></li></ul>The getopts function allows the shell scripter to create scripts that accept options (like options for Linux commands). This provides the Linux administrator with scripts that provide more flexibility and versatility. A built-in function called '''getopts''' (i.e. get command options) is used in conjunction with a '''while''' loop and a '''case''' statement to carry out actions based on if certain options are present when the shell script is run. The variable '''$OPTARG''' can be used if an option accepts text (denoted in the getopts function with an option letter followed by a colon. Case statement exceptions use the ''':)''' and '''\?)''' cases for error handling.<br><br><ul><li>'''<u>Example of getopts</u>''' (try in script and run with options)<br><br>while getopts abc: name<br>do<br> case $name in<br> a) echo "Action for option \"a\"" ;;<br> b) echo "Action for option \"b\"" ;;<br> c) echo "Action for option \"c\""<br> echo Value is: $OPTARG" ;;<br> :) echo "Error: You need text after -c option"<br> exit 1 ;;<br> \?) echo "Error: Incorrect option"<br> exit 1 ;;<br>esac<br><br></li></ul>}}
|}