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
${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. Thewordis 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 - 2That's what I kinda assumed, thanks for your answer!user419050– user4190502020-07-12 19:24:41 +00:00Commented Jul 12, 2020 at 19:24
- 2It might be helpful to mention that
%/%%is also available (I use it far more often, to strip extensions).chrylis -cautiouslyoptimistic-– chrylis -cautiouslyoptimistic-2020-07-13 08:07:56 +00:00Commented Jul 13, 2020 at 8:07 - 1@chrylis-cautiouslyoptimistic- Good suggestion. I just added a section to mention suffix removal.John1024– John10242020-07-13 21:09:30 +00:00Commented Jul 13, 2020 at 21:09