Prompt pliz script in Linux, which would do the following:

  1. Check if folder exists
  2. If yes, then do nothing.
  3. If not, create this folder.
  • one
    @evm Please do not forget to accept those answers to questions that you consider most correct and useful. - Nicolas Chabanovsky
  • one
    And why is this question raised? It's a completely nooby question, which is very easy to find the answer :) - cy6erGn0m
  • one
    @ cy6ergn0m +1, finally it is not clear ... - kirelagin

3 answers 3

In the bash script (mkdir.sh) you can do this:

DIR=$1 if [ ! -d "$DIR" ]; then # Создать папку, только если ее не было mkdir $DIR fi 

Run as

 $ ./mkdir.sh 

You can also check if the name is not a symbolic link:

 DIR=$1 if [[ ! -d "$DIR" && ! -L "$DIR" ]] ; then # Создать папку, только если ее не было и не было символической ссылки mkdir $DIR fi 
  • This option has a significant drawback: there is a time difference between checking and creating. This means that if someone slips between, then this option will be reduced to the answer of Kirelagin (i.e. the variable $? Will still be set to one, so does this workaround give the illusion of protection from one in $?) . And since there is no difference, and the version of kirelagin is shorter and simpler, then it is better. - cy6erGn0m

mkdir <name> 2> /dev/null

  • This option is also good. Just need to remember when writing a script that after an error mkdir expose $? in the unit. - stanislav
  • Well, no specific conditions sounded - I wrote the easiest option that came to mind :). - kirelagin
  • Yes, it does. Thank. But in a script that runs as ./some.sh hangs up at this place ( - Jenkamen
  • Most likely, you forgot to remove the triangular brackets around the name (folder name) FACEPALM - kirelagin
  • Correctly use this: mkdir "$ 1" 2> / dev / null - kirelagin
 mkdir -p 

It will create subdirectories if necessary (mkdir -pa / b / c), and in the meantime it will not react to the already created directory.