I've seen this answer since searching for this, but initially I wrote this script:

for i in `seq 1 $1`; 
   do cd ../;

It doesn't change directory. Why is this, running as

./updir.sh 5
  • Thanks guys. I've gone with the function solution with: function updir() { a=""; for i in seq 1 $1; do a=$a"../"; done; cd $a; }. This allows use of cd - as expected. – David Boshton Dec 6 at 17:39
up vote 5 down vote accepted

Running a script as you show creates a copied environment in a sub-shell, and any changes you make, such as setting directories or environment variables, affect only this sub-shell environment, not the calling shell.

In order to make changes to the current shell from a script, you must run the script within the current shell using the source or . command:

. ./updir.sh 5

You can make this automatic with an alias:

alias updir='. ./updir.sh'

Alternatively, you can use a function instead of a script:

{   for i in `seq 1 $1`; 
       do cd ../;

Because scripts are run in a subshell, which keeps track of the current working directory separately. The simplest solution is to use a function:

function updir() {
  for i in $(seq 1 $1); do
    cd ..
  • 1
    Sorry, my answer crossed with yours, but I am leaving mine because I gave some extra details. – AFH Dec 6 at 16:33

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.