Tuesday, May 24, 2005

If you use a shell

I am sure many of you who use a shell like the bash shell or the korn shell or any other shell for that matter must be power users of it by now. I will probably blog on some fun shell techniques, like the one in this blog.

Korn shell comes with a variant of the "cd" command that very few people are aware of. It is very useful for people who tend to have symmetrical directory hierarchies

Lets assume that you are in a directory structure as shown below

(1) /home/user/programming/drivers/source/cxx

and want to change directories to

(2) /home/user/programming/user_mode/source/cxx

Well, in KSH you can say

"cd drivers user_mode" and it will change from (1) to (2). I love this feature and miss it in the BASH shell, so I wrote my own wrapper (that's why I love *NIX)

function cd
case $# in
1) builtin cd $1
return ;;
2) builtin cd ${PWD/$1/$2}
return ;;
*) builtin cd $*
return ;;


In fact this version is slightly different from the KSH one, can you spot the difference?

Let me know if you do, I will post your name(s) on this blog


NGM said...

Hey balbir, not related to the post above:
I have posted a simple problem data structure and algorithms. May be you can post your ideas.

H said...

I'm no shell expert, but my 2 cents

2) builtin cd ${PWD/$1/$2}

The case2 seems to have a problem
Example :- I'm currently in /usr/local/abc/def/ghi

and I have a directory called /usr/local/abc/jkl/ghi

so a cd def jkl will be case 2) pwd will return /usr/local/abc/def/ghi and you are now trying to do a cd /usr/local/abc/def/ghi/def/jkl

this may not work.

Balbir Singh said...

cd ${PWD/$1/$2} is used for substitution. It does not concatenate the string. So basically def gets replaced by jkl in the new string and cd will actually take you to the second directory

H said...

Okay :)

Dynamic programming for the binomial coefficient

More fun things, this time with some visualisation of what happens when memoisation is used and what happens when we don't. I don'...