简体   繁体   English

测试文件存在bash

[英]testing for file existence bash

I've read some other questions, and I feel like i'm doing exactly as everybody else is, but I just can't find the files. 我已经阅读了其他一些问题,我觉得我和其他人一样,但我找不到文件。

file="~/.todo/$1.task"
if [ ! -f "$file" ]; then
    echo "Error. Task ~/.todo/$1.task not found."
    ls ~/.todo/
    exit 1
fi

This is inside of a function when del gets called....so with this command, here's the output: 当del被调用时,这是在函数内部....所以使用这个命令,这是输出:

$ ./todo.sh del 19
Error. ~/.todo/19.task not found.
10.task  13.task  16.task  1.task  6.task  9.task     tododatesorted
11.task  14.task  18.task  3.task  7.task  taskno
12.task  15.task  19.task  4.task  8.task  tododates

How come it says it doesn't exist when really it does? 为什么它真的不存在呢? I've tried -e and -f flags although I don't fully understand the difference. 我试过-e和-f标志虽然我不完全理解其中的区别。

The The difference is in pathname expansion. 不同之处在于路径名扩展。 When you have ~ unquoted, the shell expands it to your home directory. 当你有~引用时,shell会将它扩展到你的主目录。 But when it's within quotation marks, as you have it, it does not get expanded. 但是当它在引号内时,就像你拥有它一样,它不会被扩展。 Eg 例如

$ file="~"; echo $file
~
$ file=~; echo $file
/Users/kevin

You can fix your script in one of two ways: 您可以通过以下两种方式之一修复脚本:

  1. Drop the quotation marks: file=~/.todo/$1.task . 删除引号: file=~/.todo/$1.task In the case of variable assignment like this, whitespace in $1 won't break the command, but you can quote just the $1 if you want. 在像这样的变量赋值的情况下, $1空格不会破坏命令,但如果需要,你可以只引用$1
  2. Use $HOME instead: file="$HOME/.todo/$1.task" 使用$HOME代替: file="$HOME/.todo/$1.task"

I don't think tilde expansion is happening when you check "$file" . 当你检查"$file"时,我不认为代字号扩展正在发生。 So the filename it's looking for still has the tilde character in it, rather than expanding to the home directory. 所以它正在寻找的文件名仍然包含波形符,而不是扩展到主目录。

In Bash you can do this: 在Bash中你可以这样做:

unexpanded_file="~/example.txt"
file="${unexpanded_file/#\~/$HOME}"

This should replace ~ with $HOME 这应该用$ HOME替换〜

Try to get rid of the ';' 试着摆脱';' after the ]...I'm not sure, I can't try it. 之后......我不确定,我不能尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM