¿Cómo hacer mkdir solo si no existe un directorio?


Estoy escribiendo un script de shell para ejecutarlo bajo KornShell (ksh) en AIX. Me gustaría usar el comando mkdir para crear un directorio. Pero el directorio puede que ya exista, en cuyo caso no quiero hacer nada. Así que quiero probar para ver que el directorio no existe, o suprimir el error "El archivo existe" que mkdir lanza cuando intenta crear un directorio existente.

¿Alguna idea sobre la mejor manera de hacer esto?

Author: Jahid, 2009-04-27

13 answers

Intente mkdir -p:

mkdir -p foo

Tenga en cuenta que esto también creará cualquier directorio intermedio que no exista; por ejemplo,

mkdir -p foo/bar/baz

Creará los directorios foo, foo/bar, y foo/bar/baz si no existen.

Si desea un error cuando los directorios padre no existen, y desea crear el directorio si no existe, entonces puede test para la existencia del directorio primero:

[ -d foo ] || mkdir foo
 2385
Author: Brian Campbell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-24 10:09:33

Esto debería funcionar:

$ mkdir -p dir

O:

if [[ ! -e $dir ]]; then
    mkdir $dir
elif [[ ! -d $dir ]]; then
    echo "$dir already exists but is not a directory" 1>&2
fi

Que creará el directorio si no existe, pero le advertirá si el nombre del directorio que está tratando de crear ya está en uso por algo que no sea un directorio.

 114
Author: Alnitak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-27 16:02:35

Use la bandera-p.

man mkdir
mkdir -p foo
 71
Author: jimmyorr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-27 14:50:09

Definir árboles de directorios complejos con un comando

mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}
 61
Author: Oleg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-21 20:08:57

Si no desea mostrar ningún mensaje de error:

[ -d newdir ] || mkdir newdir

Si desea mostrar su propio mensaje de error:

[ -d newdir ] && echo "Directory Exists" || mkdir newdir
 23
Author: Jahid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-27 05:17:35

El viejo probado y verdadero

mkdir /tmp/qq >/dev/null 2>&1

Hará lo que quieras sin ninguna de las condiciones de carrera que muchas de las otras soluciones tienen.

A veces las soluciones más simples (y más feas) son las mejores.

 18
Author: paxdiablo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-21 08:40:59

mkdir foo funciona incluso si el directorio existe. Para que funcione solo si el directorio llamado "foo" no existe, intente usar la bandera -p.

Ejemplo: -

mkdir -p foo

Esto creará el directorio llamado "foo" solo si no existe. :)

 11
Author: Atul Ranjan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-20 12:41:38
directory_name = "foo"

if [ -d $directory_name ]
then
    echo "Directory already exists"
else
    mkdir $directory_name
fi
 9
Author: Visuwa Bharathi K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-03 14:57:09

O si quieres comprobar la existencia primero:

if [[ ! -e /path/to/newdir ]]; then
            mkdir /path/to/newdir
fi

-e es la prueba exist para korn shell.

También puedes buscar en Google un manual de korn shell.

 7
Author: alkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-27 15:16:05

Mkdir ya no admite el interruptor-p en sistemas Windows 8+.

Puedes usar esto:

IF NOT EXIST dir_name MKDIR dir_name
 3
Author: Karanvir Kang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-22 12:39:41

Puede usar if loop para verificar si el directorio existe o no, si no sale, entonces cree el directorio.

1) dir = / home / dir_name

if [ ! -d $dir ]
then
     mkdir $dir
else
     echo "Directory exists"  
fi

2) Puede usar el directorio mkdir con la opción-p para crear un directorio. Comprobará si el directorio no está disponible.

mkdir -p $dir

Mkdir-p también permite crear la estructura de árbol del directorio. Si desea crear los directorios padre e hijo usando el mismo comando, puede optar por mkdir-p

mkdir -p /home/parent_dir /home/parent_dir/child1 /home/parent_dir/child2
 1
Author: AbhinavVaidya8,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-22 01:50:14

Esta es una función simple (shell bash) que le permite crear un directorio si no existe.

#----------------------------------
# Create a directory if it doesn't exist
#------------------------------------
createDirectory() {
    if [ ! -d $1 ]
        then
        mkdir -p $1
    fi
}

Puede llamar a la función anterior como :

CreateDirectory/tmp / fooDir / BarDir

Lo anterior crea fooDir y BarDir si no existen. Observe la opción" - p " en el comando mkdir que crea directorios recursivamente. Espero que esto ayude.

 0
Author: Balaji Boggaram Ramanarayan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-14 18:54:02
mkdir -p sam
  • mkdir = Make Directory
  • - p =parents padres
  • (no hay error si existe, hacer directorios padre según sea necesario)
 0
Author: Paritosh Yadav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-20 09:50:04