Yashwanth Lagisetty Yashwanth Lagisetty - 5 months ago 35
Bash Question

How to mkdir in if statement

I'm new to coding and trying to teach myself. I was wondering why I keep getting "notcoolbeans" instead of creating the directory?

!/bin/sh
if [ $mkdir /Users/Matt/Desktop/Yaya = 1 ];
then
echo "theres beans"
else
echo "notcoolbeans"
fi


The directory does not already exist. I am trying to make it.

Answer

A correct implementation would look like this:

#!/bin/sh
if mkdir /Users/Matt/Desktop/Yaya; then
  echo "theres beans"
else
  echo "notcoolbeans"
fi

Items of note:

  • A valid shebang starts with #!, not !. (BTW, consider #!/bin/bash or #!/bin/ksh instead of #!/bin/sh if you want a more full-featured scripting language).
  • [ ] is not part of the if statement. It's a command that runs tests and sets exit status on output, but if you want to test the exit status of a different command, there's no call to use it.
  • $mkdir is trying to expand a variable named mkdir. No such variable can be reasonably expected to exist in a new shell; if it's empty, then the result is [ /Users/Matt/Desktop/Yaya = 1 ]. "/Users/Matt/Desktop/Yaya" and "1" are not identical strings, so this always fails.
Comments