Thread: Implementing ! functionality for Korn shell

  1. #1
    Registered User
    Join Date
    Sep 2003
    Posts
    224

    Implementing ! functionality for Korn shell

    Hello,
    No one answered this on the Tech Board, so I thought I'd post it here.
    I'm trying to implement the ! operator from the Bourne shell for Korn shell. The ! operator allows you to execute the last command entered beginning with the word after !. Here's what I have so far. Note: I know that fc -s would allow me to implement the functionality of !, but I did not know about fc before writing this. I figured I might as well go through with this.
    Code:
    #!/bin/ksh
    
    _()
    {
     i=0;
    
     tmp=`history`;
    
     if (($?==0)) then
      list=`history | cut -f2`;
    
      #sequence to store each line in an array
      while [[ -n $list ]] do
       temp2=$temp;
       temp=${list%
    *};
    
       #last line does not have \n
       if [[ $temp2 == $temp ]] then
        hist[$i]=$temp;
        list="";
       else
        hist[$i]=${list#$temp
    };
        list=$temp;
        ((i=$i+1));
       fi
      done
    
     else
      print "ksh: _: no history (yet)";
     fi
    
     ((i=0));
    
     while (($i < ${#hist[*]})) do
      if [[ "${hist[$i]}" == "$1" ]] then
       print "here: ${hist[$i]}";
       ${hist[$i]};
       return $?;
      fi
    
      ((i=$i+1));
     done
    
     print "ksh: _: $1: not in history";
     return 1;
    }
    This works for things like "_ ls", but it won't work for something like "_ l", which would find the first command beginning with "l" and execute it. I tried the following, but it always executes the last command:
    Code:
     while (($i < ${#hist[*]})) do
      tmp="\"${hist[$i]}\"";
      `perl -e 'exit $tmp =~ /^$1/'`;
    
      if (($?==1)) then
    #  if [[ "${hist[$i]}" == "$1" ]] then
       print ${hist[$i]};
       ${hist[$i]};
       return $?;
      fi
    
      ((i=$i+1));
     done
    I would prefer not to use perl, just the shells simple globbing rules. I am using pdksh that comes with NetBSD.

    Thanks,
    Yasir

  2. #2
    Registered User
    Join Date
    Sep 2003
    Posts
    224
    That last hist line should have been `${hist[$i]}`;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 34
    Last Post: 05-27-2009, 12:26 PM
  2. What shell is more powerful?
    By xddxogm3 in forum Tech Board
    Replies: 10
    Last Post: 07-24-2004, 10:47 PM
  3. Implementing ! functionality for Korn shell
    By Yasir_Malik in forum Tech Board
    Replies: 1
    Last Post: 06-13-2004, 05:27 PM
  4. System.ini Shell Problems
    By (TNT) in forum Windows Programming
    Replies: 2
    Last Post: 08-26-2001, 01:05 PM