Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting output of bash for loop

Tags:

linux

bash

shell

I have a simple BASH command that looks like

for i in `seq 2`; do echo $i; done; > out.dat 

When this runs the output of seq 2 is output to the terminal and nothing is output to the data file (out.dat)

I am expecting standard out to be redirected to out.dat like it does simply running the command seq 2 > out.dat

like image 593
Matthew Kirkley Avatar asked Sep 04 '13 11:09

Matthew Kirkley


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.

What is $() in bash script?

$() Command Substitution According to the official GNU Bash Reference manual: “Command substitution allows the output of a command to replace the command itself.

What is &1 in shell script?

&1 is used to reference the value of the file descriptor 1 (stdout). both Standard output (stdout) and Standard Error (stderr) will redirected to output.

Can you nest for loops in bash?

Nested loop definition That is to say, it is a loop that exists inside an outer loop. When you integrate nested loops in bash scripting, you are trying to make a command run inside another command. This is what it means: a bash nested for loop statement runs a command within another loop.


1 Answers

Remove your semicolon.

for i in `seq 2`; do echo "$i"; done > out.dat 

SUGGESTIONS

Also as suggested by Fredrik Pihl, try not to use external binaries when they are not needed, or at least when practically not:

for i in {1..2}; do echo "$i"; done > out.dat for ((i = 1; i <= 2; ++i )); do echo "$i"; done > out.dat for i in 1 2; do echo "$i"; done > out.dat 

Also, be careful of outputs in words that may cause pathname expansion.

for a in $(echo '*'); do echo "$a"; done 

Would show your files instead of just a literal *.

$() is also recommended as a clearer syntax for command substitution in Bash and POSIX shells than backticks (`), and it supports nesting.

The cleaner solutions as well for reading output to variables are

while read var; do     ...    done < <(do something) 

And

read ... < <(do something)  ## Could be done on a loop or with readarray.  for a in "${array[@]}"; do     : done 

Using printf can also be an easier alternative with respect to the intended function:

printf '%s\n' {1..2} > out.dat 
like image 182
konsolebox Avatar answered Oct 18 '22 11:10

konsolebox