开发者

BASH shell script to quickly create and populate new test files

开发者 https://www.devze.com 2023-01-26 21:16 出处:网络
# for i in {1..5} do echo \"New File $i\" > file$i done -bash: syntax error near unexpected token `>\'
# 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 tr开发者_运维问答ied 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.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号