Какой верный синтаксис цикла for в BASH?

Почему при выполнении этого скрипта
#!/usr/bin/env bash
# To run this script you need to install https://rclone.org/ first
# Use current date and time for future backup folder name
TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S")
# Declare the directory where the temporary backup files will be stored
BACKUP_DIR="/user/backup/$TIMESTAMP"
# State the username for your MySQL / MariaDB instace that can access the neccessary databases
MYSQL_USER="user"
# Point this script to mysql executable file
MYSQL=/usr/bin/mysql
# State the password to the username above
# Be aware that using plain password is unsecure
MYSQL_PASSWORD="password"
# Point this script to mysqldump executable file
MYSQLDUMP=/usr/bin/mysqldump
# Declare the name of the remote that will be used as a remote storage
REMOTE="cloud"
# Create the temporary backup directory in case it doesn't exist
mkdir -p "$BACKUP_DIR"
# Get the list of all databases in your local MySQL / MariaDB instance
databases=`$MYSQL --user=$MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema)"`
# Start a cycle
for db in $databases; do
	# Echo the starting notice
	echo -e "===\nStarted working with the $db."
	# Use mysqldump to create and actual backup of your database
	$MYSQLDUMP --user=$MYSQL_USER -p$MYSQL_PASSWORD --databases $db | gzip > "$BACKUP_DIR/$db.sql.gz"
	# Use rclone to upload files to the remote backup server
	rclone copy "$BACKUP_DIR/$db.sql.gz" $REMOTE:$BACKUP_DIR
	# Echo the result
	echo -e "===\nFinished backup process for $db. Check your remote folder or watch for errors."
done


Выдаёт ошибку
backup_db.sh: 23: /user/backup_db.sh: Syntax error: word unexpected (expecting "do")
  • Вопрос задан
  • 89 просмотров
Пригласить эксперта
Ответы на вопрос 2
@AVKor
#!/usr/bin/env bash

# To run this script you need to install https://rclone.org/ first
# Use current date and time for future backup folder name
TIMESTAMP=$(date +"%F_%T")
# Declare the directory where the temporary backup files will be stored
BACKUP_DIR="/user/backup/$TIMESTAMP"
# State the username for your MySQL / MariaDB instace that can access the neccessary databases
MYSQL_USER="user"
# Point this script to mysql executable file
MYSQL=/usr/bin/mysql
# State the password to the username above
# Be aware that using plain password is unsecure
MYSQL_PASSWORD="password"
# Point this script to mysqldump executable file
MYSQLDUMP=/usr/bin/mysqldump
# Declare the name of the remote that will be used as a remote storage
REMOTE="cloud"
# Create the temporary backup directory in case it doesn't exist
mkdir -p "$BACKUP_DIR"
# Get the list of all databases in your local MySQL / MariaDB instance
databases=$($MYSQL --user=$MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema)")
# Start a cycle
for db in $databases; do
  # Echo the starting notice
  echo -e "===\nStarted working with the $db."
  # Use mysqldump to create and actual backup of your database
  $MYSQLDUMP --user=$MYSQL_USER -p$MYSQL_PASSWORD --databases "$db" | gzip > "$BACKUP_DIR/$db.sql.gz"
  # Use rclone to upload files to the remote backup server
  rclone copy "$BACKUP_DIR/$db.sql.gz" $REMOTE:$BACKUP_DIR
  # Echo the result
  echo -e "===\nFinished backup process for $db. Check your remote folder or watch for errors."
done

Используйте линтеры при написании кода.
Используйте настройки в ~/.my.cnf вместо впендюривания в скрипт имени пользователя, пароля и т.д.
Ответ написан
#!/bin/sh
#скрипт бэкапа баз данных
###########################
#Создаем папку для архивов.  -p не ругается когда папка уже есь test проверяет есть ли папка  для чистых логов
test ! -d /var/backup/mysql/`date +%Y` && { mkdir -p /var/backup/mysql/`date +%Y` ; }
test ! -d /var/backup/mysql/last && { mkdir -p /var/backup/mysql/last ; }

#прячем от умных, и так не зайдут но всеже.
chmod 600 /var/backup/mysql
chmod 600 /var/backup/mysql/last

# делаем сам дапм файлов sql, свежинькие файлы лежат всегда в ней, очень удобно не нужно заходить в архивы и искать там вчерашние базы, и логируется.
for i in `mysql -u***** -p******** -e'show databases;' | grep -v information_schema | grep -v Database`; do mysqldump -u********* -p********* $i > /var/backup/mysql/last/$i.sql;done >> /dev/null 2>> /var/log/sqlbackup.log
# Архивируем дамп, ну и логируем разумеется
cd /var/backup/mysql/
tar -czvf /var/backup/mysql/`date +%Y`/sqldump-`date +%Y-%m-%u`.tar.gz ./last >> /dev/null >> /var/log/sqlbackup.log
#(echo "Subject: Бэкап mysql  server завершен"; cat /var/log/sqlbackup.log;) | /usr/sbin/sendmail  viktor@demo.ru
##################  Конец скрипта

Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы