Input Redirection in Linux/Unix Examples - Linux Linux

Input redirection is a powerful feature in Linux/Unix systems that allows users to manipulate the flow of data between commands, files, and processes. By leveraging input redirection operators, users can redirect input from various sources, providing flexibility and efficiency in command-line operations. In this article, we'll explore the basics of input redirection and provide practical examples to showcase its utility.

Understanding Input Redirection: In Linux/Unix, input redirection is accomplished using the < operator. This operator allows users to take input from a specified file or command and pass it as input to another command. This feature proves invaluable in automating tasks, handling large datasets, and streamlining command-line workflows.

Basic Syntax:

command1 < input_file

Examples:

  1. Reading Input from a File: Suppose you have a file named data.txt containing a list of names. You can use input redirection to pass the content of this file as input to a command like cat:

    cat < data.txt

    In this example, the cat command reads the contents of data.txt without explicitly specifying the file as an argument.

  2. Combining Commands: Input redirection is handy when combining the output of one command with the input of another. For instance, consider the following example where the output of the ls command is redirected as input to the grep command:

    ls -l | grep 'example' < input_file

    Here, the ls -l command lists files in long format, and the output is piped to grep, which then filters lines containing the term 'example'. Meanwhile, input redirection is used to provide additional input from input_file.

  3. Interactive Input: Input redirection is not limited to files; it can also be employed in scenarios requiring interactive input. For instance, consider a script that prompts the user for input. Instead of manually entering data, you can redirect input from a file:

    ./interactive_script.sh < input_data.txt

    Here, the script interactive_script.sh reads input from input_data.txt as if it were entered interactively.

  4. Here Document: A Here Document is a convenient way to redirect multiple lines of input to a command. This is particularly useful when dealing with commands that expect input from the standard input stream. For example:

    cat << EOF Line 1 Line 2 Line 3 EOF

    In this case, the cat command will output the lines enclosed between << EOF and EOF.

Conclusion: Input redirection in Linux/Unix is a versatile tool that enhances the efficiency and flexibility of command-line operations. Whether dealing with files, combining commands, or facilitating interactive input, understanding and mastering input redirection can significantly improve your ability to work with these systems. By incorporating these examples into your daily workflow, you can harness the power of input redirection to streamline your tasks and operations.