Logo  

CS469 - Linux and Unix Administration and Networking

Bash Script Examples

  • To make these scripts self executable
    • Make sure that #!/bin/bash is the first line
    • Make executable with: chmod a+x filename

n x n box:

#!/bin/bash
function box() {
  declare -i n=$1 r c;

  for ((r=0; r<n; r++)) {
    for ((c=0; c<n; c++)) {
      echo -n "*";
    }
    echo;
  }
}

# Print a 10x10 box:
box 10

n row high pyramid:

#!/bin/bash
function pyramid() {
  declare -i n=$1 r c s a;

  let s=n-1;
  let a=1;
  for((r=0; r<n; r++)) {
    for((c=0;c<s;c++)) { echo -n " "; }
    for((c=0;c<a;c++)) { echo -n "*"; }
    echo;
    let s--;
    let a+=2;
  }
}

pyramid 10

params.sh

#!/bin/bash

declare -i idx=1;
# or let idx=1;

for param; do
  echo "$idx: $param";
  let idx++;
done

sizes.sh

#!/bin/bash

let total=0;

# Always quote variables that may contain a filename as filenames may contain
# spaces.

# Iterates over the positional parameters, placing their values in f one at a
# time:
for f; do
  let size=$(stat -c%s "$f");
  printf "%12d %s\n" $size "$f";
  let total+=size;
done

printf "Total = %d\n" $total;

draw.sh

#!/bin/bash

read rows cols < <(stty size);
let row=rows/2;
let col=cols/2;
let pen=0;
tput clear;
while true
do
  tput cup $row $col;
  if (( pen )); then
    echo -n -e "#\b";
  else
    echo -n -e " \b";
  fi
  read -n 1 -s key;
  case $key in
    [wW]) if (( row )); then let row--; fi ;;
    [sS]) if (( row < rows-1 )); then let row++; fi ;;
    [aA]) if (( col )); then let col--; fi ;;
    [dD]) if (( col < cols-1 )); then let col++; fi ;;
    [qQ]) break ;;
    *) let pen^=1 ;;
  esac
done

float.sh

  • Adds "floating point" support to bash via the bc command:
function float() {
  local _v _lval _rval _val;

  for _v; do
    if [[ $_v =~ ^[a-zA-Z0-9_]+=[^=] ]]; then
      _lval="${_v%=*}";
      _rval="${_v#*=}";
    else
      _lval=;
      _rval="$_v";
    fi
    _val=$(echo "$_rval" | BC_LINE_LENGTH=0 bc -l);
    if [[ $_lval ]]; then
      eval $_lval="'$_val'";
    else
      # If no assignment is made, simply echo the result:
      echo "$_val";
    fi
  done
}

# It's a good idea to quote anything with wild-card characters in them, though not
# always necessary:
float v=5.234 x=1.23*2.10;
# Printf supports "floats":
printf "v=%f, x=%.4f\n" $v $x;

# Unlike with 'let', variables must be expanded in the rval before passing to float:
float "z=$v*$x";
echo $z;

float "tau=3.1415927*2";
float "sqrt($tau)";

float a=1/3;
echo "$a";