这行代码是什么以及如何工作:{message:0:1} {message:23:17}

What & How does this line of code work: {message:0:1} {message:23:17}

希望有人能帮助我了解这行代码。

使用 diff 命令比较两个文件,这以某种方式允许 message:0:1message:23:17 等其他命令访问它的结果。

这是如何工作的?

message=$(diff previousscan.txt scan.txt | grep 192)

#get first char which indicates if the host came up or went away
iostring="${message:0:1}"

#get first ip-number from the list
computer="${message:23:17}"

#show ip-number in notify if host came up
if [ "$iostring" = \> ]; then
        notify-send "$computer online"
        fi
#show ip-number in notify if host went away
if [ "$iostring" = \< ]; then
        notify-send "$computer offline"
        fi

$message 不是命令;它是一个变量,其中包含 diff 命令的 output。后面几行引用子字符串; ${message:0:1} 是存储在 $message.

中的第一个字符(从偏移量 0 开始的第一个字符)

一个展示子字符串机制的简单例子:

$ message="abcdefghijklmnop"
$ echo ${message:0:1}
a
$ echo ${message:7:3}
hij

构造 foo=$(bar) 在子 shell 中运行命令 bar,如果你简单地 运行 命令 bar在变量 $foo.