0x335 Shell

This page summarizes shells and related utilities

Linux

Bash

Basic

Variables will be global scope unless it is declared with local keyword

for

#sequence 
for i in $(seq 10); do  echo $i; done

# filename
for f in file1 file2 file3 file5
do
echo "Processing $f"
# do something on $f
done

array

a=(1 2 3)
echo ${a[0]} // 1
echo ${a[1]} // 2
echo ${a[*]} // 1 2 3 (print all)
echo ${a[@]} // 1 2 3 (same as prev)
echo ${#a[*]} // 3 (number of elements)

Arithmetic Expression

use (()) to evaluate integer expressions


var=$((var+1))
((var=var+1))
((var+=1))
((var++))
(( 1 -eq 1 )) && echo 'true'

Condition

test, [ and [[

  • test: command
  • [ : POSIX command defined in /usr/bin/[, requires ] as an argument
  • [[ : bash (ksh, zsh) specific command, not POSIX compliant

Condition operators

  • -e: existence of a file
  • -f: existence of a regular file
  • -d: existence of a dir

Text Processing

grep

  • -C [num]: show [num] lines near the target

sed

awk

According to Kernighan’s description [1], the operation of awk can be summarized as follows, very beautiful

for each file
  for each input line 
    for each pattern
      if pattern matches input line
        do the action    

Reference

[1] Brian Kernighan on successful language design