0

The code "named mywhich" below does basically the same thing as the "which" command in sh does. however, if i do >mywhich wrongcmd wrongcmd2 wrongcmd3

it will only returns wrongcmd3 not found ...... how do i make it like:
wrongcmd not found
wrongcmd2 not found
wrongcmd3 not found ???

I really wanna know this... any one can point out how will be highly appreciated. thank you

#!/bin/sh

all=FALSE


while getopts a option
do
  case "$option" in
       a) all=TRUE;;
      \?) echo "Usage: mywhich [-a] command"
          exit 1;;
  esac
done

if [ "$OPTIND" -gt "$#" ]
then
    echo "error: missing command name!"
    found=0
fi

if [ "$all" = TRUE ]
then
    shift                             #trash the -a and make command to $1
#!/bin/sh
#90.312 Programming Assignment1
#Henry Li

all=FALSE


while getopts a option
do
  case "$option" in
       a) all=TRUE;;
      \?) echo "Usage: mywhich [-a] command"
          exit 1;;
  esac
done

if [ "$OPTIND" -gt "$#" ]
then
    echo "error: missing command name!"
    found=0
fi

if [ "$all" = TRUE ]
then
    shift                             #trash the -a and make command to $1
    while [ "$#" -ne "0" ]
    do

      command=$1                       #first command being at $1
      for dir in `echo $PATH | sed 's/:/ /g'`
      do
        if [ -x "$dir/$command" ]
        then
          found=0
          echo "$dir/$command"         #if command is -x, then echo it with path
          else
          badcommand=$command

        fi
      done
    shift                              #shift second command to $1
    done


else                          #if all=FALSE
    while [ "$#" -ne "0" ]
    do
        command=$1
        for dir in `echo $PATH | sed 's/:/ /g'`
        do
           if [ -x "$dir/$command" ]
           then
               found=0
               echo "$dir/$command"
               break
           else

               badcommand=$command
           fi
        done
    shift                     #shift the 2nd command to $1
    done
fi

if [ "$found" != 0 ]
then
   echo "$badcommand is not found"
fi
2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by omrsafetyo
0

You are only returning (echoing) the last iteration of badcommand. Your while/for/if loop above assigns the current argument that it is processing to the badcommand variable. You let that loop run through all arguments and THEN exit out of the loop and echo. It's only echoing the last command it processed as "not found".

You need to move your echo into your else statement.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.