Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8108087
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T00:59:11+00:00 2026-06-06T00:59:11+00:00

If you want to overwrite a file with Bash, this is easy echo Hello

  • 0

If you want to overwrite a file with Bash, this is easy

echo "Hello world" > hosts

This does not seem to work with a file descriptor

$ exec 3<> hosts

$ echo "Hello world" >&3
$ cat hosts
Hello world

$ echo "Hello world" >&3
$ cat hosts
Hello world
Hello world
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T00:59:13+00:00Added an answer on June 6, 2026 at 12:59 am

    That’s correct. The mode in which a file is opened is determined when the shell calls open(2). When you DUP2 an FD (in any language), the flags that were set when the file was opened are shared between open FDs. In your case, O_TRUNC can only be specified when the file is actually opened.

    The important thing to know is that the mode and various flags are determined only when the file is opened using <file, >file, or similar. Copying a FD with the & modifier essentially creates an “alias” that points to the original FD, and retains all the same state as the original. Truncating the file requires re-opening it.

    This is my debugging function if you’d like to play around with file descriptors easily:

    lsfd() {
        local ofd=${ofd:-2} target=${target:-$BASHPID}
    
        while [[ $1 == -* ]]; do
            if [[ -z $2 || $2 == *[![:digit:]]* ]]; then
                cat
                return 1
            fi
            case ${1##+(-)} in
                u)
                    shift
                    ofd=$1
                    shift
                    ;;
                t)
                    shift
                    target=$1
                    shift
                    ;;
                h|\?|help)
                    cat
                    return
            esac
        done <<EOF
    USAGE: ${FUNCNAME} [-h|-?|--help] [-u <fd>] [ -t <PID> ] [<fd1> <fd2> <fd3>...]
    
    This is a small lsof wrapper which displays the open
    file descriptors of the current BASHPID. If no FDs are given,
    the default FDs to display are {0..20}. ofd can also be set in the
    environment.
    
        -u <fd>: Use fd for output. Defaults to stderr. Overrides ofd set in the environment.
        -t <PID>: Use PID instead of BASHPID. Overrides "target" set in the environment.
    EOF
    
        IFS=, local -a 'fds=('"${*:-{0..20\}}"')' 'fds=("${fds[*]}")'
        lsof -a -p $target -d "$fds" +f g -- >&${ofd}
    }
    

    I like to not close stdin, because this can sometimes cause problems, so it gets saved first.

     $ ( { lsfd 3; cat <&3; } {savefd}<&0 <<<'hi' 3>&0- <&"${savefd}" )
    COMMAND PID  USER   FD   TYPE FILE-FLAG DEVICE SIZE/OFF     NODE NAME
    bash    920 ormaaj   3r   REG        LG   0,22        3 59975426 /tmp/sh-thd-8305926351 (deleted)
    hi
    

    As you can see, even if FD 0 is moved to 3 using the 3>&0- operator, the file remains opened O_RDONLY. The choice of > or < is arbitrary with the copy descriptor and only serves to determine the default if the FD on the left of the operator is omitted.

    If you did want to open a new independent FD, something like this could work:

    $ ( {
    cat <&4 >/dev/null; lsfd 3 4; echo there >&4; cat </dev/fd/3
    } {savefd}<&0 <<<'hi' 3>&0- 4<>/dev/fd/3 <&"${savefd}"
    )
    COMMAND  PID  USER   FD   TYPE FILE-FLAG DEVICE SIZE/OFF     NODE NAME
    bash    2410 ormaaj   3r   REG        LG   0,22        3 59996561 /tmp/sh-thd-8305914274 (deleted)
    bash    2410 ormaaj   4u   REG     RW,LG   0,22        3 59996561 /tmp/sh-thd-8305914274 (deleted)
    hi
    there
    

    Now FD 4 is really “re-opened” to the file FD 3 is pointed at, not just duplicated (even if the file has already been unlink(2)‘d, as above). First FD 4 is opened and seeked to the end using cat, then an additional line is written to the file. Meanwhile the seek position of FD 3 is still at the beginning, so the entire resulting file can be cated to the terminal.

    The same principle could be applied to your case.

    $ { echo 'Hello world'; echo 'hi' >/dev/fd/1; } >hosts; cat hosts
    hi
    

    Or probably even better would be to just open and close the file twice using two separate commands, without exec.

    I prefer to avoid using exec just to open file descriptors unless it’s absolutely necessary. You have to remember to explicitly close the file. If you use command grouping instead, files will automatically close themselves, in effect giving them a “scope”. This is similar in principle to Python’s with statement. That might have prevented some confusion.

    See also:

    • http://wiki.bash-hackers.org/howto/redirection_tutorial
    • http://wiki.bash-hackers.org/syntax/redirection
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have archive.zip with two files: hello.txt and world.txt I want to overwrite hello.txt
I want to overwrite the hosts file on the Windows machine if the user
I want to declare three properties in my MSBuild file and overwrite one property
I'm using fstream to open a file for write. I don't want to overwrite
I am creating a file in C# (.NET Web Service) and do not want
I'm using this method to copy a file: [fileManager copyItemAtPath:sourcePath toPath:targetPath error:&error]; I want
Is it possible to overwrite CSS file permanently using JavaScript / jQuery? I want
I want to overwrite an XML File that is stored in Project's Resource folder.
Hi i want to overwrite the content(object) in a specific file i have set
Given two integers X and Y, I want to overwrite bits at position P

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.