19

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
  • 7
    You should include the shell you are using into the question. Which is probably bash. – Raphael Ahrens Apr 11 '16 at 7:20
  • 2
    This seems to be done to parse command line arguments. Probably you'll want to know about getopt or getopts to make your life easier (or the life of whomever did this). – Carlos Campderrós Apr 11 '16 at 8:13
31

It's a Substring Expansion (subclass of Parameter Expansion) pattern of shell.

The format is:

${parameter:offset:length}

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:

$ foo=spamegg
$ echo "${foo:0:2}"
sp

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.

  • 1
    Essentially it is checking for whether or not user provided $1 with -c or -r ,which probably better have been implemented with getopts – Sergiy Kolodyazhnyy Apr 12 '16 at 1:01
15

A small extract from man bash:

${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 specified by offset and extending to the end of the value. length and offset are arithmetic expressions (see ARITHMETIC EVALUATION below).

5

This is a simple substring extraction from a variable. The variable in question is the first parameter to the script (which is 1).

If I have a variable, FOO, I can see the first two characters of its value with ${FOO:0:2}. The same thing is being done in your example with the first argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.