3
#!/bin/bash echo 123456789 > out.txt exec 3<> out.txt read -n 4 <&3 echo -n 5 >&3 exec 3>&- 

Was asked the content of out.txt at the end of script, in an interview written exam. I did run the script afterwords and it gave me 123456789. Yet I have no idea what is going on in the script, especially the parts with the exec statements. I looked up the manpage and google search results for exec and could not find anything on the 3<> bit. Could somebody, well versed in shell scripting, explain what is going on here?

3
  • 4
    Have a look here. Commented Feb 15, 2020 at 23:25
  • 1
    wow, this was ripped off line for line. thanks @Freddy for pointing me to the relevant resource Commented Feb 15, 2020 at 23:30
  • 1
    Add an echo "$REPLY" anywhere after the line with the read command and run it. you should 1234 which is what the -n4 does Commented Feb 15, 2020 at 23:36

1 Answer 1

9

echo 123456789 > out.txt writes the string 123456789 in out.txt file.

The exec 3<>out.txt construct opens the file out.txt for reading < and writing > and attaches it to file descriptor #3.

read -n 4 <&3 reads 4 characters.

echo -n 5 >&3 writes 5 (replacing 5 by 5).

exec 3>&- closes file descriptor #3.

Resulting in

cat out.txt 123456789 

Section about execint bash(1) states that:

exec [-cl] [-a name] [command [arguments]] If command is specified, it replaces the shell. [...] If command is not specified, any redirections take effect in the current shell [...].

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.