Practical Example
File redirection is very common both when reading files into scripts and when outputting data from a script into a file. This example script does both of those things. It reads a .csv-formatted data file and outputs SQL INSERT
statements to insert the data into a database (see Chapter 25).
The shell script uses a command line parameter to define the name of the .csv
file from which to read the data. The .csv
format is used to export data from spreadsheets, so you can place the database data into a spreadsheet, save the spreadsheet in .csv
format, read the file, and create INSERT
statements to insert the data into a MySQL database.
Here's what the script looks like:
$cat test23
#!/bin/bash
# read file and create INSERT statements for MySQL
outfile='members.sql'
IFS=','
while read lname fname address city state zip
do
cat >> $outfile << EOF
INSERT INTO members (lname,fname,address,city,state,zip) VALUES
('$lname', &apos...