Shell Script that goes up N folders in the file sy

2019-04-15 00:40发布

问题:

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?

回答1:

I've had the same issue on Linux, actually, if I understood correctly what I've found after some searching, this is what happens:

The command is launched in a subshell, and in that subshell the path gets changed, you don't see the change because when the script finishes you get back to the starting (parent) shell.

I solved this by putting that useful script in my .bashrc as a function, like this:

up(){
    #code goes here
}

Another option is to source the script every time you launch it but I prefer the first one.



回答2:

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



回答3:

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

up() { LIMIT=$1; P=$PWD; for ((i=1; i <= LIMIT; i++)); do P=$P/..; done; cd $P; }

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.



回答4:

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)

. cdup 3 
source cdup 3

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



回答5:

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"



标签: macos bash shell