SetSlapShot
SetSlapShot

Reputation: 1298

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:

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

Upvotes: 1

Views: 509

Answers (4)

Joe Alamo
Joe Alamo

Reputation: 133

In Bash you can do this:

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

This should replace ~ with $HOME

Upvotes: 0

Kevin
Kevin

Reputation: 56129

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"

Upvotes: 7

Salvatore
Salvatore

Reputation: 1185

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

Upvotes: -4

Jim Lewis
Jim Lewis

Reputation: 45115

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.

Upvotes: 1

Related Questions