乐闻世界logo
搜索文章和话题

How to define variables, write conditional statements and loops in Linux Shell scripting?

2月17日 23:38

Linux Shell scripting is an important skill for automated operations and system management.

Variable definition and usage:

  • Variable definition: name="value" (note no spaces around the equals sign)
  • Variable reference: $name or ${name}
  • Read-only variable: readonly name
  • Delete variable: unset name
  • Environment variable: export name="value"
  • Special variables: $0 (script name), $1-$9 (positional parameters), $# (number of parameters), $* (all parameters), $@ (all parameters), $? (exit status of last command), $$ (current process PID), $! (background process PID)

Conditional statements:

  • if statement: if [ condition ]; then commands; fi
  • File tests: -f (file exists), -d (directory exists), -e (exists), -r (readable), -w (writable), -x (executable)
  • String comparison: = (equal), != (not equal), -z (empty string), -n (non-empty string)
  • Numeric comparison: -eq (equal), -ne (not equal), -gt (greater than), -lt (less than), -ge (greater than or equal), -le (less than or equal)
  • Logical operators: -a (and), -o (or), ! (not)

Loop structures:

  • for loop: for i in {1..10}; do commands; done or for ((i=0; i<10; i++)); do commands; done
  • while loop: while [ condition ]; do commands; done
  • until loop: until [ condition ]; do commands; done

Function definition:

  • Function definition: function_name() { commands; } or function function_name { commands; }
  • Function call: function_name arg1 arg2
  • Return value: return value (0-255)
  • Local variable: local var="value"

Common commands:

  • echo: output text, echo -n no newline, echo -e parse escape characters
  • printf: formatted output
  • read: read user input, read -p "prompt" var
  • test: condition test, [ ] is a synonym for test
  • expr: expression evaluation
  • let: arithmetic operations
  • awk: text processing tool
  • sed: stream editor
  • grep: text search

Array operations:

  • Define array: arr=(item1 item2 item3)
  • Access elements: ${arr[0]}, ${arr[@]} (all elements), ${#arr[@]} (number of elements)
  • Add element: arr+=("new_item")

Best practices:

  • Use set -e to exit immediately on error
  • Use set -u to report error when using undefined variables
  • Use set -o pipefail to return failure if any command in the pipeline fails
  • Add comments to explain script purpose
  • Use quotes to protect variables
标签:Linux