coproc Command in Linux with Examples
Last Updated :
10 Oct, 2024
coproc command in Linux is a shell command which allows us to create a co-process that is connected to the invoking shell via two pipes. One of the pipes enables us to send the input while the other enables us to read the output without having to resort to named pipes. The co-process is executed asynchronously in a subshell. This command can be used above bash versions 4.0.
Syntax
coproc command args #first command
coproc name command args #second command
where,
- command: The command or script you want to execute in the background.
- name: An optional name for the array that stores file descriptors. If not provided, COPROC is used by default.
Explanation of coproc Array and File Descriptors
The first command is used in the case of simple commands. Name must not be given to the command because, in the case of a simple command, it is interpreted as the first word of the simple command. In the case of compound commands, the second command is used.
If the name is not provided then COPROC is the 'name' by default. When the coprocess is executed, an array is created named 'name'(by default COPROC if the name is not supplied in the command) in the context of the executing shell. The first element of this array is the output descriptor while the second element of the array is the input descriptor to the co-process.
A bidirectional pipe is established between the executing shell and the co-process. Bash puts the file descriptors for those pipes into the array :
- name[0] is the file descriptor for the pipe that is connected to the standard output of the co-process in the executing shell.
- name[1] is the file descriptor for the pipe that is connected to the standard input of the co-process in the executing shell.
These pipes are established before any redirections are done by the command. These file descriptors can be utilized as arguments to shell commands and redirections using standard word expansions. The variable name_PID stores the process ID number.
The wait builtin command may be used to wait for the co-process to complete its execution. The coproc command always returns success as it is created as an asynchronous command. The return status of a co-process is the same as the exit status of command.
Working with coproc command
1. Creating a Simple Co-Process Without a Name
As is can be seen in the below-mentioned example code, no name is given in the coproc command so by default COPROC is the name of the array. COPROC[@] prints the elements of the array which stores the file descriptor that is connected to the output and input respectively. COPROC_PID stores the process ID number. COPROC[0] enables us to read the output of the coprocess
coproc (echo $(whoami))
echo "The coprocess array is ${COPROC[@]}"
echo "The PID of the coprocess is ${COPROC_PID}"
read -r o <&"${COPROC[0]}"
echo "The user is $o which is the output of the coprocess"

2. Sending Input to a Co-Process
The below-mentioned code prints geeksforgeeks as the output. The input to the bash is given using gfg[1] which is the file descriptor for the pipe connected to the input.
coproc gfg { bash ; }
echo 'echo geeksforgeeks' >&"${gfg[1]}"
read output <&"${gfg[0]}"
echo $output

3. Accessing File Descriptors Only in the Original Shell
The file descriptors of the co-process are accessible only to the process from which the co-process was generated. They are not inherited by subshells (For ex: any command which is launched within parenthesis is launched in a new subshell). As it can be seen from the below-mentioned code, Error is shown in the second case as the command within the parenthesis is launched within a new shell and file descriptors of co-process are accessible only to the process from which it was generated.
coproc gfg ( read -r input; echo "${input}" )
echo "PID:${gfg_PID}"
#first case
echo "geeksforgeeks" >&"${gfg[1]}"
read -r output1 <&"${gfg[0]}"
echo "The output of coprocess is ${output1}"
#second case
(echo "geeksforgeeks" >&"${gfg[1]}") #This will cause an error
read -r output2 <&"${gfg[0]}"
echo "The output of coprocess is ${output2}"

4. Replacing Characters in Input Using tr
tr command in the below-mentioned code will replace all instances of the letter “a” in the input with letter b. The file descriptor is closed by the exec statement. Note that closing this way is allowed in bash versions above 4.3. For versions, prior to 4.3, you need to first store the file descriptor in a variable and then use the exec command.
coproc gfg { tr a b; }
echo abbaaabbb >&"${gfg[1]}"
exec {gfg[1]}>&-
cat <&"${gfg[0]}"

Advantage of coproc command over & operator
Running a co-process in the background can also be achieved by using & operator which can be simply appended to the command. Commands like fg, kill, and [jobspec]% can be used to bring the process to the foreground or sending signals to it. But this does not allow us to send input to the background command or read the output of that command.
This can be achieved using coproc command which can be interpreted as having the same function as an & operator with a two-way pipe established between the executing shell and the co-process.
Conclusion
The coproc command in Linux provides an advanced way to create and manage co-processes, enabling bidirectional communication between the shell and the background process. It is particularly useful for interactive scripting, managing long-running tasks, and debugging Bash scripts. By understanding the coproc command's features, syntax, and practical examples, you can take full advantage of this powerful tool for shell scripting in Linux.
Similar Reads
cpio command in Linux with Examples
The cpio command, which stands for "copy in, copy out," is a powerful utility in Linux used for processing archive files. It provides functionality to copy files to and from archives, making it an essential tool for system administrators and power users. This article will explore the cpio command in
4 min read
cron command in Linux with Examples
The cron is a software utility, offered by a Linux-like operating system that automates the scheduled task at a predetermined time. It is a daemon process, which runs as a background process and performs the specified operations at the predefined time when a certain event or condition is triggered w
4 min read
cpp command in Linux with Examples
cpp is the C language preprocessor, it is automatically used by your C compiler to transform your program before compilation. It is also termed as a macro processor because it is used to give abbreviations for the longer piece of code. It can only be used with C, C++ and Objective-C source code. Usi
3 min read
echo command in Linux with Examples
The echo command in Linux is a built-in command that allows users to display lines of text or strings that are passed as arguments. It is commonly used in shell scripts and batch files to output status text to the screen or a file. Syntax of `echo` command in Linuxecho [option] [string]Here, [option
3 min read
compgen command in Linux with Examples
The compgen command is a Bash built-in utility used to list all available commands that can be executed in a Linux system. It is a powerful tool for searching for commands based on specific keywords, counting the total number of commands, and printing Bash details such as built-in functions, keyword
3 min read
dc command in Linux with examples
The dc command is a versatile calculator found in Linux systems, operating using reverse Polish notation (RPN). This command allows users to perform arithmetic calculations and manipulate a stack, making it ideal for complex mathematical tasks directly from the command line.SyntaxThe basic syntax fo
3 min read
cvs command in Linux with Examples
In today's digital era, where file modifications and version control are essential, the Concurrent Versions System (CVS) command in Linux emerges as a powerful tool. CVS allows users to store and track the history of files, enabling easy retrieval of previous versions and restoring corrupted files.
6 min read
doexec command in Linux with examples
doexec command in the Linux system is used to run an executable with an arbitrary argv[0]. It allows the user to argv[0] other than the name of the executable, which is by default passed. Syntax: doexec /path/to/executable argv[0] [argv[1-n]] Options: The argv list is used to send all options to the
1 min read
dirs command in Linux with examples
dirs command shell builtin is used to display the list of currently remembered directories. By default, it includes the directory you are currently in. A directory can get into the list via pushd command followed by the dir name and can be removed via popd command. Syntax: dirs [-clpv] [+N] [-N] It
1 min read
df command in Linux with Examples
Ever felt the chilling fear of a "disk full" error message on your Linux machine? Fear not, for the mighty df command stands ready to guide you through the treacherous terrain of disk space management! This article delves deep into the df command, equipping you with the knowledge and skills to navig
5 min read