AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / unix / Perguntas / 445419
Accepted
Michael
Michael
Asked: 2018-05-23 12:17:13 +0800 CST2018-05-23 12:17:13 +0800 CST 2018-05-23 12:17:13 +0800 CST

Como remover arquivos temporários sem alterar o registro de data e hora de modificação do diretório?

  • 772

Eu trabalho em testcase, cada um sendo um subdiretório de ~/test. É conveniente ver quais foram os casos de teste que trabalhei mais recentemente usando algo como ls -rtl. Agora eu gostaria de remover certos arquivos temporários dos diretórios de teste; infelizmente, isso mudaria o registro de data e hora dos diretórios.

É possível remover um arquivo de um diretório sem alterar o registro de data e hora de modificação do diretório?

directory timestamps
  • 3 3 respostas
  • 1997 Views

3 respostas

  • Voted
  1. Best Answer
    ilkkachu
    2018-05-23T12:29:03+08:002018-05-23T12:29:03+08:00

    Você terá que redefinir o registro de data e hora no diretório após remover os arquivos. Assumindo ferramentas GNU, algo assim deve funcionar:

    mtime=$(stat -c %y dir)            # get the timestamp, store in $mtime
    rm dir/somefile dir/someotherfile  # do whatever you need
    touch -d "$mtime" dir              # set the timestamp back
    

    Isso redefine os registros de data e hora de modificação ( mtime) e acesso ( atime) no diretório para o registro de data e hora de modificação original, mas também define o registro de data e hora de alteração ( ctime) para a hora atual. Mudar o ctimeé inevitável, mas você provavelmente não se importa com isso ou atime.

    • 3
  2. Dave
    2019-02-16T17:16:01+08:002019-02-16T17:16:01+08:00

    O touchcomando fornece a -ropção que permite tocar em um arquivo com os mesmos carimbos de data/hora de um arquivo de referência. Como tal, você poderia fazer isso:

    touch -r /dir/somefile /tmp/_thetimestamps  # save the timestamps in /tmp/_thetimestamps
    rm /dir/somefile                            # do whatever you need
    touch -r /tmp/_thetimestamps /dir           # set the timestamps back
    

    Homem do Linux :

    -r, --reference=FILE
          use this file's times instead of current time
    

    Homem Unix :

    -r       Use the access and modifications times from the specified file
             instead of the current time of day.
    
    • 2
  3. Jay Taylor
    2020-02-04T10:05:40+08:002020-02-04T10:05:40+08:00

    Aqui está a versão Python da excelente resposta de ikkachu :

    https://gist.github.com/jaytaylor/ea1b6082ea5bcea7a6b65518d91238f5

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    """
    Removes a file or directory while preserving the modification time (mtime) of
    the parent directory.
    
    Pure-python implementation.
    
    See also:
        https://unix.stackexchange.com/a/565595/22709
    """
    
    import argparse
    import logging
    import os
    import platform
    import re
    import shutil
    import stat
    import sys
    
    log_formatter = logging.Formatter('%(asctime)s, %(levelname)s %(message)s')
    
    logging.basicConfig(level=logging.INFO, formatter=log_formatter)
    logger = logging.getLogger(__name__)
    
    def parse_opts(args):
        parser = argparse.ArgumentParser(
            description='Removes a file or directory while preserving the modification time (mtime) of the parent directory.',
            argument_default=False,
        )
        parser.add_argument('-f', '--force', default=False, action='store_true', help='Ignore nonexistent files and arguments')
        parser.add_argument('-i', '--interactive', default=False, action='store_true', help='Prompt for confirmation before taking action on a target')
        parser.add_argument('--no-preserve-root', default=False, action='store_true', help="Do not treat '/' specially")
        parser.add_argument('-r', '--recursive', default=False, action='store_true', help='Remove directories and their contents recursively')
        parser.add_argument('-v', '--verbose', default=False, action='store_true', help='Display verbose log output')
        parser.add_argument('paths', type=str, nargs='+', help='Filesystem path(s) to remove')
    
        opts = parser.parse_args(args)
        if opts.verbose:
            logger.setLevel(logging.DEBUG)
    
        return opts
    
    # n.b. Use the appropriate input function depending on whether the runtime
    #      environment is Python version 2 or 3.
    _input_fn = input if sys.version_info > (3, 0) else raw_input
    
    def _prompt_for_confirmation(path, opts):
        if not opts.interactive:
            return True
    
        response = _input_fn('Permanently remove "%s"? (Y/n)' % (path,))
        return response in ('Y', 'y')
    
    def require_write_permissions(path):
        parent = os.path.dirname(path)
        if not os.access(parent, os.W_OK):
            raise Exception('Missing necessary write permission for parent directory "%s"; operation aborted' % (parent,))
    
    def rm_preserving_parent_mtime(path, opts):
        """
        Deletes the specified path, and restores the filesystem access and modified
        timestamp values afterward removing path.
    
        IMPORTANT
        ---------
        Take note of the permission test before removing the target. These checks
        verify write access to parent's parent.
    
        Without the check, there is a risk that the file will be removed and then
        setting mtime fails.  When this happens, the entire purpose of this program is defeated.
        """
        if not opts.no_preserve_root and (path == os.sep or (platform.system() == 'Windows' and re.match(r'^[A-Z]:%s?' % (os.sep,), path))):
            raise Exception('Cowardly refusing to operate on root path')
    
        if path in ('', '.', '..'):
            raise Exception('Invalid path "%s", must have a parent directory' % (path,))
    
        parent = os.path.dirname(path)
    
        if path == parent:
            raise Exception('Invalid path, parent directory="%s" should not equal path="%s"' % (parent, path))
    
        st = os.stat(parent)
        atime = st[stat.ST_ATIME]
        mtime = st[stat.ST_MTIME]
    
        modified = False
    
        try:
            if os.path.isfile(path):
                require_write_permissions(parent)
                if _prompt_for_confirmation(path, opts):
                    logger.debug('Removing file "%s"' % (path,))
                    modified = True
                    os.remove(path)
            elif os.path.isdir(path):
                if not opts.recursive:
                    raise Exception('Cannot remove "%s": Is a directory' % (path,))
                require_write_permissions(parent)
                if _prompt_for_confirmation(path, opts):
                    logger.debug('Removing directory "%s"' % (path,))
                    modified = True
                    shutil.rmtree(path)
            else:
                raise Exception('Path "%s" is not a file or directory' % (path,))
        finally:
            if modified:
                logger.debug('Restoring access and modification timestamps for parent="%s"' % (parent,))
                os.utime(parent, (atime, mtime))
    
    def main(paths, opts):
        try:
            for path in paths:
                rm_preserving_parent_mtime(path, opts)
            return 0
        except BaseException:
            logger.exception('Caught exception in main')
            if opts.force:
                return 0
            return 1
    
    if __name__ == '__main__':
        opts = parse_opts(sys.argv[1:])
        sys.exit(main(opts.paths, opts))
    

    Para obter soluções completas para mover ou excluir arquivos preservando o diretório pai mtime, consulte estes scripts python: https://gist.github.com/jaytaylor/e2e0b53baf224f4e973b252370499de7

    • -1

relate perguntas

  • Como o fsync trata os links de diretório?

  • Como excluir todas as pastas em um diretório usando o bash?

  • ptpd 3.2.1 no Ubuntu 14.04

  • Maneira mais rápida de determinar se o conteúdo do diretório mudou desde a última vez

  • Dúvida de carimbo de data/hora do Unix

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Como exportar uma chave privada GPG e uma chave pública para um arquivo

    • 4 respostas
  • Marko Smith

    ssh Não é possível negociar: "nenhuma cifra correspondente encontrada", está rejeitando o cbc

    • 4 respostas
  • Marko Smith

    Como podemos executar um comando armazenado em uma variável?

    • 5 respostas
  • Marko Smith

    Como configurar o systemd-resolved e o systemd-networkd para usar o servidor DNS local para resolver domínios locais e o servidor DNS remoto para domínios remotos?

    • 3 respostas
  • Marko Smith

    Como descarregar o módulo do kernel 'nvidia-drm'?

    • 13 respostas
  • Marko Smith

    apt-get update error no Kali Linux após a atualização do dist [duplicado]

    • 2 respostas
  • Marko Smith

    Como ver as últimas linhas x do log de serviço systemctl

    • 5 respostas
  • Marko Smith

    Nano - pule para o final do arquivo

    • 8 respostas
  • Marko Smith

    erro grub: você precisa carregar o kernel primeiro

    • 4 respostas
  • Marko Smith

    Como baixar o pacote não instalá-lo com o comando apt-get?

    • 7 respostas
  • Martin Hope
    rocky Como exportar uma chave privada GPG e uma chave pública para um arquivo 2018-11-16 05:36:15 +0800 CST
  • Martin Hope
    Wong Jia Hau ssh-add retorna com: "Erro ao conectar ao agente: nenhum arquivo ou diretório" 2018-08-24 23:28:13 +0800 CST
  • Martin Hope
    Evan Carroll status systemctl mostra: "Estado: degradado" 2018-06-03 18:48:17 +0800 CST
  • Martin Hope
    Tim Como podemos executar um comando armazenado em uma variável? 2018-05-21 04:46:29 +0800 CST
  • Martin Hope
    Ankur S Por que /dev/null é um arquivo? Por que sua função não é implementada como um programa simples? 2018-04-17 07:28:04 +0800 CST
  • Martin Hope
    user3191334 Como ver as últimas linhas x do log de serviço systemctl 2018-02-07 00:14:16 +0800 CST
  • Martin Hope
    Marko Pacak Nano - pule para o final do arquivo 2018-02-01 01:53:03 +0800 CST
  • Martin Hope
    Kidburla Por que verdadeiro e falso são tão grandes? 2018-01-26 12:14:47 +0800 CST
  • Martin Hope
    Christos Baziotis Substitua a string em um arquivo de texto enorme (70 GB), uma linha 2017-12-30 06:58:33 +0800 CST
  • Martin Hope
    Bagas Sanjaya Por que o Linux usa LF como caractere de nova linha? 2017-12-20 05:48:21 +0800 CST

Hot tag

linux bash debian shell-script text-processing ubuntu centos shell awk ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve