相关疑难解决方法(0)

为什么不带引号的带空格的参数扩展在双括号“[[”内起作用,而在单括号“[”内不起作用?

我对使用单括号或双括号感到困惑。看看这段代码:

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}"以防止空格引起的问题?

bash ksh quoting test

106
推荐指数
3
解决办法
4万
查看次数

如何计算目录中的文件数并在数量超过 5 时删除最旧的文件

我创建了一个脚本来在我的 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)

shell-script variable

15
推荐指数
4
解决办法
4237
查看次数

标签 统计

bash ×1

ksh ×1

quoting ×1

shell-script ×1

test ×1

variable ×1