加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – Bash – 检查文件是否存在,文件名包含空格

发布时间:2020-12-14 01:12:54 所属栏目:Linux 来源:网络整理
导读:我在 Bash中测试是否存在文件,其中文件名使用$(printf’%q’“$FNAME”)进行转义 如下面的注释示例所示,使用if [-f $FNAME]时总会产生错误.如何测试包含空格和其他字符的文件名? #!/usr/bin/env bash# code used in Raspberry Pi Podcasting Jukebox proje
我在 Bash中测试是否存在文件,其中文件名使用$(printf’%q’“$FNAME”)进行转义
如下面的注释示例所示,使用if [-f $FNAME]时总会产生错误.如何测试包含空格和其他字符的文件名?

#!/usr/bin/env bash

# code used in Raspberry Pi Podcasting Jukebox project
# youtube-dl -f 17 --get-filename https://www.youtube.com/watch?v=AgkM5g_Ob-w
# returns "HOW ABUNDANCE WILL CHANGE THE WORLD - Elon Musk 2017-AgkM5g_Ob-w.3gp"

# Purpose: To test if file exists before downloading
# for testing purposes using an existing regular file "abc def ghi"
AFILE="abc def ghi"
TFILE=$(printf '%q' "$AFILE") # Escaping filename using printf
echo $TFILE # returns abc def ghi
# if [ -f $AFILE ] # this test returns false every time with error [:too many arguments

if [ -f $TFILE ] # This test also returns FALSE with err [: too many arguments
then
  echo "Existing"
  # don't download
else
  echo "Not existing"
  # youtube-dl http://www.youtube.com/watch?v=AgkM5g_Ob-w
fi

编辑:这个问题的解决方案涉及通过[[]]使测试条件成为Bash表达式的具体问题

解决方法

总是引用你的文件名,使用%q来转义空格的想法是对的,但是当与[运算符一起使用时,未加引号的$TFILE被分成多个单词,导致-f操作数在实际上接收到太多的参数期待一个论点.因此,一旦你引用它,就保留了空格,并在条件中传递了一个文字的单个参数.

testFile="abc def ghi"
printf -v quotedFile '%q' "$testFile"

if [ -f "$quotedFile" ]; then
    printf 'My quoted file %s existsn' "$quotedFile"
fi

以上应该适用(在任何POSIX兼容的shell中使用[].但是,如果您单独针对bash shell编写脚本,则可以使用[[在其中作为表达式求值时从不需要引用).所以你可以做到

file_with_spaces="abc def ghi"
if [[ -f $file_with_spaces ]]; then
    printf 'My quoted file %s existsn' "$file_with_spaces"
fi

但总的来说,在bash中为变量添加引号并没有什么坏处.你总是可以做到.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读