Problem with Bash Output Redirection

Output redirection in shell script not working completely

as sjsam has answered remove the backticks . I think the syntax is like this

./test >/dev/null 2>&1 << end
source(scripts/all.src);
quit;
end

Problem with Bash output redirection

Redirecting from a file through a pipeline back to the same file is unsafe; if file.txt is overwritten by the shell when setting up the last stage of the pipeline before tail starts reading off the first stage, you end up with empty output.

Do the following instead:

tail -1 file.txt >file.txt.new && mv file.txt.new file.txt

...well, actually, don't do that in production code; particularly if you're in a security-sensitive environment and running as root, the following is more appropriate:

tempfile="$(mktemp file.txt.XXXXXX)"
chown --reference=file.txt -- "$tempfile"
chmod --reference=file.txt -- "$tempfile"
tail -1 file.txt >"$tempfile" && mv -- "$tempfile" file.txt

Another approach (avoiding temporary files, unless <<< implicitly creates them on your platform) is the following:

lastline="$(tail -1 file.txt)"; cat >file.txt <<<"$lastline"

(The above implementation is bash-specific, but works in cases where echo does not -- such as when the last line contains "--version", for instance).

Finally, one can use sponge from moreutils:

tail -1 file.txt | sponge file.txt

Problem redirecting a C program output in bash

Flushing after newlines only works when printing to a terminal, but not necessarily when printing to a file. A quick Google search revealed this page with further information: http://www.pixelbeat.org/programming/stdio_buffering/

See the section titled "Default Buffering modes".

You might have to add some calls to fflush(stdout), after all.

You could also set the buffer size and behavior using setvbuf.

bash redirect output to file but result is incomplete

That is a funny problem, I've never seen that happening before. I am going to go out on a limb here and suggest this, see how it works:

 sudo ./bin/sc --doctor 2>&1 | tee -a alloutput.txt

How to redirect and append both standard output and standard error to a file with Bash


cmd >>file.txt 2>&1

Bash executes the redirects from left to right as follows:

  1. >>file.txt: Open file.txt in append mode and redirect stdout there.
  2. 2>&1: Redirect stderr to "where stdout is currently going". In this case, that is a file opened in append mode. In other words, the &1 reuses the file descriptor which stdout currently uses.


Related Topics



Leave a reply



Submit