15

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

2 Answers 2

22

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"

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

In bash, it's generally better to use (( )) for numerical comparisons. (( $# < 1 || $# > 1 )) && ....
(( $# != 1 )) && ... is simpler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.