helpermethod
helpermethod

Reputation: 62234

Unable to use cd within a bash script as intended

Consider this script I wrote, which should go into parent directory, when no argument is given (the if ... part).

#/bin/bash

if (($# == 0))
then
  cd ..
else
  for basename
  do
    cd ${PWD%$basename*}$basename
  done
fi

The problem is, that if I execute it like this

./up.sh

the cd is executed in a subshell, rendering it useless.

If I execute the script using source, it works, but I don't want to call it that way (I makes calling the script to complicated, also you would expect to call it directly if found in the PATH).

Upvotes: 2

Views: 720

Answers (2)

sehe
sehe

Reputation: 393694

I suggest using a function instead of a script

function myscript()
{
     // use $1, $2, "$@" as usual in scripts

     local v1="bla"       # can use globals
     export PATH="$PATH"  # but global shell env too

     somedirectory=.. 
     cd $somedirectory
}

Alternatively, alias would work (but it doesn't support redirection, argument passing, flow control etc well, and you cannot nest them in $() IIRC).

Lastly source the existing script in the current shell like so:

source ./script.sh

ksh and bash have shorthands for that:

. ./script.sh

Beware of scripts with 'exit' statements though: they will exit the parent shell!

Upvotes: 3

phihag
phihag

Reputation: 288230

An arbitrary program (such as your bash program) cannot change the working directory of the parent process, as that would pretty much break all existing processes that spawn children.

You should define a bash alias or function instead. As you have discovered, typing source ./up.sh (or shorter: . ./up.sh) works too.

Upvotes: 3

Related Questions