BASH shell 脚本可快速创建和填充新的测试文件
# for i in {1..5} do echo "New File $i" > file$i done
-bash: syntax error near unexpected token `>'
我尝试了上面的单行脚本,但由于上述错误而失败。我正在尝试自动化输入过程:
echo "New File" > file1
echo "New File" > file2
echo "New File" > file3
echo "New File" > file4
echo "New File" > file5
我正在尝试在不创建脚本文件的情况下执行此操作,如下所示,该脚本文件有效:
#!/usr/bin/env bash
for i in {1..5}
do
echo "New File $i" > file$i
done
该脚本有效,但我希望能够在命令的一行中执行类似的操作线。
我知道该问题与重定向 >
到文件有关。我尝试逃避 >
重定向的一些其他事情,并谷歌搜索,但我没有想出一些有效的方法。
我希望能够在 cli 上的一行中执行此操作的原因是因为我希望能够不断更改文件的数量和内容以进行测试,并且我更愿意在命令行上执行此操作而不是编辑脚本文件。
更新 1
我按照建议尝试了命令分隔符,并收到以下错误:
# for i in {1..5} do ; echo "New File $i" > file$i ; done
-bash: syntax error near unexpected token `echo'
更新 2
我在上面的更新 1 中错误地使用了命令分隔符。 完成命令分隔符后,就像下面的答案一样,效果非常好。
# 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
do
和done
之前需要一个分号或换行符。在do
之后您不需要这样做,尽管这并没有什么坏处。单线
多线
You need either a semi-colon or a new line before the
do
and before thedone
. You do not need one after thedo
, although it doesn't hurt.Single line
Multiple lines
以下内容对我有用,您对更新 1 所需要做的就是在
for
和do
之间插入命令分隔符:The following works for me, all you needed to do to your update 1 was to insert a command separator between the
for
and thedo
: