简体   繁体   English

用于测试文件存在的 Bash 脚本

[英]Bash script to test file existence

I'm trying to check if the filespaths written in a txt file (of user jane) are present in the system.我正在尝试检查系统中是否存在写入(用户 jane 的)txt 文件中的文件路径。 This is the file list.txt:这是文件 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.是真的,但是当我像上面的脚本一样编写它时,它返回false。 Is it related to the way i'm adding the ~?它与我添加 ~ 的方式有关吗? Without it the command by itself returns false.没有它,命令本身会返回 false。

The ~ in front of ~/data/jane_profile_07272018.doc is roughly equivalent to $HOME/data/jane_profile_07272018.doc .~前面~/data/jane_profile_07272018.doc大致相当于$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.因此,它不是在 root /下查找文件,而是在您的 HOME 目录下查找文件。

You should do:你应该做:

if [[ -e "$file" ]]; then
    echo "$file: exists"
else
    echo "file: does not exist"
fi

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

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