4

I'm trying to understand one script, which uses this command: set -- ${line#?}. I understand the set command and the curly brackets. But I can't find any explanation for the "#?" part.

1 Answer 1

18

${line#?}, a standard sh parameter expansion operator (originated in the Korn shell) simply removes the first character from the variable line. For example:

$ line=abc; echo "${line#?}" bc 

More generally, ${variablename#word} removes word from the beginning of the contents of variablename. This is called prefix removal. word is treated as a glob which means that ? matches any single character.

Documentation

From man bash (where bash is the GNU implementation of an sh interpreter):

${parameter#word}
${parameter##word}

Remove matching prefix pattern. The word is expanded to produce a pattern just as in pathname expansion, and matched against the expanded value of parameter using the rules described under Pattern Matching below. If the pat‐ tern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the # case) or the longest matching pattern (the ## case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the ex‐ pansion is the resultant list.

Aside: Suffix removal

Just as ${parameter#word} and ${parameter##word} do prefix removal, it is helpful to know that the shell also offers ${parameter%word} and ${parameter%%word} which do suffix removal. Suffix removal is commonly used to remove extensions from file names:

$ name=file.jpg; echo "${name%.jpg}" file 
3
  • 2
    That's what I kinda assumed, thanks for your answer! Commented Jul 12, 2020 at 19:24
  • 2
    It might be helpful to mention that %/%% is also available (I use it far more often, to strip extensions). Commented Jul 13, 2020 at 8:07
  • 1
    @chrylis-cautiouslyoptimistic- Good suggestion. I just added a section to mention suffix removal. Commented Jul 13, 2020 at 21:09

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.