I am looking into the code displayed below and it checks the input if the row/column arguments start with either -r
or -c
.
What does ${1:0:2}
mean in this context?
rowArgName="-r"
colArgName="-c"
if [ "${1:0:2}" != $rowArgName ] && [ "${1:0:2}" != $colArgName ]
then
echo $correctCmdMsg >&2
exit 1
fi
Best Answer
It's a Substring Expansion (subclass of Parameter Expansion) pattern of shell.
The format is:
and indexing starts at 0.
Say, you have a variable
foo
, then${foo:0:2}
yields the first two characters (from position 0 the next 2).Example:
In your case, the first number,
1
, refers to variable name$1
, which is the first argument passed via command line (in the main program) or the first argument passed to the function.So in your case,
"${1:0:2}"
will:start extracting the substring starting from index 0 i.e. first character
and continue upto next two characters
so after the operation you will get the first two characters (indexed at 0 and 1) of the input string.
The
[ "${1:0:2}" != $rowArgName ]
and[ "${1:0:2}" != $colArgName ]
are checking if the output subtring is equal to some other strings.