Add Conditions to ZSH Functions to Prevent Mistakes

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

Forgetting to pass an argument to a zsh function could result in creating unnecessary folders or cloning code you didn't mean to. It's best to check for arguments to prevent unwanted results.

Instructor: [0:00] You know, our vanilla and lesson functions, they both have required names of the project, or branch. So let's protect ourselves in case we forget those with an if statement. This has required white space.

[0:11] We're going to check if the first argument is nothing. Then, if that's true, we'll go ahead and echo, "Please name your project," and return out so that nothing runs beyond this point. We can close out our if statement.

[0:27] Then, if I save this, and source my files so my terminal pulls in the new function, I'll try running plus vanilla without a name. It'll say, "Please name your project."

[0:36] We'll do the same thing inside of our lesson function down here. Just paste this. It'll just echo out, "Please name your branch." Hit save here. Source our file again.

[0:47] We'll create a new vanilla project. Name it "If Check." Let that run. We'll clone. Create the repo. Install everything, and launch VS Code. Then we can go back and go into...

[0:58] Then we can go back and go into our project here. This will be called if-check.

[1:04] If you try and add a new lesson without a branch name, it'll say, "Please name your branch." If I name it my-branch, hit enter, [inaudible] everything, and then launch the code Sandbox for the if-check repo on the my-branch.