Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH shell script to quickly create and populate new test files

# for i in {1..5} do echo "New File $i" > file$i done
-bash: syntax error near unexpected token `>'

I tried the above single line script which failed with the error above. I'm trying to automate the process of typing:

echo "New File" > file1  
echo "New File" > file2  
echo "New File" > file3  
echo "New File" > file4  
echo "New File" > file5  

I'm trying to do this without creating a script file such as below which works:

#!/usr/bin/env bash                                                                                                                                                                                       
for i in {1..5} 
  do  
    echo "New File $i" > file$i 
  done

This script works but I want to be able to do something like this on a single line from the command line.

I understand the problem has something to do with the redirection > to the file. I tried escaping the > redirection a few other things, and googling but I didn't come up with something which worked.

The reason I want to be able to do this in a single line on the cli is because I want to be able to keep changing the numbers and contents of files for testing and I'd prefer to just do it on the command line rather than editing a script file.

Update 1

I tried the command separators as suggested and got the error below:

# for i in {1..5} do ; echo "New File $i" > file$i ; done
-bash: syntax error near unexpected token `echo'

Update 2

I did the command separators incorrectly above in Update 1. Done with the command separators as they are in the answer below worked like a charm.

like image 702
caleban Avatar asked Feb 26 '23 18:02

caleban


2 Answers

You need either a semi-colon or a new line before the do and before the done. You do not need one after the do, although it doesn't hurt.

Single line

for i in {1..5}; do echo "New File $i" > file$i; done
               ^                               ^ 

Multiple lines

for i in {1..5}
do
    echo "New File $i" > file$i
done

for i in {1..5}; do
    echo "New File $i" > file$i
done
like image 147
John Kugelman Avatar answered Mar 05 '23 16:03

John Kugelman


The following works for me, all you needed to do to your update 1 was to insert a command separator between the for and the do:

for i in {1..5} ; do echo "New File $i" >file$i ; done
like image 42
paxdiablo Avatar answered Mar 05 '23 18:03

paxdiablo