如果没有,则检查dir是否存在

时间:2013-09-13 11:03:42

标签: bash

这就是我现在所拥有的

#!/bin/bash

# This would match files that begin with YYYYMMDD format.
files=([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*)

# If you want to match those in the current year, start it with that year instead.
# current_year=$(date +%Y)
# files=("$current_year"[0-9][0-9][0-9][0-9]*)

#expands its values to multiple arguments "${files[@]}"
for file in "${files[@]}"; do
 file_year=${file:0:4}

#  Adding -p option to mkdir would create the directory only if it doesn't exist.
  mkdir -p "$file_year"  

  file_month=${file:4:2}
  mkdir -p "$file_month”
  mv "$files" "$file_year"/"$file_month"

done

获取错误 第19行:寻找匹配的“”时意外的EOF 第22行:语法错误:意外的文件结尾

2 个答案:

答案 0 :(得分:1)

这是符合您要求的概念脚本。我希望它有所帮助。

#!/bin/bash

# This would match files that begin with YYYYMMDD format.
files=([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*)

# If you want to match those in the current year, start it with that year instead.
# current_year=$(date +%Y)
# files=("$current_year"[0-9][0-9][0-9][0-9]*)

for file in "${files[@]}"; do
    file_year=${file:0:4}

    # You could just simply do this. Adding -p option to mkdir would create the directory only if it doesn't exist.
    # mkdir -p "$file_year"  

    if [[ -d $file_year ]]; then
        echo "Directory exists."
    else
        echo "Creating directory ${file_year}."
        mkdir "$file_year" || {
            # If it fails, send a message to user and break the loop.
            echo "Failed to create directory ${file_year}."
            break
        }
    fi

    # After creating the directory perhaps you want to move the file to it so:
    # mv "$file" "$file_year"
done

答案 1 :(得分:0)

在这一行:

mkdir -p "$file_month”

最后一个字符不是双引号"。这是一个“正确的双引号”, U+201D

"

如果您收到有关不匹配引号的错误消息,则跟踪它的最佳方法是在编辑器中搜索",确保每行都有偶数。