![脚本输入数据运行基于它的命令](https://linux22.com/image/216038/%E8%84%9A%E6%9C%AC%E8%BE%93%E5%85%A5%E6%95%B0%E6%8D%AE%E8%BF%90%E8%A1%8C%E5%9F%BA%E4%BA%8E%E5%AE%83%E7%9A%84%E5%91%BD%E4%BB%A4.png)
不知道从哪里开始我只知道基本的文本处理。
我正在尝试创建一个脚本,该脚本将根据 VM 名称(作为命令参数给出)搜索 zfs 快照,然后选择最新的快照,最后将其传输到另一台服务器。
例如我会运行
script.sh 2839
哪个将首先运行
zfs list -t snapshot | grep "vm-2839"
找到以下文件,根据日期选择最新的
zfs/backups/vm-2839-disk-0@ZAP_home1_2023-01-20T21:53:29p0000--1d 193M - 11.9G -
zfs/backups/vm-2839-disk-0@ZAP_home1_2023-01-22T11:54:19p0000--1d 18.2M - 11.9G -
zfs/backups/vm-2839-disk-0@ZAP_home1_2023-01-22T16:08:20p0000--1d 0B - 11.9G -
然后它最终应该将该文件发送到外部服务器
zfs send zfs/backups/vm-2839-disk-0@ZAP_home1_2023-01-22T16:08:20p0000--1d | ssh [email protected] "zfs receive zfs/vm-2839-disk-0"
答案1
幸运的是,您使用的日期格式可以按数字排序。
所以解决这个问题的方法是
- 告诉
zfs list
不要输出你不关心的数据 - 告诉
zfs list
按照创建日期排序 - 获取第一行输出并随之滚动
所以,我现在坐在前面的机器上没有设置 zfs,所以我只是继续官方文档——你应该这样做!
#!/bin/bash
machine=$1 # save the first passed argument in the variable "machine"
zfs list -o name -s creation -t snapshot | grep "vm-${machine}" |tail -n1 | xargs zfs send | ssh [email protected] "zfs receive zfs/vm-${machine}-disk-0"
# ^------------------------------ specify the field(s) to display;
# ^ "name" is the first mentioned on the
# | man page.
# |
# \----------------------- specify which field to sort by. As
# linked to, zfsprops man page tells
# that "creation" is the time the
# snapshot was created
#
# ^---- pipe to "tail", which
# ^---- keeps the last 1 line(s)
#
# ^---- pipe to xargs, which
# takes the input and
# appends it as argument
# to the passed command
# "zfs send"
#
# ^---- pipe to
# your ssh
# as before