Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect bash output to dynamic file name

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.

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

"%steam" % $1

Do you have any ideas? Thank you

like image 827
mythander889 Avatar asked May 13 '12 00:05

mythander889


2 Answers

Just concatenate $1 with the "team.csv".

#!/bin/bash
mdb-export 2011ROXBURY.mdb TEAM > "${1}team.csv"

In the case that they do not pass an argument to the script, it will write to "team.csv"

like image 130
jordanm Avatar answered Oct 23 '22 04:10

jordanm


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:

$ cat buildcsv 
#!/bin/bash
echo foo > $1.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.

Note that running the script without an argument will then make an empty file named .csv. If you want to handle that, you'll have to count the number of arguments using $#. I hacked that together too:

$ cat buildcsv 
#!/bin/bash
(( $# != 1 )) && echo Need an argument && exit 1
echo foo > $1.csv
like image 39
sarnold Avatar answered Oct 23 '22 04:10

sarnold