BASH用户驱动器选择

时间:2013-03-07 14:51:41

标签: macos bash shell

我正在为mac os x创建一个简单的脚本,根据/ Volumes的内容为用户提供可供备份的可用驱动器列表,但是我遇到了处理'find'输出的问题命令,如果驱动器名称包含空格。 find命令在一个单独的行上输出每个驱动器,但'for each'将名称分成几部分。例如:

脚本:

#!/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,这非常有效。这是一个生成ditto命令的简单脚本,但我会在这里发布它,以防有人发现它的任何部分有用:

#!/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

1 个答案:

答案 0 :(得分:2)

由于您遇到的空间问题,您无法使用find循环安全地迭代for的输出。使用内置while的{​​{1}}循环代替:

read