How to redirect stdin to a file in bash

Consider this very simple bash script:

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

It redirects everything that you bring to the file. eg.

echo "hello" | script.sh

and "hello" will be in / tmp / file. This works ... but there seems to be a native way for bash to do this without using "cat". But I can’t understand.

NOTE:

  • It must be in the script. I want the script to work on the contents of the file afterwards.

  • It should be in the file, the steps in my case include a tool that only reads from the file.

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

+4
5

, , stdin EOF, :

#!/bin/bash
exec > /tmp/file
while IFS= read -r line; do
  printf '%s\n' "$line"
done
+2
echo "$(</dev/stdin)" > /tmp/file

ENTER ctrl + d

+4

BASH:

#!/bin/bash

IFS= read -t 0.01 -r -d '' indata

[[ -n $indata ]] && printf "%s" "$indata" >/tmp/file

IFS= -d '' stdin indata.

-t 0.01: script , read 0.01 . , indata >/tmp/file.

+3

cp/dev/stdin myfile.txt Ctrl + D Ctrl + Z , , stdin

+2

GENERATE INPUT | (
    # do whatever you like to the input here
)

But sometimes, especially when you want to perform input first and then work with the modified output, you still need to use temporary files:

TMPFILE="/tmp/fileA-$$"
GENERATE INPUT | (
    # modify input
) > "$TMPFILE"
(
     # do something with the input from TMPFILE
) < "$TMPFILE"
rm "$TMPFILE"
0
source

All Articles