Differences
This shows you the differences between two versions of the page.
linux_wiki:use_shell_scripting_to_automate_system_maintenance_tasks [2016/09/21 22:58] billdozor created |
linux_wiki:use_shell_scripting_to_automate_system_maintenance_tasks [2019/05/25 23:50] |
||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== Use Shell Scripting To Automate System Maintenance Tasks ====== | ||
- | |||
- | **General Information** | ||
- | |||
- | Review of common shell scripting syntax. | ||
- | |||
- | ---- | ||
- | |||
- | ====== General Layout ====== | ||
- | |||
- | General bash script layout | ||
- | <code bash> | ||
- | #!/bin/bash | ||
- | |||
- | echo "Hello world" | ||
- | exit 0 | ||
- | </ | ||
- | |||
- | ---- | ||
- | |||
- | ====== Arguments ====== | ||
- | |||
- | Sending and parsing arguments to scripts. | ||
- | <code bash> | ||
- | #!/bin/bash | ||
- | |||
- | echo "The first argument is: $1" | ||
- | echo "The second argument is: $2" | ||
- | |||
- | echo "There are $# total arguments." | ||
- | echo "All of the arguments are: $@" | ||
- | |||
- | # Loop through arguments one at a time | ||
- | for myarg in $@; do | ||
- | echo " | ||
- | done | ||
- | </ | ||
- | |||
- | ---- | ||
- | |||
- | ====== Getting User Input ====== | ||
- | |||
- | User input with the read command | ||
- | <code bash> | ||
- | #!/bin/bash | ||
- | |||
- | # If there is no argument passed, prompt for input | ||
- | if [ -z $1 ]; then | ||
- | echo "Enter something: " | ||
- | read myname | ||
- | else | ||
- | # There is an argument, use that | ||
- | myname=$1 | ||
- | fi | ||
- | |||
- | echo "You entered: $myname" | ||
- | exit 0 | ||
- | </ | ||
- | |||
- | ---- | ||
- | |||
- | ====== Conditionals ====== | ||
- | |||
- | If/else conditional testing | ||
- | <code bash> | ||
- | if [ -f $1 ]; then | ||
- | echo " | ||
- | elif [ -d $1 ]; then | ||
- | echo " | ||
- | else | ||
- | echo " | ||
- | fi | ||
- | |||
- | exit 0 | ||
- | </ | ||
- | |||
- | \\ | ||
- | Logical operators | ||
- | <code bash> | ||
- | # Logical AND: If first command is true, execute second command | ||
- | [ -f $1 ] && echo "This is a file" | ||
- | |||
- | # Logical OR: If first command is true, do not execute second command | ||
- | [ -f $1 ] || echo "This is not a file" | ||
- | </ | ||
- | |||
- | ---- | ||