0

This was taken from another stack question that helped me out with something but there wasn't an explanation for the code and I'm not sure hwo to read it.
The problem was stripping trailing characters from a string in bash. This was one of the solutions.

foo="hello world"
echo ${foo%?}
hello worl

I'm confused why this works and how bash interprets the middle line.
I believe the ${ SOMETHING } is an evaluation, but its the "%?" that is confusing me.

  • This is [parameter expansion](http://wiki.bash-hackers.org/syntax/pe). We already have many Q&A entries in the knowledgebase explaining it. [BashFAQ #100](http://mywiki.wooledge.org/BashFAQ/100), [BashFAQ #73](http://mywiki.wooledge.org/BashFAQ/073) and [the relevant BashGuide entry](http://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion) are also pertinent. – Charles Duffy Dec 30 '18 at 17:56
  • 1
    BTW, `echo "${foo%?}"` is more reliable -- leaving an expansion unquoted tells the shell to do a bunch of extra, potentially-unwanted processing steps on its output. And `printf '%s\n' "${foo%?}"` is even more reliable than that -- see the caveats in the APPLICATION USAGE and RATIONALE sections of the POSIX spec for `echo` at http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html – Charles Duffy Dec 30 '18 at 17:59
  • In that usage: % -> delete next ? -> char see: [enter link description here][1] [1]: http://wiki.bash-hackers.org/syntax/pe#common_use – LORDTEK Dec 30 '18 at 18:00
  • @LORDTEK, yes, that's the first link in the initial comment. :) – Charles Duffy Dec 30 '18 at 18:00
  • If you want, I will remove my comment. But even the same page, I linked on the related title. (title: common_use) – LORDTEK Dec 30 '18 at 18:04
  • Sorry I clearly didn't search the right terms. Knowing what it is called is helpful. Should I delete the question since its a duplicate? – Michael Anonymous Dec 30 '18 at 18:47
  • @MichaelAnonymous Leaving it up is fine, it now serves as a sign post for other people looking for the same. – Benjamin W. Dec 30 '18 at 19:19

0 Answers0