You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

load.mysql.sh 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/bin/bash
  2. # Prompt for MySQL root password securely
  3. read -sp "Enter MySQL root password: " MYSQL_PASSWORD
  4. echo # Newline after password input
  5. DEFAULT_INSTANCENAME="cihsr"
  6. echo "Enter instance name (default: $DEFAULT_INSTANCENAME):"
  7. read instancename
  8. INSTANCENAME=${instancename:-$DEFAULT_INSTANCENAME}
  9. # Prompt for the database name with a default value
  10. read -p "Enter the database name (default: cihsr): " DB_NAME
  11. DB_NAME=${DB_NAME:-$INSTANCENAME}
  12. # Default the SQL file to 'create.mysql.db.sql' in the current directory
  13. SQL_FILE="elxr/create.mysql.db.sql"
  14. # Confirm if the SQL file exists
  15. if [[ ! -f "$SQL_FILE" ]]; then
  16. echo "SQL file '$SQL_FILE' does not exist in the current directory. Please check the file path and try again."
  17. exit 1
  18. fi
  19. # MySQL user credentials
  20. MYSQL_USER="root"
  21. # Check if the database exists
  22. DB_EXISTS=$(mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES LIKE '$DB_NAME';")
  23. if [[ -z "$DB_EXISTS" ]]; then
  24. # Database does not exist, create it
  25. echo "Database '$DB_NAME' does not exist. Creating database..."
  26. mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "CREATE DATABASE IF NOT EXISTS $DB_NAME;"
  27. fi
  28. # Replace the placeholder {{DB_NAME}} in the SQL file with the database name
  29. TEMP_SQL_FILE=$(mktemp)
  30. sed "s/{{DB_NAME}}/$DB_NAME/g" "$SQL_FILE" > "$TEMP_SQL_FILE"
  31. # Run the SQL script with the provided database name
  32. mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $DB_NAME < "$TEMP_SQL_FILE"
  33. # Clean up the temporary file
  34. rm "$TEMP_SQL_FILE"
  35. mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $DB_NAME < $SQL_FILE -- Create Schema
  36. mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $DB_NAME < $DB_NAME.sql -- Load data
  37. echo "SQL script executed successfully on database $DB_NAME"