How do file descriptors work?

前端 未结 4 1734
礼貌的吻别
礼貌的吻别 2020-11-29 16:46

Can someone tell me why this does not work? I\'m playing around with file descriptors, but feel a little lost.

#!/bin/bash
echo \"This\"
echo \"is\" >&         


        
4条回答
  •  一向
    一向 (楼主)
    2020-11-29 17:37

    To add on to the answer from rsp and respond the question in the comments of that answer from @MattClimbs.

    You can test if the file descriptor is open or not by attempting to redirect to it early and if it fails, open the desired numbered file descriptor to something like /dev/null. I do this regularly within scripts and leverage the additional file descriptors to pass back additional details or responses beyond return #.

    script.sh

    #!/bin/bash
    2>/dev/null >&3 || exec 3>/dev/null
    2>/dev/null >&4 || exec 4>/dev/null
    
    echo "This"
    echo "is" >&2
    echo "a" >&3
    echo "test." >&4
    

    The stderr is redirected to /dev/null to discard the possible bash: #: Bad file descriptor response and the || is used to process the following command exec #>/dev/null when the previous one exits with a non zero status. In the event that the file descriptor is already opened, the two tests would return a zero status and the exec ... command would not be executed.

    Calling the script without any redirections yields:

    # ./script.sh
    This
    is
    

    In this case, the redirections for a and test are shipped off to /dev/null

    Calling the script with a redirection defined yields:

    # ./script.sh 3>temp.txt 4>>temp.txt
    This
    is
    # cat temp.txt
    a
    test.
    

    The first redirection 3>temp.txt overwrites the file temp.txt while 4>>temp.txt appends to the file.

    In the end, you can define default files to redirect to within the script if you want something other than /dev/null or you can change the execution method of the script and redirect those extra file descriptors anywhere you want.

提交回复
热议问题