2015-12-14 24 views
2

例如:如何處理條件如果字符串不是各種字符串?

#!/bin/bash 

DATABASES=`ssh [email protected] "mysql -u root -e 'show databases;'"`; 
for database in $(echo $DATABASES | tr ";" "\n") 
do 
    if [ "$database" -ne "information_schema" ] 
    then 
     # ssh [email protected] "mysqldump -u root ..." 
     # rsync ... 
    fi 
done 

需要排除:

  • 數據庫
  • INFORMATION_SCHEMA
  • SYS

如何讓3個條件中的一個 「如果」?在其他語言中使用「或」或「||」但在bash中是?

回答

2

在bash,那麼你可以使用@(str1|str2|str3)[[...]]來比較多個字符串值:

if [[ $database != @(information_schema|Database|sys) ]]; then 
    echo "execute ssh command" 
fi 
+1

謝謝:)最終腳本:http://pastebin.com/5Ka6qNNi –

+0

確保你在腳本中有'shopt -s extglob' –

+0

實際上'extglob'不需要在[[[...] ]]' – anubhava

1

裏面[[ ... ]]您可以使用||爲OR和&&爲AND條件,例如:

if [[ $database != information_schema && $database != sys && $database != Database ]] 
then 
    # ssh [email protected] "mysqldump -u root ..." 
    # rsync ... 
fi 

另一種替代方法是使用case

case "$database" in 
    information_schema|sys|Database) ;; 
    *) 
     # ssh [email protected] "mysqldump -u root ..." 
     # rsync ... 
     ;; 
esac