Often this is the difference between well-written and poorly written programs. One-off or individually used programs you can get away with little to no input validation. But on scripts that are shared by multiple users input validation is important.
Example#!/bin/bash # read-validate: validate input invalid_input () { echo "Invalid input '$REPLY'" >&2 exit 1 } read -p "Enter a single item > " # input is empty (invalid) [[ -z "$REPLY" ]] && invalid_input # input is multiple items (invalid) (( "$(echo "$REPLY" | wc -w)" > 1 )) && invalid_input # is input a valid filename?
...
Expression Is True If… n1 -eq n2 n1 is equal to n2 n1 -ne n2 n1 is not equal to n2 n1 -le n2 n1 is less than or equal to n2 n1 -lt n2 n1 is less than n2 n1 -ge n2 n1 is greater than or equal to n2 n1 -gt n2 n1 is greater than n2 Where n1 and n2 are integers
Internal Field Separator By default space, tab, and newline are used.
Example:
#!/bin/bash # read-ifs: read fields from a file FILE=/etc/passwd read -p "Enter a username > " user_name file_info="$(grep "^$user_name:" $FILE)" if [ -n "$file_info" ]; then IFS=":" read user pw uid gid name home shell <<< "$file_info" # Note: IFS variable assignment only lasts duration of the command # and you can't pipe to read so '<<<' indicates a 'here string'.
...
Notes # Linux File System File Redirection Bash Expansion Tilde Expansion Command Substitution Strings in Bash File Permissions Shell Prompt Archiving and Backup regex Directory Stack Builtins Bash Variables Resources # The Art of Command Line See also # Data Science at the CLI Awesome Shell
Operator Description <= Less than or equal to >= Greater than or equal to < Less than > Greater than == Equal to != Not equal to && Logical AND ` expr1?expr2:expr3 Comparison (ternary) operator. if expression expr1 evaluates to be non-zero (arithmetic true), then expr2; else expr3.
...
Operation test [ ] [[ ]] and ((()) AND -a && OR -o \ NOT ! !
Use a default value # ${parameter:-word} - If parameter is empty/unset results in word, else results in parameter
Assign a default value # ${parameter:=word} - If parameter is empty/unset results in word and word is assigned to parameter, else results in parameter.
Note: Positional and other special parameters cannot be assigned this way.
Display error if null or unset # ${parameter:?word} - If parameter is empty/unset script exits and word sent to stderr, else results in parameter.
...
Please Select: 1. Display System Information 2. Display Disk Space 3. Display Home Space Utilization 0. Quit Enter selection [0-3] > See also # case
Uses first-in first-out (FIFO) buffers.
process1 > namedpipe process2 < namedpipe
Will behave like … process1 | process2
Creating the pipe # mkfifo pipe1
ls -l > pipe1 cat < pipe1
Necessary to use two separate terminals to run the above.
Note: It’s always good practice to enclose parameter expansion in double quotes to prevent unwanted word splitting, unless there is a specific reason not to. Especially true for filenames.