I just found this very usefull shell script here on SO but unfortunately it's not working on Mac OS X 10.5.
This is the script in question(copied it for convenience):
#!/bin/bash
LIMIT=$1
P=$PWD
for ((i=1; i <= LIMIT; i++))
do
P=$P/..
done
cd $P
I tried to echo $P
at the very end and it's returning the right path, but still cd $P
doesn't seem to be working.
So I tried to manually enter P="some/path"
and cd $P
in the terminal and it worked.
I don't get why the same command isn't working in the script. Could it be a security thing?
Any suggestions?
once the shell script ends it will put you right back in the directory it was executed from. The cd will only effect the cwd of the script process
If you want to run the script within the context of your current shell just do one of the following (assuming your shell script is called cdup)
The source command (and its alias .) run the provided script within the context of your current shell, i.e. they do not start a separate sub-shell to run the command so your cd will work as it is within the current shell
I've had the same issue on Linux, actually, if I understood correctly what I've found after some searching, this is what happens:
I solved this by putting that useful script in my .bashrc as a function, like this:
Another option is to source the script every time you launch it but I prefer the first one.
A small addition to the up() - function; add the test for no value:
LIMIT=$1
if [ -z "$LIMIT" ]; then
LIMIT=1
fi
and no more "cd .." - just "up"
You are only changing the working directory for the copy of the shell that is running the script as an interpreter, not the original shell program that you launched the script from.
For a bash-like shell, in order to run a sequence of commands that operate on the interactive shell session, you can define them as a shell function.
e.g. type the following
and you'll define an up command that works the way you intended.
You could put this function definition into a file that is sourced when you login, such as .bashrc, to keep it conveniently defined on login.