José Ferreira
José Ferreira

Reputation: 11

How to check if file exist in a diretory, and overwrite or create

i have a script that manipulate text and create files in one diretory by name/acronym. like that:

#!/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"

but when i try to see if there is a file i try this

#!/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"

but if they have files the script at the moment remove but not create again.. and i have this erros:

[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]$ 

I cannot see what is wrong in script

I change for that :

#!/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"

but i still have :

[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

with your comments i put this :

#!/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"

Upvotes: 0

Views: 320

Answers (1)

wallysslima
wallysslima

Reputation: 19

You can use test command to check if file exits.

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

Or

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

Upvotes: 1

Related Questions