0

I'm trying to check if the filespaths written in a txt file (of user jane) are present in the system. This is the file list.txt:

001 jane /data/jane_profile_07272018.doc
002 kwood /data/kwood_profile_04022017.doc
003 pchow /data/pchow_profile_05152019.doc
004 janez /data/janez_profile_11042019.doc
005 jane /data/jane_pic_07282018.jpg
006 kwood /data/kwood_pic_04032017.jpg
007 pchow /data/pchow_pic_05162019.jpg
008 jane /data/jane_contact_07292018.csv
009 kwood /data/kwood_contact_04042017.csv
010 pchow /data/pchow_contact_05172019.csv

This is the script I wrote:

#!/bin/bash
file=$(grep ' jane ' ../data/list.txt | cut -d ' ' -f 3)
for i in $file
do
  i="~${i}"
  if (test -e $i); then echo "File exists"; else echo "File doesn't exist"; fi
done

I don't understand why the command

test -e ~/data/jane_profile_07272018.doc

is true, but when I write it like in the script above it returns false. Is it related to the way i'm adding the ~? Without it the command by itself returns false.

2
  • 1
    I think ~ only works from the bash command-line. Try $HOME instead?
    – Gem Taylor
    Commented Mar 23, 2020 at 12:04
  • ~ will work in scripts, but not if it's in quotes (as it is here). So try i="${HOME}${i}" instead. Commented Mar 23, 2020 at 16:04

1 Answer 1

1

The ~ in front of ~/data/jane_profile_07272018.doc is roughly equivalent to $HOME/data/jane_profile_07272018.doc. So instead of looking for the file under root /, it is looking for the file under your HOME directory.

You should do:

if [[ -e "$file" ]]; then
    echo "$file: exists"
else
    echo "file: does not exist"
fi
1
  • while IFS= read -r f; do p="$HOME/$f"; if [ -e "$p" ]; then printf '%s exists\n' "$p"; fi; done < <(sed -n 's/^[[:digit:]]\+ jane //p' list.txt)
    – Léa Gris
    Commented Mar 23, 2020 at 12:38

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.