bash - ls $FOLDER_PATH $FOLDER_PATH : No such file or directory 中有空格

标签 bash shell sh

我正在尝试获取一个只有一个文件的文件夹中的文件名。

仅供引用:$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/

相关文章:

bash - 在您的 ~/.bashrc 文件中引用/etc/bashrc 是强制性的还是必需的?

bash - 在 grep 中搜索字符串模式以获取滑动窗口

python os.system 命令跳过与命令中的 awk 关联的空格 ""

sh - 在 sh 中逐行读取命令输出(无 bash)

linux - 如何在shell脚本中使用do循环读取多个具有相似名称的文件

linux截断第一行-有没有更好的方法

bash - 使用 bash printf 包装列的正确方法

linux - Minicom 运行脚本不理解变量

bash - 使用 Grep(或任何其他命令行工具)来计算包含不同模式的行

mysql - 命令被 bash 错误解释