Bash read/write file descriptors — seek to start of file

前端 未结 7 1808
暗喜
暗喜 2020-12-08 08:48

I tried to use the read/write file descriptor in bash so that I could delete the file that the file descriptor referred to afterward, as such:

F=$(mktemp)
ex         


        
7条回答
  •  天命终不由人
    2020-12-08 09:18

    To 'rewind' the file descriptor, you can simply use /proc/self/fd/3

    Test script :

    #!/bin/bash
    
    # Fill data
    FILE=test
    date +%FT%T >$FILE
    
    # Open the file descriptor and delete the file
    exec 5<>$FILE
    rm -rf $FILE
    
    # Check state of the file
    # should return an error as the file has been deleted
    file $FILE
    
    # Check that you still can do multiple reads or additions
    for i in {0..5}; do
        echo ----- $i -----
    
        echo . >>/proc/self/fd/5
        cat /proc/self/fd/5
    
        echo
        sleep 1
    done
    

    Try to kill -9 the script while it is running, you will see that contrary to what happens with the trap method, the file is actually deleted.

提交回复
热议问题