You are currently viewing Shell Scripting – Redirections
Shell Scripting – Redirection

Shell Scripting – Redirections

Shell Scripting – Redirections

Hello Everyone

Welcome to CloudAffaire and this is Debjeet.

In the last blog post, we have discussed conditional statements in the shell.

https://cloudaffaire.com/shell-scripting-conditions/

In this blog post, we will discuss redirections in shell. Redirection simply means capturing output from a file, command, program, script, or even code block within a script and sending it as input to another file, command, program, or script. Each open file gets assigned a file descriptor. A file descriptor (FD) is a number which refers to an open file. Each open file gets assigned a file descriptor. When bash starts it opens the three standard file descriptors Standard Input (stdin with FD 0), Standard Output (stdout with FD 1), and Standard Error (stderr with FD 2).

Shell Scripting – Redirections:

Output Redirection:

Output of a file can be redirected using > which causes the file to be opened for writing on file descriptor n, or the standard output (FD 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size. If you want to append the output to existing file instead of overwriting you can use >>.

Standard Output & Standard Error Redirection:

You can redirect Standard Output (stdout with FD 1) using 1> and Standard Error (stderr with FD 2) using 2>. If you want to redirect both Standard Output (stdout with FD 1) and Standard Error (stderr with FD 2) in the same place you can use 2>&1 or 1>&2.

Input Redirection:

Input to a file can be redirected using < which causes the file to be opened for reading on file descriptor n, or the standard input (FD 0) if n is not specified. Input redirection can also be achieved using heredoc (<<) and herestring (<<<).

IO Redirection Using Pipe:

You can use a pipe to pass the output of one command as the input to another command. The pipe can also be combined with the IO redirection.

Hope you have enjoyed this article, in the next blog post, we will discuss array in the shell.

 

Leave a Reply