bash - 如何检查目录中是否存在文件,并覆盖或创建
问题描述
我有一个脚本,可以按名称/首字母缩写词在一个目录中操作文本并创建文件。像那样:
#!/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"
解决方案
您可以使用test
命令来检查文件是否存在。
if [ -f /path/to/file ]; then
# do something here.
fi
或者
[ -f /path/to/file ] && rm -rf /path/to/file
推荐阅读
- python - 如果列表不够长,则将项目添加到列表中
- c - 如何在C的头文件中隐藏函数?
- javascript - TypeError:当检查值等于零时,无法读取未定义的属性“0”
- terraform - 如何根据资源所在的环境动态命名资源?
- javascript - React-Redux:JSX 中的访问调度类型
- gcc - 刷完 SD 卡 / Buildroot Distro 后安装 GCC
- mongodb - MongoDB 4.4.1 mirroredRead vs secondaryPreferred readPerence
- java - 即使提供了@EnableTransactionManagement,@Transactional 注释也不会回滚 RuntimeException
- r - R随机数据拆分基于2列
- python - 我在python中编写了一个登录项目,但它不起作用