变量作为 Bash 脚本中的命令 [英] Variables as commands in Bash scripts
问题描述
我正在编写一个非常简单的 Bash 脚本,它tars 给定目录, 对其输出进行加密,然后将生成的文件拆分为多个较小的文件,因为备份媒体不支持大文件.
I am writing a very simple Bash script that tars a given directory, encrypts the output of that, and then splits the resultant file into multiple smaller files since the backup media doesn’t support huge files.
我对 Bash 脚本没有很多经验.我相信我在正确引用我的变量以允许参数中有空格时遇到了问题.脚本如下:
I don't have a lot of experience with Bash scripting. I believe I’m having issues with quoting my variables properly to allow spaces in the parameters. The script follows:
#! /bin/bash
# This script tars the given directory, encrypts it, and transfers
# it to the given directory (likely a USB key).
if [ $# -ne 2 ]
then
echo "Usage: `basename $0` DIRECTORY BACKUP_DIRECTORY"
exit 1
fi
DIRECTORY=$1
BACKUP_DIRECTORY=$2
BACKUP_FILE="$BACKUP_DIRECTORY/`date +%Y-%m-%dT%H-%M-%S.backup`"
TAR_CMD="tar cv $DIRECTORY"
SPLIT_CMD="split -b 1024m - "$BACKUP_FILE""
ENCRYPT_CMD='openssl des3 -salt'
echo "$TAR_CMD | $ENCRYPT_CMD | $SPLIT_CMD"
$TAR_CMD | $ENCRYPT_CMD | $SPLIT_CMD
say "Done backing up"
运行此命令失败:
拆分:foo/2009-04-27T14-32-04.backup"aa:没有那个文件或目录
split: "foo/2009-04-27T14-32-04.backup"aa: No such file or directory
我可以通过删除设置 $SPLIT_CMD
的 $BACKUP_FILE
周围的引号来修复它.但是,如果我的备份目录的名称中有空格,则它不起作用.此外,如果我复制并粘贴回声"的输出命令直接进入终端,它工作正常.很明显,我不明白 Bash 是如何逃避事物的.
I can fix it by removing the quotes around $BACKUP_FILE
where I set $SPLIT_CMD
. But, if I have a space in the name of my backup directory, it doesn't work. Also, if I copy and paste the output from the "echo" command directly into the terminal, it works fine. Clearly there's something I don't understand about how Bash is escaping things.
推荐答案
不要将整个命令放在变量中.尝试恢复引用的参数会遇到很多麻烦.
Simply don't put whole commands in variables. You'll get into a lot of trouble trying to recover quoted arguments.
还有:
- 避免在脚本中使用全大写的变量名.这是一种用脚射击自己的简单方法.
- 不要使用反引号.使用 $(...) 代替;它可以更好地嵌套.
#! /bin/bash
if [ $# -ne 2 ]
then
echo "Usage: $(basename $0) DIRECTORY BACKUP_DIRECTORY"
exit 1
fi
directory=$1
backup_directory=$2
current_date=$(date +%Y-%m-%dT%H-%M-%S)
backup_file="${backup_directory}/${current_date}.backup"
tar cv "$directory" | openssl des3 -salt | split -b 1024m - "$backup_file"
这篇关于变量作为 Bash 脚本中的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!