我对使用单括号或双括号感到困惑。看看这段代码:
dir="/home/mazimi/VirtualBox VMs"
if [[ -d ${dir} ]]; then
echo "yep"
fi
Run Code Online (Sandbox Code Playgroud)
尽管字符串包含空格,但它工作得很好。但是当我将其更改为单括号时:
dir="/home/mazimi/VirtualBox VMs"
if [ -d ${dir} ]; then
echo "yep"
fi
Run Code Online (Sandbox Code Playgroud)
它说:
./script.sh: line 5: [: /home/mazimi/VirtualBox: binary operator expected
Run Code Online (Sandbox Code Playgroud)
当我将其更改为:
dir="/home/mazimi/VirtualBox VMs"
if [ -d "${dir}" ]; then
echo "yep"
fi
Run Code Online (Sandbox Code Playgroud)
它工作正常。有人可以解释发生了什么吗?什么时候应该在变量周围分配双引号,"${var}"以防止空格引起的问题?
我创建了一个脚本来在我的 CentOS 7 服务器上运行自动备份。备份存储到 /home/backup 目录。该脚本有效,但现在我想合并一种在备份发生后计算文件数的方法,如果数量超过 5,则删除最旧的备份。
以下是我的备份脚本。
#!/bin/bash
#mysqldump variables
FILE=/home/backup/databasebk_!`date +"Y-%m-%d_%H:%M"`.sql
DATABASE=database
USER=root
PASS=my password
#backup command process
mysqldump --opt --user=${USER} --password=${PASS} ${DATABASE} > ${FILE}
#zipping the backup file
gzip $FILE
#send message to the user with the results
echo "${FILE}.gz was created:"
ls -l ${FILE}.gz
# This is where I would like to count the number of files
# in the directory and if there are more than 5 I would like
# to delete the oldest …Run Code Online (Sandbox Code Playgroud)