[英]How to pass files to a script that processes folders
So I have this bash script which will rename all the files from the current directory. 所以我有这个bash脚本,它将重命名当前目录中的所有文件。 I need help modifying it so I can instead specify only certain files which will be renamed, but also still have the ability to pass it a directory instead. 我需要修改它的帮助,因此我可以只指定将被重命名的某些文件,但仍然可以将其传递给目录。 I'm not super familiar with bash so it's fairly confusing to me. 我对bash不太熟悉,所以对我来说相当混乱。
#!/bin/bash
#
# Filename: rename.sh
# Description: Renames files and folders to lowercase recursively
# from the current directory
# Variables: Source = x
# Destination = y
#
# Rename all directories. This will need to be done first.
#
# Process each directory’s contents before the directory itself
for x in `find * -depth -type d`;
do
# Translate Caps to Small letters
y=$(echo $x | tr '[A-Z]' '[a-z]');
# check if directory exits
if [ ! -d $y ]; then
mkdir -p $y;
fi
# check if the source and destination is the same
if [ "$x" != "$y" ]; then
# check if there are files in the directory
# before moving it
if [ $(ls "$x") ]; then
mv $x/* $y;
fi
rmdir $x;
fi
done
#
# Rename all files
#
for x in `find * -type f`;
do
# Translate Caps to Small letters
y=$(echo $x | tr '[A-Z]' '[a-z]');
if [ "$x" != "$y" ]; then
mv $x $y;
fi
done
exit 0
Your script has a large number of beginner errors, but the actual question in the title has some merit. 您的脚本有大量的初学者错误,但是标题中的实际问题有一定的价值。
For a task like this, I would go for a recursive solution. 对于这样的任务,我将寻求递归解决方案。
tolower () {
local f g
for f; do
# If this is a directory, process its contents first
if [ -d "$f" ]; then
# Recurse -- run the same function over directory entries
tolower "$f"/*
fi
# Convert file name to lower case (Bash 4+)
g=${f,,}
# If lowercased version differs from original, move it
if [ "${f##*/}" != "${g##*/}" ]; then
mv "$f" "$g"
fi
done
}
Notice how variables which contain file names always need to be quoted (otherwise, your script will fail on file names which contain characters which are shell metacharacters) and how Bash has built-in functionality for lowercasing a variable's value (in recent versions). 请注意, 始终需要用引号将包含文件名的变量加引号(否则,脚本将对包含壳元字符的字符的文件名失败),以及Bash如何具有内置功能来降低变量的值 (在最新版本中)。
Also, tangentially, don't use ls
in scripts and try http://shellcheck.net/ before asking for human debugging help. 同样, 切勿在脚本中使用ls
并尝试http://shellcheck.net/来寻求人工调试帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.