簡體   English   中英

解析文件名的一部分以用作bash中的變量

[英]Parsing part of a file name to use as a variable in bash

我需要獲取數據庫名稱並將其用作文件名部分的變量。 目前我從ls命令中提取文件的名稱。 這是它返回的內容:
測試20150311-1200.sql

我需要文件名的第一部分到“ - ”,所以對於這個例子,它將是Test。 我怎樣才能獲得變量的部分文件名? 下面是我正在處理的完整腳本。 任何幫助都會很棒。 謝謝。

#!/bin/bash
DB_USER=x
DB_PASS=x
DB=
        for DB_GZFILE in $( ls *.sql.gz ); do
        gunzip $DB_GZFILE
            echo item: $DB_FILE unzipped
    done
        for DB_FILE in $( ls *.sql ); do    
#Use this statement to insert dump into a new server
        mysql $DB <$DB_FILE
    done    
#Use this command to insert into a server already in use
#       mysql -u$DB_USER -p$DB_PASS <$DB_FILE
            echo $DB_FILE inserted into database
    done
#Remove sql files used to insert into this server

#            rm $DB_FILE
#           echo $DB_FILE removed
    done

            echo restarting the mysql process .....
#       /etc/init.d/mysql restart
             echo mysql restarted
       done

不要解析ls

    for DB_GZFILE in *.sql.gz; do
    for DB_FILE in *.sql; do    

要獲得第一部分,請使用參數替換來刪除第一個-以及所有后續字符:

first_part=${DB_FILE%%-*}

你應該引用所有的"$vars" ,特別是你從用戶或文件系統獲得的任何價值:你永遠不知道什么時候你會得到一個帶有空格的文件名。 例:

gunzip "$DB_GZFILE"

我建議你不要使用ALL_CAPS_VARNAMES:有一天你會不小心使用PATH=...然后想知道為什么你的腳本壞了。 保留ALL_CAPS以獲取系統環境變量和shell特殊變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM