Я нашел код для получения текущего статуса Caps Lock (поскольку на клавиатуре этого ноутбука нет светодиодных индикаторов) из здесь .
#!/bin/bash
v=`xset -q | grep Caps`
echo ${v:7:17}
Я понимаю, как работает первая часть; он запрашивает статус, затем ищет строку «Caps» и сохраняет ее в переменной. Я не понимаю вот этой строчки:
echo ${v:7:17}
Эта строчка просто выводит «Caps Lock: off / on», в зависимости от статуса Caps Lock. Я предполагаю, что числа и двоеточия предназначены для указания диапазона, поэтому посторонняя информация не печатается, но числа, похоже, не соответствуют печатаемым символам каким-либо образом, который я могу видеть. Полная строка, которая будет распечатана, выглядит примерно так:
00: Caps Lock: off 01: Num Lock: on 02: Scroll Lock: off
Я спрашиваю: что именно определяет диапазон? По сути, он говорит v: start: end
? Я пытался найти информацию об использовании диапазонов с помощью echo
, но ничего не нашел. На страницах моей системы об этом даже не упоминается об использовании echo
.
См. Расширение подстроки . Формат - $ {строка: позиция: длина}
. Рассмотрим, например:
$ x="123456789012345678901234567890"
$ echo ${x:0:0}
$ echo ${x:0:1}
1
$ echo ${x:0:2}
$ echo ${x:0:3}
123
$ echo ${x:1:3}
234
Дело не в echo
. Речь идет об оболочке. Если вы поищете в man bash
, используя, например, эту команду,
man bash | grep -C5 {
вы увидите такое описание
${parameter:offset}
${parameter:offset:length}
Substring Expansion. Expands to up to length characters of the value of parameter starting at the character specified by
offset. If parameter is @, an indexed array subscripted by @ or *, or an associative array name, the results differ as
described below. If length is omitted, expands to the substring of the value of parameter starting at the character spec‐
ified by offset and extending to the end of the value. length and offset are arithmetic expressions (see ARITHMETIC EVAL‐
UATION below).
echo
печатает только подстроку, но printf
сделает то же самое.
Все описание в man bash
:
${parameter:offset}
${parameter:offset:length}
Substring Expansion. Expands to up to length characters of the value
of parameter starting at the character specified by offset. If
parameter is @, an indexed array subscripted by @ or *, or an asso‐
ciative array name, the results differ as described below. If length
is omitted, expands to the substring of the value of parameter start‐
ing at the character specified by offset and extending to the end of
the value. length and offset are arithmetic expressions (see ARITH‐
METIC EVALUATION below).
If offset evaluates to a number less than zero, the value is used as
an offset in characters from the end of the value of parameter. If
length evaluates to a number less than zero, it is interpreted as an
offset in characters from the end of the value of parameter rather
than a number of characters, and the expansion is the characters
between offset and that result. Note that a negative offset must be
separated from the colon by at least one space to avoid being con‐
fused with the :- expansion.
If parameter is @, the result is length positional parameters begin‐
ning at offset. A negative offset is taken relative to one greater
than the greatest positional parameter, so an offset of -1 evaluates
to the last positional parameter. It is an expansion error if length
evaluates to a number less than zero.
If parameter is an indexed array name subscripted by @ or *, the
result is the length members of the array beginning with ${parame‐
ter[offset]}. A negative offset is taken relative to one greater
than the maximum index of the specified array. It is an expansion
error if length evaluates to a number less than zero.
Substring expansion applied to an associative array produces unde‐
fined results.
Substring indexing is zero-based unless the positional parameters are
used, in which case the indexing starts at 1 by default. If offset
is 0, and the positional parameters are used, $0 is prefixed to the
list.