Andrew Chen

Andrew Chen

SDE @ StripeMS CS '19 @ UW-MadisonEnthusiastic about creating tools to make life better.

Shell Script

Back

Array

Initialize arry

# declare variable, with a type -a array
declare -a arr=("command1" "command2" "command3")

for cond in "${arr[@]}"
do
  ${cond}
done

Positional parameter

  • > some_program word1 word2 word3

    $0 = someprogram
    $1 = word
    1
    $2 = word2
    $3 = word
    3

  • $# ~= arguments.length, is the number of items on the command line not include ($0)

Comamnd

# add prefix to all file in folders
for FILENAME in *; do mv $FILENAME prefix_$FILENAME; done

# remvoe prefix from all files in folders
for FILENAME in prefix_*; do mv $FILENAME "${FILENAME#prefix_}"; done

shift

  • is a shell builtin that operates on the positional parameters.
  • Each time you invoke shift, it “shifts” all the positional parameters down by one. 2becomes2 becomes1, 3becomes3 becomes2, 4becomes4 becomes3
# Loop until all parameters are used up
while [ "$1" != "" ]; do
  echo "Parameter 1 equals $1"
  echo "You now have $# positional parameters"

  # Shift all the parameters down by one
  shift
done