将 bash 输出重定向到动态文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10568473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirect bash output to dynamic file name
提问by mythander889
I'm writing a bash script that will (hopefully) redirect to a file whose name is generated dynamically, based on the the first argument given to the script, prepended to the some string. The name of the script is ./buildcsvs.
我正在编写一个 bash 脚本,它将(希望)重定向到一个名称是动态生成的文件,基于给脚本的第一个参数,附加到一些字符串。脚本的名称是 ./buildcsvs。
Here's what the code looks like now, without the dynamic file names
这是代码现在的样子,没有动态文件名
#!/bin/bash
mdb-export 2011ROXBURY.mdb TEAM > team.csv
Here's how I'd like it to come out
这是我希望它出来的方式
./buildcsvs roxbury
should output
应该输出
roxburyteam.csv
with "$1" as the first arg to the script, where the file name is defined by something like something like
将“$1”作为脚本的第一个参数,其中文件名由类似的东西定义
"%steam" %
Do you have any ideas? Thank you
你有什么想法?谢谢
回答by jordanm
Just concatenate $1 with the "team.csv".
只需将 $1 与“team.csv”连接起来。
#!/bin/bash
mdb-export 2011ROXBURY.mdb TEAM > "team.csv"
In the case that they do not pass an argument to the script, it will write to "team.csv"
如果他们没有将参数传递给脚本,它将写入“team.csv”
回答by sarnold
You can refer to a positional argument to a shell script via $1
or something similar. I wrote the following little test script to demonstrate how it is done:
您可以通过$1
或类似的方式引用 shell 脚本的位置参数。我编写了以下小测试脚本来演示它是如何完成的:
$ cat buildcsv
#!/bin/bash
echo foo > .csv
$ ./buildcsv roxbury
$ ./buildcsv sarnold
$ ls -l roxbury.csv sarnold.csv
-rw-rw-r-- 1 sarnold sarnold 4 May 12 17:32 roxbury.csv
-rw-rw-r-- 1 sarnold sarnold 4 May 12 17:32 sarnold.csv
Try replacing team.csv
with $1.csv
.
尝试替换team.csv
为$1.csv
.
Note that running the script without an argument will then make an emptyfile named .csv
. If you want to handle that, you'll have to count the number of arguments using $#
. I hacked that together too:
需要注意的是运行脚本不带参数会然后作出一个空命名的文件.csv
。如果你想处理这个问题,你必须使用$#
. 我也一起破解了:
$ cat buildcsv
#!/bin/bash
(( $# != 1 )) && echo Need an argument && exit 1
echo foo > .csv