1

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:

$ ./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.

4 Answers 4

7

The The difference is in pathname expansion. When you have ~ unquoted, the shell expands it to your home directory. But when it's within quotation marks, as you have it, it does not get expanded. E.g.

$ 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. 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.
  2. Use $HOME instead: file="$HOME/.todo/$1.task"
0
1

I don't think tilde expansion is happening when you check "$file". So the filename it's looking for still has the tilde character in it, rather than expanding to the home directory.

1
  • Indeed. But the tilde expansion does happen if you remove the quotes arround $file. Commented Mar 9, 2013 at 21:46
0

In Bash you can do this:

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

This should replace ~ with $HOME

-4

Try to get rid of the ';' after the ]...I'm not sure, I can't try it.

1
  • 1
    that's just the syntax for putting multiple things on one line. Commented Mar 9, 2013 at 21:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.