2013-03-07 69 views
2

我正在爲mac os x創建一個簡單腳本,以向用戶提供基於/ Volumes內容備份的可用驅動器列表,但我遇到了處理輸出的問題如果驅動器名稱包含空格,則使用'find'命令。 find命令在一個單獨的行上輸出每個驅動器,但'for each'將該名稱分解爲多個部分。例如:BASH用戶驅動器選擇

腳本:

#!/bin/bash 
find /Volumes -maxdepth 1 -type d 
echo "" 

i=1 
for Output in $(find /Volumes -maxdepth 1 -type d) 
do 
DriveChoice[$i]=$Output 
echo $i"="${DriveChoice[$i]} 
i=$((i+1)) 
done 

輸出:

/Volumes 
/Volumes/backup 
/Volumes/EZBACKUP DRIVE 
/Volumes/Tech 

1=/Volumes 
2=/Volumes/backup 
3=/Volumes/EZBACKUP 
4=DRIVE 
5=/Volumes/Tech 
logout 

[Process completed] 

這似乎應該是相當直接的。有沒有更好的方法來實現這個目標?

更新:謝謝你chepner,完美的作品。這是一個簡單的腳本生成一個同上命令,但我將它張貼在這裏反正萬一有人發現有用的任何部分:

#!/bin/bash 
#Get admin rights 
sudo -l -U administrator bash 
#Set the path to the backup drive 
BackupPath="/Volumes/backup/" 
#Generate a list of source drives, limiting out invalid options 
i=1 
while read -r Output; do 
if [ "$Output" != "/Volumes" ] && [ "$Output" != "/Volumes/backup" ] && [ "$Output" != "/Volumes/Tech" ] ; then 
    DriveChoice[$i]=$Output 
    echo "$i=${DriveChoice[$i]}" 
    i=$((i+1)) 
fi 
done < <(find /Volumes -maxdepth 1 -type d) 

#Have the user select from valid drives 
echo "Source Drive Number?" 
read DriveNumber 
#Ensure the user input is in range 
if [ $DriveNumber -lt $i ] && [ $DriveNumber -gt 0 ]; then 
    Source=${DriveChoice[$DriveNumber]}"/" 
    #Get the user's NetID for generating the folder structure 
    echo "User's NetID?" 
    read NetID 
    NetID=$NetID 
    #Grab today's date for generating folder structure 
    Today=$(date +"%m_%d_%Y") 
    #Destination for the Logfile 
    Destination=$BackupPath$NetID"_"$Today"/" 
    #Full path for the LogFile 
    LogFile=$Destination$NetID"_log.txt" 
    mkdir -p $Destination 
    touch $LogFile 
    #Destination for the backup 
    Destination=$Destination"ditto/" 
    #Execute the command 
    echo "Processing..." 
    sudo ditto "$Source" "$Destination" 2>&1 | tee "$LogFile" 
else 
    #Fail if the drive selection was out of range 
    echo "Drive selection error!" 
fi 

回答

2

你不能安全地迭代的find使用for環路輸出,因爲你看到的空間問題。使用一個while循環與read內置代替:

#!/bin/bash 
find /Volumes -maxdepth 1 -type d 
echo "" 

i=1 
while read -r output; do 
    DriveChoice[$i]=$output 
    echo "$i=${DriveChoice[$i]}" 
    i=$((i+1)) 
done < <(find /Volumes -maxdepth 1 -type d) 
+0

你打我吧:-) – William 2013-03-07 14:57:28

相關問題