3

I am trying to create an alias which when given some argument will look for the folder with contains the argument as pattern. Let the alias name be gohf.

Now, I will be using this alias like gohf <some-pattern>, for eg. gohf testing. Now this should look for a folder that contains “testing” in its name and take me to that folder in the last step.

Following is what I could think of.

alias gohf='cd `find . -type d | grep testing`';

The above alias works when the pattern is always “testing”. How can I modify so that if the alias is used as say gohf game, then the alias should take me to the folder that contains game in its name.

Note:

Shell: ksh

I am assuming that there is only one folder for each pattern I input.

Kazark
  • 979
  • 3
  • 12
  • 31
g4ur4v
  • 1,764
  • 8
  • 29
  • 34

1 Answers1

2

As manatwork said in the comment you should use a function instead to handle arguments better.

gohf(){
  cd $(find . -type d -iname "$1" | sed 1q)
}

There is no need to pipe the results of find to grep as using the flag -name or -iname does the same thing. Then we pipe the whole thing to sed so that we only cd to the first "hit" if there are multiple.

In the case that you want to be able to handle multiple find "hits" you should do something like this:

gohf(){
  select dir in $(find . -name "$1" -type d)
  do
    cd $dir
    break
  done
}
h3rrmiller
  • 13,235
  • How do I use this function in my shell.when I copy this to .profile,I get this error gohf{: command not found – g4ur4v Jan 23 '13 at 15:42
  • @g4ur4v because your .profile is read once when the shell is executed you just need to exec ksh to get it to read the new copy by executing a new shell without forking the process – h3rrmiller Jan 23 '13 at 15:43
  • I am getting that error after logging into the account after making changes to .profile.Even if I use exec ksh,I get the same error. – g4ur4v Jan 23 '13 at 15:46
  • Please ignore ...I made some manual mistake. – g4ur4v Jan 23 '13 at 15:48
  • Not "better", aliases don't take arguments at all. – vonbrand Jan 23 '13 at 20:39
  • alias psg='ps -ef | grep ' sort of takes an argument (ie. psg root). if you look at the other previous comments you will see us call things like this "arguments" though we know theyre not actual arguments – h3rrmiller Jan 23 '13 at 21:49