using CD in ksh script


Recommended Posts

hello gents, hoping someone can point me in the right direction, i am tryign to get a simple script to work that will place you into a directory using a variable; here's basicly what my script looks like:

#!/bin/ksh

if [ $# -eq 0 ] ; then

echo ""

echo "Usage: godir {dirname}"

echo ""

exit

else

cd /dir1/adir/thisdir/diriwant/$1

fi

The Usage part works just fine, but of course when it hits the CD command, it give me an error, more or less that "cd" is not found.

Now i've been told the cd command can't be used in a script because its part of the shell, but i would think there is some way to call it so that it responds without placing you back in your home directory or erroring out.

any idea's? :huh:

Link to comment
https://www.neowin.net/forum/topic/305273-using-cd-in-ksh-script/
Share on other sites

You're doing it too hard, just make an alias:

alias lcd='cd /where-ever/you-want/it/$1'

Or whatever you want to call the alias, lcd is just an example :)

And the reason you can't use cd in a script is because the parent process does not gain the environmental path of the child process (the script).

You could go around this by using source but aliasing is tons easier and faster.

As an additional note, I tried this on my Windows box here at work (with MS SFU installed), and it works (minus the fact that daPhoenix pointed out about the parent {your shell} not inheriting the environmnet {current directory} from the child {your godir script}).

Here was my modified script that used my C: drive and pulled a listing from the directory I specified. As the ls command is after the cd, it listed files from the specified directory, as expected.

Not sure why you were having problems with "cd" not being recognized. :unsure:

#!/bin/ksh


if [ $# -eq 0 ]; then
echo ""
echo "Usage: godir {dirname}"
echo ""
exit
else

cd /dev/fs/C/$1
ls

fi

  Quote
You're doing it too hard, just make an alias

urmmm, actually i did -i'm lazy that way :p

but i want this script to work too, i beleive i found the problem however -there were some oddly defined variables in my .kshrc for cd/_cd that kept throwing it off.

thanks for the insight guys

:cool:

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.