Difference between revisions of "OPS435 Lecture 7 - Bash"

From CDOT Wiki
Jump to: navigation, search
(Created page with 'Today we practiced some more with algorithm design, functions, and arithmetic. In-class examples: errorfunction.sh: <source lang="bash"> #!/bin/bash printUsageAndExit() { ec…')
(No difference)

Revision as of 13:12, 15 March 2016

Today we practiced some more with algorithm design, functions, and arithmetic.

In-class examples:

errorfunction.sh:

#!/bin/bash

printUsageAndExit()
{
  echo "========================================="
  echo "Usage: $0 num1 num2"
  echo "  Where num1 and num2 are integer numbers"
  echo "========================================="
  exit 1
}

if [ -z $1 ]
then
  printUsageAndExit
fi

if [ -z $2 ]
then
  printUsageAndExit
fi

if [ `echo $1 | sed -n '/^[0-9]*$/p' | wc -l` -ne 1 ]
then
  printUsageAndExit
fi

if [ `echo $2 | sed -n '/^[0-9]*$/p' | wc -l` -ne 1 ]
then
  printUsageAndExit
fi

echo Sum of first two arguments is: $(($1 + $2))

cowsay.sh:

#!/bin/bash

STRINGTOPRINT=$1
STRLEN=`echo -n $STRINGTOPRINT | wc -c`

printBubbleLine()
{
  echo -n " "
  for NUM in `seq $(($STRLEN + 2))`
  do
    echo -n "$1"
  done
  echo
}

printBubbleLine "_"
echo "< $STRINGTOPRINT >"
printBubbleLine "-"

echo "       \   ^__^"
echo "        \  (oo)\_______"
echo "           (__)\       )\/\\"
echo "               ||----w |"
echo "               ||     ||"

safecopy.sh:

#!/bin/bash

COPYTODIR=$1

# Not valid characers in a filename:
# < > : " / \ | ? *
isValidFilename()
{
  NAME=$1
 
  if echo $NAME | grep "<" > /dev/null
  then
    return 1
  elif echo $NAME | grep '>'  > /dev/null
  then
    return 1
  elif echo $NAME | grep ':'  > /dev/null
  then
    return 1
  elif echo $NAME | grep '"'  > /dev/null
  then
    return 1
  elif echo $NAME | grep '/'  > /dev/null
  then
    return 1
  elif echo $NAME | grep '\\'  > /dev/null
  then
    return 1
  elif echo $NAME | grep '|'  > /dev/null
  then
    return 1
  elif echo $NAME | grep '?'  > /dev/null
  then
    return 1
  elif echo $NAME | grep '*'  > /dev/null
  then
    return 1
  fi
 
  return 0
}

for FILE in *
do
  if isValidFilename "$FILE"
  then
    echo "$FILE is good"
  else
    echo "$FILE is bad"
  fi
done

#cp -v $COPYFROMDIR/* $COPYTODIR/