Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding bash exec {logout}?

Tags:

bash

What does the following Bash command do?

exec {logout}> >(tee -a "${LOGFILE}")

or

exec {logout}>> "${LOGFILE}"
like image 748
Clemens Avatar asked Dec 07 '25 06:12

Clemens


1 Answers

From the Bash reference about redirections:

Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form {varname}. In this case, for each redirection operator except >&- and <&-, the shell will allocate a file descriptor greater than 10 and assign it to {varname}.

  • In the case

    exec {logout}> >(tee -a "${LOGFILE}")
    

    Bash will open a new file descriptor, assign the corresponding integer to the variable logout, and link this file descriptor to the process substitution

    tee -a "${LOGFILE}"
    

    After you enter this command, you can check that the variable logout has been assigned to an integer. Then, each time you redirect a stream to the file descriptor $logout, it will be fed to tee:

    #!/bin/bash
    
    logfile=testlogfile
    
    exec {logout}> >(tee -a "$logfile")
    echo "logout=$logout"
    
    # now output some stuff to fd $logout:
    echo >&"$logout" "Hello file descriptor $logout"
    
    # it will send the message to tee, so that you'll see it on stdout
    # and will also be appended to $logfile
    
    # Check that output really got to $logfile:
    cat "$logfile"
    
  • The second case is similar, but this time, output going to file descriptor $logout will only be appended to $logfile (and not passed to tee, so you won't see it on stdout).

After this, you don't really need to close the file descriptor, it will be closed automatically at the end of the script (or of the session); but if you really want to close it anyway:

exec {logout}>&-

You can check the file descriptors that are opened with

ls /dev/fd
like image 147
gniourf_gniourf Avatar answered Dec 09 '25 22:12

gniourf_gniourf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!