首页 > 解决方案 > 检查目录中是否存在文件

问题描述

我想检查目录中是否存在某些文件。如果是,我想跳过这些文件而不执行任何程序。如果不是,那么我想执行一些程序。

假设在目录中/setup/server我有以下文件:

systems-server01
systems-server02
system-server03
system-server04

如果我运行该命令,./add-system.sh system-server05我的代码应该执行 readline 过程并添加一个新服务器。

但是如果我运行命令./add-system.sh system-server04我的代码应该回显“服务器已经存在,请输入新服务器”。

这是我到目前为止所拥有的

#!/bin/bash
DOMAIN=my.home.fs.cville.com
if [ $# -lt 1]; then
   echo "Please enter filename\n"
   exit
fi

#I think this is where I need to do the check if files exist but I have 
#problem figure out how to do it

while read line ; do
    alt=(${line[@]}
    hostname=${alt[0]}
    ipaddress=${$alt[1]}
    mac=${alt[2]}
    iface=${alt[3]}
    profile=${alt[4]}

    copper system add --cobber --name=$hostname --profile=$profile --ip- 
    address=$ipaddress \ --interface=$iface --mac=$mac 
    --hostname=$hostname --dns-name=${hostname}.$DOMAIN
done<$1
copper sync

标签: bashshell

解决方案


是的,您的评论块在哪里,您可以添加如下检查:

if [ -e /setup/server/"$1" ]; then
    echo "file exists, nothing to do"
    exit
fi

有关可用的各种测试,请参阅“帮助测试”。'[' 是 'test' 的同义词


推荐阅读