0

I'm trying to make a script to automatically write my configs to any new Unix system I spin up

In my script I want to make a git directory for a plug-in I'm using in vim and then cd into it, else I want to cd back to the dir I called the script from and exit to avoid running the succeeding git commands in the wrong directory.

As follows:

( mkdir $nerdgitdir && cd $nerdgitdir ) || ( cd $curPwd & exit 1 )

The mkdir $nerdgitdir command runs fine as evident from the existence of the directory, but I never cd into it. I also don't exit the script as the result of a "failed" cd (behaviour on right side of || operator) because the script proceeds to run the git commands in the wrong directory.

Any ideas what I'm doing wrong with this line? It seems like either the cd command should fail, or the expression beyond the || should fail to run, but boolean logic tells me that at least one of them should run.

1 Answer 1

2

You are changing the working directory of the subshell created by (...), not in your current shell. You would need to use {...} instead:

{ mkdir "$nerdgitdir" && cd "$nerdgitdir"; } || exit 1

(There's no point changing the working directory if you are just going to exit.)

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, didn't know
I wasn't calling my script with source so I wanted to return to the directory I called the script from
@TheThing If you run a script normally (i.e. without the source or . commands), it runs as a subprocess, so when it cds it has no effect on the parent process (and therefore you don't need to worry about cding back).
I did not know that haha.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.