Nroh
Nroh

Reputation: 11

Bash Script don't make folders and tries to move it self

I´m writing a bash script that should sort photos by parts of they´re names to folders. The problem it gives me a lot of errors and I can't find the mistake. Even ShellCheck don't found something so If u guys can help me that would be great.

My Script:

#!/bin/bash

Total=$(ls -1 | wc -l)
echo "$Total"
Count=1

while [[ $Count < $Total ]]
do
    NameOut=$(ls -1 | grep -o '[^-]*,[^-]*' | sed -n "$Count"p)
    echo "$NameOut"
    Filename=$(ls -1 | sed -n "$Count"p)
    echo "$Filename"
    if [ -d "$NameOut" ]; then
        mv "$Filename" "$NameOut"/
        Count=$((Count + 1))
    else
        mkdir "$NameOut"
        mv "$Filename" "$NameOut"/
        Count=$((Count + 1))
    fi
done

The script tries for some reason to move the script itself and it don't make the folders - and can't move the files because there are no folders to move them in to. The directory it self contains files that are looking like this:

ls -1

REZ-Name,Surname-02-12-1996.jpg
BLEACH-Name,Surname-04-08-2008.jpg

Upvotes: 0

Views: 85

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80931

shellcheck does identify a couple of issues with this script.

This script is also hugely inefficient as it repeatedly loops over the contents of the file when it doesn't need to do that.

An array of filenames would be a much better way to do this task.

That being said none of that has anything to do with the error you listed.

The problem with your script is the print lines.

What are you expecting them to be doing?

The echo lines are printing out your variable values already. Did you mean printf '%s\n' "$var" there? (Which would just duplicate the echo lines output?)

print is a different command entirely and is trying to figure out how to print the argument you gave it (as in to a printer, etc.).


Untested but something like this will probably do what you want. The remaining use of grep can almost certainly be replaced also but without seeing representative input and output this was less likely to have deviated from the original intention.

#!/bin/bash

files=(*)
total=${#files[@]}
echo "$total"

count=1
while (( count < total )); do
    filename=${files[count - 1]}
    echo "$filename"
    nameout=$(echo "$filename" | grep -o '[^ ]*,[^ ]*')
    mkdir -p "$nameout"
    mv "$filename" "$nameout/"
    count=$((count + 1))
done

Upvotes: 1

Related Questions