Here to Learn
Here to Learn

Reputation: 79

Checking if dir exist if not make it

This is what I have now

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

Getting errors Line 19: unexpected EOF while looking for matching `"' line 22: syntax error: unexpected end of file

Upvotes: 0

Views: 184

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263617

On this line:

mkdir -p "$file_month”

that last character is not a double quote ". It's a "RIGHT DOUBLE QUOTATION MARK", U+201D.

" vs.

If you get an error message about mismatched quotation marks, the best way to track it down is to search for the " in your editor, making sure you have an even number on each line.

Upvotes: 0

konsolebox
konsolebox

Reputation: 75588

Here's a concept script for your requirement. I hope it helps.

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

Upvotes: 1

Related Questions