0

I try to change the directory inside a bash-script function, but it does not have any effect. Possibly, because the function is run inside a separate process...

Here is a simple script without a function call. It works perfectly:

#!/bin/bash

# Doing it without the function works:
echo "Dir: $PWD" # Output: "/Users/philipp/"
cd ~/Documents
echo "Dir: $PWD" # Output: "/Users/philipp/Documents"

However, once I move the cd into a function, it does not change the directory for the rest of the shell script anymore:

#!/bin/bash

show_or_run() {
    if [[ "yes" = $RUN ]]; then
        eval "$@"
    else
        echo "   $ $@"
    fi
}

echo "Dir: $PWD" # Output: "/Users/philipp/"
show_or_run cd ~/Documents
echo "Dir: $PWD" # Output: "/Users/philipp/", but expected "/Users/philipp/Documents"
Philipp
  • 101
  • 1
    Hmm is RUN set as an environment variable in the outer scope. Where is it defined? If it isn't defined then you don't change directory. – Att Righ May 22 '18 at 14:18
  • oh!! You are right @AttRigh... I actually did not set the RUN variable – Philipp May 22 '18 at 14:24
  • Cool cool. Because of this the question seems kind of specific - so I would be in favour of closing it... unless someone told me a good reason for leaving it around - not that this is something I have the power to do :). I guess knowing about "eval cd blah" is interesting... I'm not sure this question is the best way to index this fact thought – Att Righ May 22 '18 at 14:28

0 Answers0