How to save /dev/stdout target location in a bash script?

I have a certain bash script, which wants to preserve original /dev/stdout location before replacing 1st file descriptor with other location.

So, naturally, I wrote something like

old_stdout=$(readlink -f /dev/stdout) 

And it didn't work. Very quickly I understand what the problem was:

[email protected]:~$ echo $(readlink -f /dev/stdout) /proc/5175/fd/pipe:[31764] [email protected]:~$ readlink -f /dev/stdout /dev/pts/18 

Obvioulsly, $() runs in a subshell, which is piped to the parent shell.

So the question is: is there a reliable (scoped to portability between Linux distributions) way to save /dev/stdout location as a string in a bash script?


As you can see, bash scripting is not like a regular programming language where you can assign file descriptors.

The simplest solution is to use a sub-shell to run what you want redirected so that processing can be reverted to the top-shell which has its standard I/O intact.

An alternate solution would be to use tty to identify the TTY device and control the I/O in your script.

$$ would get you the current process PID, in case of interactive shell or script the relevant shell PID.

So you can use:

readlink -f /proc/$$/fd/1


% readlink -f /proc/$$/fd/1

% var=$(readlink -f /proc/$$/fd/1)

% echo $var

Category: bash Time: 2016-07-29 Views: 5

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 0.220 (s). 12 q(s)