简体   繁体   English

Bash脚本不创建文件夹,而是尝试自行移动

[英]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. 我正在编写一个bash脚本,该脚本应按照片的部分名称对文件夹进行排序。 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. 甚至ShellCheck也找不到任何东西,因此,如果你们能帮助我,那太好了。

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

shellcheck does identify a couple of issues with this script. shellcheck确实发现了此脚本的几个问题。

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. 脚本的问题是print线。

What are you expecting them to be doing? 您期望他们做什么?

The echo lines are printing out your variable values already. echo线已经打印出您的变量值。 Did you mean printf '%s\\n' "$var" there? 你是说那里的printf '%s\\n' "$var"吗? (Which would just duplicate the echo lines output?) (哪个会重复输出echo ?)

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.). print完全是一个不同的命令,它正在尝试弄清楚如何打印给定的参数(例如在打印机等中)。


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. grep的其余用途几乎可以肯定也可以被替换,但是在没有看到代表性的输入和输出的情况下,这不太可能偏离了最初的意图。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM