我正在尝试获取一个只有一个文件的文件夹中的文件名。
仅供引用:$FOLDER_TMP
中包含一个空格,这就是我使用 printf
function nameofkeyfile(){
FOLDER_TMP="${PWD%/*/*}/folder/"
FOLDER=$(printf %q "${FOLDER_TMP}")
FILENAME=ls "$FOLDER" # Error: No such file or directory
# or this: FILENAME=$(ls "$FOLDER") # Error: No such file or directory
FNAME=`basename $FILENAME`
}
问题出在这一行: FILENAME=ls "$FOLDER"# 错误:没有这样的文件或目录
你知道为什么吗 - 是的,文件夹就在那里?
如果我回显 $FOLDER
它会给我正确的文件夹。
最佳答案
I am trying to get the filename in a folder with only one file in it.
你的方法肯定是错误的。
相反,请考虑像这样使用通配符:
作业
fname=( "${PWD%/*/*}"/folder/* )
将填充数组 fname
将扩展给定的glob:即目录中的所有文件 "${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"
}
这使用 Bash(命名)数组。如果您希望该函数符合 POSIX 标准,那么这相当简单,因为 POSIX shell 有一个未命名的数组(位置参数):
# 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
!):1
fname=${fname##*/}
更准确地说:在 Bash 版本中,您可以使用:
fname=${fname[0]##*/}
在您使用的 POSIX 版本中:
fname=${1##*/}
1使用参数扩展来获取基本名称时有一个问题,就是 /
的情况。但看来你不会出现这种情况,所以一切都很安全!
关于bash - ls $FOLDER_PATH $FOLDER_PATH : No such file or directory 中有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33198134/