Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you write if else statements within a Shellscript for Mac OS?

My goal is a simple one. I am trying to write a MacOs Shell Script containing if else statements. Specifically, I want the script to create a new file called "targets" if a file named "newFolder" exists on my desktop. Secondly I want the script to create a new folder called "days" if a folder named "ifolder" exists on the desktop and if it does not exist create a folder called "reactProjects".

Here is what I’ve tried:

#!/bin/bash

cd ..
cd ..
cd desktop

if exist newFolder mkdir targets

if exist targets mkdir days else mkdir reactProjects

But I am having an error occur when I try run it through the terminal. The error states:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ifExample.sh: line 10: syntax error: unexpected end of file

This is my first script shell, so I may have some syntax mistakes, but please let me know if you understand how to do this.

Thanks!

>Solution :

You should know more about conditionals in bash so I encourage you to read this article.

But before that your solution should look like this:

#!/bin/bash

cd ..
cd ..
cd desktop

if [ -f newFolder ]; then
   mkdir targets
fi

if [ -d ifolder ]; then
   mkdir days
else
   mkdir reactProjects
fi
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading