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.

3
  • 2
    I think ~ only works from the bash command-line. Try $HOME instead? Commented Mar 23, 2020 at 12:04
  • 1
    ~ 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
  • awk '$2 == "jane" {cmd = "if test -e $HOME" $NF "; then echo file $HOME" $NF " exists; else echo file $HOME" $NF " does not exists; fi"; system(cmd)}' file.txt Commented Apr 19 at 9:19

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

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)
0

~ doesn't expand inside double quotes " " or when assigned to a variable as a string, so it remains a literal ~.

Using $HOME will ensure correct expansion to the home directory regardless of quotes.

CORRECT SCRIPT:

#!/bin/bash

file=$(grep ' jane ' ../data/list.txt | cut -d ' ' -f 3)

for i in $file; do
  i="$HOME$i"
  if [ -e "$i" ]; then
    echo "File exists"
  else
    echo "File doesn't exist"
  fi
done

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.