teleluck
teleluck

Reputation: 25

Can't make directory because the directory exists?

I am trying to extract a list of mp3 files into 2 parts: 1 for artist and 1 for song name. So far, I have this:

#!/bin/bash
for f in *.mp3; do
        artist="${f%  -*}"
        song="${f#*-\ }"
        mkdir "$artist"
        mv "$f" "$song"
        mv "$song" "$artist";
done

I am testing on a file I created called "hi - 1.mp3" (hi/ -/ 1.mp3) but get the error mkdir: cannot create directory ‘hi - 1.mp3’: File exists which prevents changing the song name and moving it into the directory. I thought this was a directory issue so I tried to manually check if the directory exists:

#!/bin/bash
for f in *.mp3; do
        artist="${f%  -*}"
        song="${f#*-\ }"
        if [ -d "$artist" ]; then
                exit 0
                mkdir $"$artist"
fi
        mv "$f" "$song"
        mv "$song" "$artist";
done

But because the error is that a directory exists, it doesn't do anything and just results in exit 0 (although I don't have the mkdir error anymore.) I also have tried ls -a on all my directories but I can't find another a directory with the name hi - 1.mp3

Upvotes: 0

Views: 95

Answers (2)

ABHIShek
ABHIShek

Reputation: 34

have u tried this....it is perfectly working fine...fr my case.

#!/usr/local/bin/bash
 for f in *.mp3
 do
 artist=`echo ${f%-*}`
 song=`echo ${f#*-}`
 mkdir -p $artist
 mv "$f" "$song"
 mv $song ./$artist
 done

Upvotes: 1

grand central
grand central

Reputation: 49

Bash should continue even after giving the error unless you have used set -e, you could add a set +e in your script to reverse this behavior and continue to run after having a command fail. From help set:

-e Exit immediately if a command exits with a non-zero status.

Also, you could use mkdir -p, which will supress the error. From man mkdir:

   -p, --parents
          no error if existing, make parent directories as needed

Upvotes: 0

Related Questions