这是我的第一天脚本,我使用linux但需要一个脚本,我一直绞尽脑汁直到我终于寻求帮助。我需要检查一个已经存在目录的目录,看看是否添加了任何不期望的新目录。
好的,我想我已尽可能简单了。以下工作但也显示目录中的所有文件。 我将继续努力,除非有人能告诉我如何不列出文件 |我试过ls -d但它正在做回声"没什么新的"。我觉得自己像个白痴,应该早点得到这个。
#!/bin/bash
workingdirs=`ls ~/ | grep -viE "temp1|temp2|temp3"`
if [ -d "$workingdirs" ]
then
echo "nothing new"
else
echo "The following Direcetories are now present"
echo ""
echo "$workingdirs"
fi
答案 0 :(得分:0)
如果要在创建新目录时执行某些操作,请使用inotifywait
。如果您只是想检查存在的目录是否是您期望的目录,您可以执行以下操作:
trap 'rm -f $TMPDIR/manifest' 0
# Create the expected values. Really, you should hand edit
# the manifest, but this is just for demonstration.
find "$Workingdir" -maxdepth 1 -type d > $TMPDIR/manifest
while true; do
sleep 60 # Check every 60 seconds. Modify period as needed, or
# (recommended) use inotifywait
if ! find "$Workingdir" -maxdepth 1 -type d | cmp - $TMPDIR/manifest; then
: Unexpected directories exist or have been removed
fi
done
答案 1 :(得分:0)
下面的shell脚本将显示目录是否存在。
#!/bin/bash
Workingdir=/root/working/
knowndir1=/root/working/temp1
knowndir2=/root/working/temp2
knowndir3=/root/working/temp3
my=/home/learning/perl
arr=($Workingdir $knowndir1 $knowndir2 $knowndir3 $my) #creating an array
for i in ${arr[@]} #checking for each element in array
do
if [ -d $i ]
then
echo "directory $i present"
else
echo "directory $i not present"
fi
done
输出:
directory /root/working/ not present
directory /root/working/temp1 not present
directory /root/working/temp2 not present
directory /root/working/temp3 not present
**directory /home/learning/perl present**
答案 2 :(得分:0)
这会将列表中的可用目录保存到文件中。第二次运行脚本时,它将报告已删除或添加的目录。
#!/bin/sh
dirlist="$HOME/dirlist" # dir list file for saving state between runs
topdir='/some/path' # the directory you want to keep track of
tmpfile=$(mktemp)
find "$topdir" -type d -print | sort -o "$tmpfile"
if [ -f "$dirlist" ] && ! cmp -s "$dirlist" "$tmpfile"; then
echo 'Directories added:'
comm -1 -3 "$dirlist" "$tmpfile"
echo 'Directories removed:'
comm -2 -3 "$dirlist" "$tmpfile"
else
echo 'No changes'
fi
mv "$tmpfile" "$dirlist"
对于具有非常奇特的名称(包含换行符)的目录,脚本会出现问题。