I am trying to get the filename in a folder with only one file in it.
你确有错误的做法。
而应考虑使用通配符,像这样:
分配
fname=("${PWD%/*/*}"/folder/*)
将填充阵列fname
会给出水珠的扩展:即在该目录"${PWD%/*/*}"/folder/
的所有文件,如果有的话。如果根本没有文件,你的数组将包含glob,逐字。
因此,更可靠的方法是这样的:
nameofkeyfile() {
fname=("${PWD%/*/*}"/folder/*)
# Now check that there's at most one element in the array
if ((${#fname[@]} > 1)); then
echo "Oh no, there are too many files in your folder"
return 1
fi
# Now check that there is a file
if [[ ! -f ${fname[0]} ]]; then
echo "Oh no, there are no files in your folder"
return 1
fi
# Here, all is good!
echo "Your file is: $fname"
}
这使用击(命名)阵列。如果你想要的功能是POSIX兼容的,这是相当简单的,因为POSIX壳有一个未命名的数组(位置参数):
# POSIX-compliant version
nameofkeyfile() {
set -- "${PWD%/*/*}"/folder/*
# Now check that there's at most one element in the array
if [ "$#" -gt 1 ]; then
echo "Oh no, there are too many files in your folder"
return 1
fi
# Now check that there is a file
if [ ! -f "$1" ]; then
echo "Oh no, there are no files in your folder"
return 1
fi
# Here, all is good!
echo "Your file is: $1, I'll store it in variable fname for you"
fname=$1
}
我没有剥去文件名的完整路径,但是这真的很容易(不要使用basename
!):
fname=${fname##*/}
更确切地说:在Bash版本,你会使用:
fname=${fname[0]##*/}
,并在POSIX版本,你会使用:
fname=${1##*/}
使用参数展开得到一个catch基本名称,这是/
的情况。但看起来你不会在这种情况下,所以它是安全的!
如果你的'find'版本支持'-printf',我建议使用'find“$ FOLDER_TMP”-type f -printf%f' –