How to read in a part of an echo line?

Hello,
I have a very basic script

#!/usr/bin/ksh
      while
print ' '
print '          1. View Command History '
print '          2. List files in current Directory '
 read opt'?Enter Option> ' ;do
if [ $opt = 1 ] ;then
      fc -l
      fi
#     
      if [ $opt = 2 ] ;then
      ls -la

I want to add some more options to do a 'cd' command but without coding all the 'if' statements.
Is there a way to list the options (all the directory names) and then cd to that directory based on the number supplied?

Thanks

Rob

What about using case..?

You can add multiple options..

sample code..

case "$1" in

1)  echo "Sending 1 signal"    
    ;;
2)  echo  "Sending 2 signal"
    ;;
3)  echo  "Sending 3 signal"
    ;;
*) echo "Signal number $1 is not processed"
   ;;
esac

You also may want to have a look at this link

Not sure if this works the same in ksh, but according to man page you might want to give it a shot:

allfiles=$(ls)
select selfile in $allfiles
   do echo $selfile
   done

This will return the selected file/directory in the variable selfile, to which you then can cd

You can find some ksh use of "select" here

Thanks I'll have a look but I don't really understand it !

Please look..

$ cat test.sh
case "$1" in

1)  echo "Sending 1 signal"
    ;;
2)  echo  "Sending 2 signal"
    ;;
3)  echo  "Sending 3 signal"
    ;;
*) echo "Signal number $1 is not processed"
   ;;
esac

$ sh test.sh 2
Sending 2 signal

$ sh test.sh 1
Sending 1 signal

$ sh test.sh 5
Signal number 5 is not processed

As per your given option you can change what you want to do.
just replace echo with your command.:slight_smile:

I think what we were trying to say was : first, you should focus on how to use a "case" statement, which is more appropriate to what you are trying to do and easy to read and maintain.

Then, if you want to investigate further, you should also train to use "getopts" as well as "select". (see the links previously provided)

1 Like

Thanks Pamu but it doesn't work for what I want as I can't pass the $1 until I've been shown the options.

So who is stopping you from doing this..?

You can do something like this.

echo "Options are"
echo "1 for --"
echo "2 for --"
read opt
#You can check is $opt is present or not
case "$opt" in

1)  echo "Sending 1 signal"
    ;;
2)  echo  "Sending 2 signal"
    ;;
3)  echo  "Sending 3 signal"
    ;;
*) echo "Signal number $opt is not processed"
   ;;
esac

I hope this helps:)

pamu

1 Like

Are you struggling with the logic for the menu driven cd Grueben? Maybe this code snipplet can help (tested in bash, but it should work with ksh too):

#!/bin/bash

dir=""
backmsg="Back to menu"
PS3="Select directory to cd into: "

while [ "$dir" != "$backmsg" ]
do
   alldirs=$(ls -ap |grep /)
   select dir in $alldirs "$backmsg"
   do
      if [ "$dir" != "$backmsg" ]
      then
         cd $dir
         pwd
      fi
      break
   done
done