Wednesday, April 6, 2022

[SOLVED] Bash binary operators usage

Issue

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.


Solution

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.)



Answered By - chepner
Answer Checked By - David Goodson (WPSolving Volunteer)