¿Cómo obtener la fecha/hora de creación del archivo en Bash / Debian?


Estoy usando Bash en Debian GNU/Linux 6.0. ¿Es posible obtener la fecha/hora de creación del archivo? No la fecha/hora de modificación. ls -lh a.txt y stat -c %y a.txt ambos solo dan el tiempo de modificación.

Author: NoodleFolk, 2013-02-13

11 answers

Desafortunadamente, su búsqueda no será posible en general, ya que solo hay 3 valores de tiempo distintos almacenados para cada uno de sus archivos según lo definido por el estándar POSIX (consulte Definiciones Base sección 4.8 File Times Update)

Cada archivo tiene tres marcas de tiempo asociadas distintas: la hora del último acceso a los datos, la hora de la última modificación de los datos y la hora del archivo último cambio de estado. Estos valores se devuelven en el archivo características estructura estructura stat , como se describe en .

EDITAR: Como se menciona en los comentarios a continuación, dependiendo del sistema de archivos utilizado los metadatos pueden contener la fecha de creación del archivo. Tenga en cuenta, sin embargo, el almacenamiento de información como esa no es estándar. Dependiendo de esto puede llevar a problemas de portabilidad al moverse a otro sistema de archivos, en caso de que el que realmente se usa lo almacene de todos modos.

 67
Author: mikyra,
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-09-13 21:43:39
ls -i file #output is for me 68551981
debugfs -R 'stat <68551981>' /dev/sda3 # /dev/sda3 is the disk on which the file exists

#results - crtime value
[root@loft9156 ~]# debugfs -R 'stat <68551981>' /dev/sda3
debugfs 1.41.12 (17-May-2010)
Inode: 68551981   Type: regular    Mode:  0644   Flags: 0x80000
Generation: 769802755    Version: 0x00000000:00000001
User:     0   Group:     0   Size: 38973440
File ACL: 0    Directory ACL: 0
Links: 1   Blockcount: 76128
Fragment:  Address: 0    Number: 0    Size: 0
 ctime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013
 atime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013
 mtime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013
**crtime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013**
Size of extra inode fields: 28
EXTENTS:
(0-511): 352633728-352634239, (512-1023): 352634368-352634879, (1024-2047): 288392192-288393215, (2048-4095): 355803136-355805183, (4096-6143): 357941248-357943295, (6144
-9514): 357961728-357965098
 31
Author: user2725883,
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-11-17 10:35:56

La respuesta de Mikyra es buena.El hecho justo como lo que dijo.

[jason@rh5 test]$ stat test.txt
  File: `test.txt'
  Size: 0               Blocks: 8          IO Block: 4096   regular empty file
Device: 802h/2050d      Inode: 588720      Links: 1
Access: (0664/-rw-rw-r--)  Uid: (  500/   jason)   Gid: (  500/   jason)
Access: 2013-03-14 01:58:12.000000000 -0700
Modify: 2013-03-14 01:58:12.000000000 -0700
Change: 2013-03-14 01:58:12.000000000 -0700

Si desea verificar qué archivo se creó primero,puede estructurar su nombre de archivo añadiendo la fecha del sistema cuando cree una serie de archivos.

 14
Author: jason,
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-03-14 09:10:08

Tenga en cuenta que si tiene su sistema de archivos montado con noatime por razones de rendimiento, entonces atime probablemente mostrará el tiempo de creación. Dado que noatime resulta en un aumento masivo del rendimiento (al eliminar una escritura de disco por cada vez que se lee un archivo), puede ser una opción de configuración sensata que también le da los resultados que desea.

 13
Author: unit3,
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-03-14 04:36:27

La fecha/hora de creación normalmente se almacena no. Así que no, no puedes.

 5
Author: ,
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-02-12 21:34:57

Menús Ls-i.xml

94490 menús.XML Aquí el número 94490 representa inode

Luego haga a:

Df-h

Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/vg-root   4.0G  3.4G  408M  90% /
tmpfs                 1.9G     0  1.9G   0% /dev/shm
/dev/sda1             124M   27M   92M  23% /boot
/dev/mapper/vg-var    7.9G  1.1G  6.5G  15% /var

Para encontrar el punto de montaje del sistema de archivos raíz"/", porque los menús de archivos.xml está en ' / 'que es'/dev / mapper / vg-root '

Debugfs - R ' stat '/dev/mapper / vg-root

La salida puede ser como la siguiente:

Debugfs - R ' stat '/dev/mapper / vg-root

debugfs 1.41.12 (17-May-2010)
Inode: 94490   Type: regular    Mode:  0644   Flags: 0x0
Generation: 2826123170    Version: 0x00000000
User:     0   Group:     0   Size: 4441
File ACL: 0    Directory ACL: 0
Links: 1   Blockcount: 16
Fragment:  Address: 0    Number: 0    Size: 0
ctime: 0x5266e438 -- Wed Oct 23 09:46:48 2013
atime: 0x5266e47b -- Wed Oct 23 09:47:55 2013
mtime: 0x5266e438 -- Wed Oct 23 09:46:48 2013
Size of extra inode fields: 4
Extended attributes stored in inode body: 
  selinux = "unconfined_u:object_r:usr_t:s0\000" (31)
BLOCKS:
(0-1):375818-375819
TOTAL: 2

Donde se puede ver el tiempo de creación:

ctime: 0x5266e438 -- Wed Oct 23 09:46:48 2013
 4
Author: GustavoH,
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-10-22 22:30:27

Puedes encontrar el tiempo de creación - también conocido como tiempo de nacimiento - usando stat y también coincidir usando find.
Tenemos estos archivos que muestran la última hora modificada:

$ ls -l --time-style=long-iso | sort -k6
total 692
-rwxrwx---+ 1 XXXX XXXX 249159 2013-05-31 14:47 Getting Started.pdf
-rwxrwx---+ 1 XXXX XXXX 275799 2013-12-30 21:12 TheScienceofGettingRich.pdf
-rwxrwx---+ 1 XXXX XXXX  25600 2015-05-07 18:52 Thumbs.db
-rwxrwx---+ 1 XXXX XXXX 148051 2015-05-07 18:55 AsAManThinketh.pdf

Para encontrar archivos creados dentro de un cierto marco de tiempo usando find como se muestra a continuación.
Claramente, el sistema de archivos conoce la hora de nacimiento de un archivo:

$ find -newerBt '2014-06-13' ! -newerBt '2014-06-13 12:16:10' -ls 
20547673299906851  148 -rwxrwx---   1 XXXX XXXX   148051 May  7 18:55 ./AsAManThinketh.pdf
1407374883582246  244 -rwxrwx---   1 XXXX XXXX   249159 May 31  2013 ./Getting\ Started.pdf


Podemos confirmar esto usando stat:

$ stat -c "%w %n" * | sort
2014-06-13 12:16:03.873778400 +0100 AsAManThinketh.pdf
2014-06-13 12:16:04.006872500 +0100 Getting Started.pdf
2014-06-13 12:16:29.607075500 +0100 TheScienceofGettingRich.pdf
2015-05-07 18:32:26.938446200 +0100 Thumbs.db


stat las páginas man explican %w:

%w     time of file birth, human-readable; - if unknown
 2
Author: zanfilip,
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-05-07 18:31:23

Como @mikyra explicó, la fecha y hora de creación no se almacena en ningún lugar.

Todos los métodos anteriores son agradables, pero si desea obtener rápidamente solo la última fecha de modificación, puede escribir:

ls -lit /path

Con la opción -t listará todos los archivos en /path odered por la última fecha de modificación.

 1
Author: Luca Davanzo,
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-02-21 15:41:59

Si realmente desea lograr eso, puede usar un vigilante de archivos como inotifywait.

Observas un directorio y guardas información sobre la creación de archivos en un archivo separado fuera de ese directorio.

while true; do
  change=$(inotifywait -e close_write,moved_to,create .)
  change=${change#./ * }
  if [ "$change" = ".*" ]; then ./scriptToStoreInfoAboutFile; fi
done

Como no se almacena tiempo de creación, puede construir su propio sistema basado en inotify.

 1
Author: william.eyidi,
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-02-26 16:56:21

Citado de https://unix.stackexchange.com/questions/50177/birth-is-empty-on-ext4/131347#131347 , el siguiente shellscript funcionaría para obtener el tiempo de creación:

get_crtime() {
   for target in "${@}"; do
       inode=$(stat -c %i "${target}")
       fs=$(df "${target}"  | tail -1 | awk '{print $1}')
       crtime=$(sudo debugfs -R 'stat <'"${inode}"'>' "${fs}" 2>/dev/null | grep -oP 'crtime.*--\s*\K.*')
       printf "%s\t%s\n" "${target}" "${crtime}"
   done
}
 0
Author: Mike Chen,
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
2017-04-13 12:36:24

Aún mejor:

lsct () 
{ 
    debugfs -R 'stat <'`ls -i "$1" | (read a b;echo -n $a)`'>' `df "$1" | (read a; read a b; echo "$a")` 2> /dev/null | grep --color=auto crtime | ( read a b c d;
    echo $d )
}

Lsct / etc

Mié Jul 20 19:25:48 2016

 0
Author: Zibri,
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-12-23 11:16:17