I have to check the existence of the files dir1
and dir2
. Then, delete them recursively, else print some message. Here is my code:
if [ -d "dir1"] && [-d "dir2"]; then
echo "directory exists"
echo "deleting existing files...."
sleep 2
rm -r dir1
rn -r dir1
echo "exisitng files deleted!!"
else
echo "directory does not exist"
fi
This is giving me an error saying missing expression.
./check.sh: line 16: [: missing `]'
directory does not exist.
What is wrong here?
This line is not properly written:
if [ -d "dir1"] && [-d "dir2"]; then
^ ^ ^
missing spaces
should be
if [ -d "dir1" ] && [ -d "dir2" ]; then
Then you have this:
rn -r dir1
^
rn does not exist
which should be rm
and dir2
becaus you already deleted dir1
:
rm -r dir2
You need to have:
[ -d "dir" ]
and not :
[-d "dir"]
Note the spaces. See fedorqui's answer regarding the other problems.
Proposed more robust solution (add more verbose output to your liking):
#!/bin/sh
dirs="dir1 dir2" # Directory names may not contain spaces
for dir in $dirs; do
[ ! -d $dir ] || rm -r $dir || echo "failed to remove $dir"
done
Note that your solution with &&
requires both directories to exist for it to trigger removal. I don't know if that is your intention or not. My solution looks if any of the directories in the dirs
variable exists and in that case tries to remove them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.