-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmysql_backup2csv.sh
More file actions
executable file
·47 lines (36 loc) · 1.13 KB
/
Copy pathmysql_backup2csv.sh
File metadata and controls
executable file
·47 lines (36 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<EOF
Usage: $(basename "$0") <db_name> [user] [output_dir]
Arguments:
db_name MySQL database to export (required)
user MySQL user to connect as (default: root)
output_dir Directory for CSV output files (default: /var/lib/mysql-files)
EOF
exit 1
}
[[ -z "${1:-}" ]] && usage
DB_NAME="${1}"
DB_USER="${2:-root}"
OUTPUT_DIR="${3:-/var/lib/mysql-files}"
mkdir -p "$OUTPUT_DIR"
echo "Starting native CSV export for database: $DB_NAME..."
TABLES=$(mysql -u "$DB_USER" -B -N -e "SHOW TABLES FROM $DB_NAME;")
while read -r TABLE; do
[[ -z "$TABLE" ]] && continue
echo " -> Exporting: $TABLE"
CSV_FILE="$OUTPUT_DIR/$TABLE.csv"
# MySQL's INTO OUTFILE will fail securely if the file already exists.
# We must delete the old one first.
rm -f "$CSV_FILE"
mysql -u "$DB_USER" -e "
SELECT * INTO OUTFILE '$CSV_FILE'
FIELDS TERMINATED BY ','
ENCLOSED BY '\"'
ESCAPED BY '\"'
LINES TERMINATED BY '\n'
FROM $DB_NAME.$TABLE;
"
done <<<"$TABLES"
echo "Export complete. Files are located in: $OUTPUT_DIR"