#!/bin/bash
if [ $# !=1 ]
then
echo Usage: A single argument which is the directory to backup
exit
fi
if [ ! -d ~/projects/$1 ]
then
echo 'The given directory does not seem to exist (possible typo)'
exit
fi
date=`date +%F`
if [ -d ~/projectbackups/$1_date ]
then
echo 'this project has been backed up today, overwrite?'
read answer
if [ $answer != 'y' ]
then
exit
fi
else
mkdir ~/projectbackups/$1_$date
fi
cp -R ~/projects/$1 ~/projectbackups/$1_$date
echo Backup of $1 completed
我在项目文件夹下创建了子文件夹结果,如下所示:
[root@ip-10-0-7-125 result]# pwd
/root/projects/result
但是执行脚本的时候总是报错:
[root@ip-10-0-7-125 bash-tut]# ./pj-backup.sh /root/projects/result/
./pj-backup.sh: line 2: [: 1: unary operator expected
The given directory does not seem to exist (possible typo)
[root@ip-10-0-7-125 bash-tut]# ./pj-backup.sh resutl
./pj-backup.sh: line 2: [: 1: unary operator expected
The given directory does not seem to exist (possible typo)
你们能帮我解决这个问题吗?
答案1
!=
在第 2 行,您错过了条件运算符和参数 ( )之间的空格1
:
[ $# != 1 ]
例子:
$ set -- foo bar
$ [ $# !=1 ] && echo "OK"
bash: [: 2: unary operator expected
$ [ $# != 1 ] && echo "OK"
OK
$#
此外,您还必须进行字符串比较,这在许多此类情况下可能会失败,例如,如果(将其替换为其他变量)的输出被设计为显示01
为而不是1
.因此,在进行算术比较时,请使用算术比较运算符,-ne
在本例中:
[ $# -ne 1 ]
或者
(( $# != 1 ))