首页 > 解决方案 > 如何检查目录中是否存在文件,并覆盖或创建

问题描述

我有一个脚本,可以按名称/首字母缩写词在一个目录中操作文本并创建文件。像那样:

#!/bin/bash

input="$HOME/folha1/it/colaboradores/users.txt"
out="$HOME/folha1/it/colaboradores/LDAP/"

#check if file exist, if exist rewrite for up


while IFS=';' read -r Act Nome Email Numero Skype; do
     cat  << EOF >> "$out"/"$Act"

Nome: $Nome
Email: $Email
Numero: $Numero
Skype: $Skype
EOF
done < "$input"

但是当我尝试查看是否有文件时,我试试这个

#!/bin/bash

input="$HOME/folha1/it/colaboradores/users.txt"
out="$HOME/folha1/it/colaboradores/LDAP"

if [ "$(ls -A $out)" ]; then
    rm -rf $HOME/folha1/it/colaboradores/LDAP/*
fi
while IFS=';' read -r Act Nome Email Numero Skype; do
     cat  << EOF >> "$out"/"$Act"
        Nome: $Nome
        Email: $Email
        Numero: $Numero
        Skype: $Skype
        EOF
    done < "$input"

但是如果他们现在有文件,则删除但不再创建脚本..我有这个错误:

[teste@oel73 ex02]$ ./ex026.sh
./ex026.sh: line 16: warning: here-document at line 10 delimited by end-of-file (wanted `EOF')
./ex026.sh: line 17: syntax error: unexpected end of file
[teste@oel73 ex02]$ 

我看不到脚本有什么问题

我为此改变:

#!/bin/bash

input="$HOME/folha1/it/colaboradores/users.txt"
out="$HOME/folha1/it/colaboradores/LDAP/"

if [ "$(ls -A $out)" ]; then
        rm -rf $HOME/folha1/it/colaboradores/LDAP/*
fi
while IFS=';' read -r Act Nome Email Numero Skype; do
     var=$(cat <<-EOF
        Nome: $Nome
        Email: $Email
        Numero: $Numero
        Skype: $Skype
        EOF
    )
    echo $var > "$out"/"$Act"
        done < "$input"

但我仍然有:

[teste@oel73 ex02]$ ./ex028.sh 
./ex028.sh: line 10: unexpected EOF while looking for matching `)'
./ex028.sh: line 19: syntax error: unexpected end of file

有了你的评论,我把这个:

#!/bin/bash
input="$HOME/folha1/it/colaboradores/users.txt"
out="$HOME/folha1/it/colaboradores/LDAP/"

if [ "$(ls -A "$out")" ]; then
        rm -rf "$HOME"/folha1/it/colaboradores/LDAP/*
fi
while IFS=';' read -r Act Nome Email Numero Skype; do
     cat  << EOF >> "$out"/"$Act"
Nome: $Nome
Email: $Email
Numero: $Numero
Skype: $Skype
EOF
done < "$input"

标签: bashshell

解决方案


您可以使用test命令来检查文件是否存在。

if [ -f /path/to/file ]; then
  # do something here.
fi

或者

[ -f /path/to/file ] && rm -rf /path/to/file

推荐阅读