Shell Script cd

teammatt3's picture

He has: 2,102 posts

Joined: Sep 2003

I am trying to write a shell script that sends me to my C programming directory from anywhere on the system.

#!/bin/sh
cd "$HOME/public_html/CSE121"

pwd

exit 0
'

When I run the script I get this

Quote:
mjohn0882@cs:~/bin$ c
/home/students/mjohn0882/public_html/CSE121
mjohn0882@cs:~/bin$

Instead of shooting me over to my CSE121 directory, I am right back where I started in the bin directory, when the script terminates. What's up with that?

Abhishek Reddy's picture

He has: 3,348 posts

Joined: Jul 2001

The [incode]cd[/incode] only applies "locally", that is, inside the new shell process ([incode]#!/bin/sh[/incode]). Once the process terminates, you're naturally returned right back where you initiated it.

A neat way to do this sort of thing is to set an alias in your shell. Something like:

mjohn0882@cs:~/bin$ alias c="cd $HOME/public_html/CSE121; pwd"
mjohn0882@cs:~/bin$ c
mjohn0882@cs:~/public_html/CSE121$
'

Put that alias definition in your shell's init file (.bashrc?) and you'll have it for all new sessions. Smiling

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.