1

所以我现在正在参加一个夏季的 Unix 简介课程,我们需要编写一个脚本,根据文件扩展名将文件组织到目录中。现在我遇到了一个似乎找不到的语法错误。这是我的脚本:

#!/bin/bash

echo -e "Are you sure you want to reorganize your files? (Y to continue)"
read response

if [ $response == "Y" ]  ; then 

    echo "Organizing files!"
    touch organize.log
    echo "Organizing..." > organize.log

    mkdir music
    mkdir video
    mkdir text

    for filename in *
    do
        extension="${filename##*.}"

    if [ extension == "mp3" ] || [ extension == "oog" ] || [ extension == "wav" ] ; then

            echo "$filename --> music/$filename" > organize.log
            mv $file music 

    elif [ extension == "wmv" ] || [ extension == "mov" ] || [ extension == "mpg" ] ; then

        echo "$filename --> video/$filename" > organize.log
        mv $file video 

    elif [ extension == "txt" ] ; then

        echo "$filename --> text/$filename" > organize.log
        mv $file text

    done

    echo "Finished organizing files!"
    echo "Bye!"

else
    echo "Ok then. Bye."
    exit

fi

exit

我是 Unix 新手,所以我觉得这很难。如果有人可以给我任何提示,我将不胜感激。

这是新的错误:

organizefiles.sh: line 38: syntax error near unexpected token `done'
organizefiles.sh: line 38: `    done    '
4

2 回答 2

3

这是您的脚本的更简洁版本

#!/bin/bash

read -p "Are you sure you want to reorganize your files? (Y to continue) " response
if [[ $response != [Yy]* ]]  ; then 
    echo "Ok then. Bye."
    exit
fi

echo "Organizing files!"
# don't need "touch", the file will be created if it doesn't exist.
echo "Organizing..." > organize.log

# use "-p" to avoid errors if the dirs already exist
mkdir -p music video text

# Don't Repeat Yourself, use a function
function moveto {
    echo "$2 --> $1/$2" >> organize.log
    mv "$2" "$1"
}

for filename in *
do
    case "${filename##*.}" in 
        mp3|ogg|wav) moveto music "$filename" ;;
        wmv|mov|mpg) moveto video "$filename" ;;
        txt)         moveto text  "$filename" ;;
    esac
done

echo "Finished organizing files!"
echo "Bye!"
于 2012-08-01T00:22:03.280 回答
2

您的for循环格式错误。

for ...
do
   ...
done

编辑:

if需要fi

于 2012-07-31T21:40:08.713 回答