completed homework 4
[assignments.git] / assgn3 / process-pid.sh
index 0676b8b73b67cc44ade2cabcd119500641828ce0..30d57c75e0b96fcd31fde4343e7f02e0584b9dec 100755 (executable)
@@ -1,6 +1,78 @@
 #!/usr/bin/env bash
 
-if [ -z "$1" ] || [ "$1" = "-h" ] ; then
-       echo "usage: ./process-pid.sh [command] [pid]"
-       exit 1;
+USAGE="usage: $0 <pid> [-h, -a] [-f, -e] [-s <regexp>]"
+OPTIND=2
+
+if [[ ! "$1" =~ ^-?[0-9]+$ ]]; then
+       echo $USAGE; exit 1
+
+elif [[ ! -d /proc/$1 ]]; then
+       echo "invalid pid '$1'"; exit 1
 fi
+
+echo -e "pid '${1}' refers to a running process.\n"
+
+while getopts ":s:hafe" opts; do
+       case "${opts}" in
+               s)
+                 cat /proc/"$1"/status | grep "$OPTARG"
+                 ;;
+               h) 
+                 echo "$USAGE"; DROPBOOL=1
+                 ;;
+               a)
+                 echo "written by ian sutton."; if [[ $DROPBOOL ]]; then exit 0; fi
+                 ;;
+               f)
+                 ls /proc/"$1"
+                 ;;
+               e)
+                 if [[ ! `readlink /proc/$1/exe` ]]; then
+                       echo "no permissions to read pid '$1's executable path"; exit 1
+                 fi
+
+                 echo -n "executable path of pid '$1': "
+                 readlink /proc/"$1"/exe
+                 ;;
+               \?)
+                 echo "bad option \"-$OPTARG\""; exit 1
+                 ;;
+               :)
+                 echo $USAGE; exit 1
+                 ;;
+       esac
+       echo -ne "\n"
+done
+
+# -h case
+#if [[ "$1" -eq "-h" ]]; then
+#      echo "$USAGE"; exit 0 
+#
+# <pid> case
+#elif [[ "$1" =~ ^-?[0-9]+$ ]]; then
+#      if `ps $1 > /dev/null 2>&1`; then
+#              echo "you win!"; exit 0
+#
+#      else
+#              echo -ne "invalid pid\n$USAGE"; exit 1
+#      fi
+#
+# -e <pid> case
+#elif [[ "$1" -eq "-e" && "$2" =~ ^-?[0-9]+$ ]]; then
+#      if `ps $2 > /dev/null 2>&1`; then
+#              echo "you win!"; exit 0;
+#
+#      else
+#              echo -ne "invalid pid\n$USAGE"; exit 1
+#
+# -s <pid> <regex> case
+#elif [[ "$1" -eq "-s" && "$2" =~ ^-?[0-9]+$ ]]; then
+#      if `ps $2 > /dev/null 2>&1`; then
+#              echo "you win!"; exit 0;
+#
+#      else
+#              echo -ne "invalid pid\n$USAGE"; exit 1
+#
+#else
+#      echo "$USAGE"; exit 1
+#fi