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"
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:18RUN
variable – Philipp May 22 '18 at 14:24