Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect stdin to file in bash

Tags:

bash

Consider this very simple bash script:

#!/bin/bash
cat > /tmp/file

It redirects whatever you pipe into it to a file. e.g.

echo "hello" | script.sh

and "hello" will be in the file /tmp/file. This works... but it seems like there should be a native bash way of doing this without using "cat". But I can't figure it out.

NOTE:

  1. It must be in a script. I want the script to operate on the file contents afterwards.

  2. It must be in a file, the steps afterward in my case involve a tool that only reads from a file.

  3. I already have a pretty good way of doing this - its just that it seems like a hack. Is there a native way? Like "/tmp/file < 0 " or "0> /tmp/file". I thought bash would have a native syntax to do this...

like image 387
Rafael Baptista Avatar asked Mar 30 '16 15:03

Rafael Baptista


People also ask

How do I redirect a output to a file in Bash?

For utilizing the redirection of bash, execute any script, then define the > or >> operator followed by the file path to which the output should be redirected. “>>” operator is used for utilizing the command's output to a file, including the output to the file's current contents.

How do I redirect in Bash?

The append >> operator adds the output to the existing content instead of overwriting it. This allows you to redirect the output from multiple commands to a single file. For example, I could redirect the output of date by using the > operator and then redirect hostname and uname -r to the specifications.

What is Stdin redirection?

Input/Output (I/O) redirection in Linux refers to the ability of the Linux operating system that allows us to change the standard input ( stdin ) and standard output ( stdout ) when executing a command on the terminal. By default, the standard input device is your keyboard and the standard output device is your screen.

How do you redirect stdin stdout and stderr to a file?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.


1 Answers

You could simply do

cp /dev/stdin  myfile.txt

Terminate your input with Ctrl+D or Ctrl+Z and, viola! You have your file created with text from the stdin.

like image 155
dee Avatar answered Oct 06 '22 04:10

dee