Shell Script - wwangdev/wwangdev.github.io GitHub Wiki

Shell Script

Need to Know

  • #! /bin/bash: usually write in the first line. Mark the shell which script use
  • #: comment
  • echo: std out
  • Do not add extra space!

Variable and Operator

  • use $ to refer variables
  • source XXX: load XXX variables to parent shell.
  • export var=5: load var to children shell.
  • unset var: log off var
  • use {} to mark a variable
  • $0: filename
  • $1,$2,...: variables
  • $*: all paras
  • $@: all paras
  • $#: number of paras
  • Quotes:
    • ": only $,`," keeps there specific meanings
    • ': everything no specific meanings
    • `: script command will be run
    • EX:
      • log=monday
      • echo "today is $log"
      • echo 'today is $log'
      • echo "today is data"
  • = and == almost the same

Expression

  • $[]: mark as evaluation
  • hex, oct, bin, dec: base#num
  • expr: evaluation. Add space between numbers!!
  • let: evaluation

Control Flow

  • if:
    • if test-commands-1
    • then
      • commands
    • elif test-commands-2
    • then
      • commands
    • else
      • commands
    • fi
  • case
    • case word in
    • pattern-1)
      • commands-1
      • ;;
    • pattern-2)
      • commands-2
      • ;;
    • ...
    • pattern-N)
      • commands-N
      • ;;
    • *)
      • commands-else
      • ;;
    • esac
  • control: 0 -- true, else -- false!
  • Condition test: has blank!
    • test expr
    • [ expr ]
    • [ -z str ]: return true if strlen(str) == 0
    • [ -n str ]: return true if strlen(str) > 0
    • digital compare: -eq, -ne, -lt, -le, -gt, -ge
    • And, Or and Not: -a (&&), -o (||), !
  • loop
    • while
      • while test-commands
      • do
        • commands
      • done
    • until
      • until test-commands
      • do
        • commands
      • done
    • for: could use
      • for variable [in list]
      • do
        • commands
      • done
      • EX: for i in `seq 9`

Others

  • read (XXX): read to XXX or REPLY
  • exit:
  • trap: EX: trap `echo "Type quit to exit"` INT
  • a;b: execute a and then b

Useful Shell Commands

  • cut:
    • cut -c3-6 city.txt cut 3-6th char of every line
    • cut -d" " -f2 city.txt cut 2nd word of every line
  • diff
  • sort: sort -k2 -r city.txt sort by 2nd keyword reversely
  • uniq: sort city.txt | uniq uniq must be used for sorted results!
  • tr:
    • tr "ABH" "HCA" < city.txt A->H, B->C, H->A
    • tr "ABC" "[Z*]" A->Z, B->Z, C->Z
    • tr --delete " " < city.txt delete all space
  • wc: wc city.txt 5 10 64 city.txt: 5 lines, 10 words, 64 bytes
  • substr: Should use expr to get value.
    • expr substr "hello world" 1 5
  • seq:
    • seq 8
    • seq -1 3
    • seq 9 -3 0
  • alias
    • ll='ls -l'
    • write to ~/.bashrc
    • source .bashrc enable immediately