Combining multiple bash parameter substitutions within same variable set line without using any other commands [closed]

帅比萌擦擦* 提交于 2019-12-03 01:21:58

问题


Example of what I want to combine:

sVar=$(whoami)
sVar=${sVar^}
sVar=${sVar::1}

Output:

  • Uppercase first character of username

Requirements:

  • One-liner
  • Do the rest of the processing with parameter substitutions except for the initial command substitution above $(whoami)

I realize this can be done with tr, sed, awk, printf, cut, etc.; but that is not the point of the question.

Any help is appreciate!

This isn't the real code or anything indicative of what I am wanting to actually do. I will often default (or try to) to using just one command over concatenating multiple commands.

I've seen other posts state that concatenating within the braces are not possible, but I know that everything is possible.

Please don't:

  • Reference other posts as duplicate that say it's impossible

回答1:


One liner:

sVar=$(whoami) sVar=${sVar^} sVar=${sVar::1}

It may not be what you were looking for, but it is certainly a single command and uses parameter substitutions. A single command can consist of multiple variable assignments, in which case they are performed left to right.

The subject of a parameter substitution is a variable name, an indirection (a ! followed by a variable name), or a subscript expression (a variable name -- not an indirection -- followed by a subscript within [ and ]. That's a bit limited, to be sure, but that's bash. (Posix shell is even more restrictive; it has no indirection nor arrays, and fewer types of expansion.)


Posix wording from XCU, emphasis added:

When a given simple command is required to be executed… the following expansions, assignments, and redirections shall all be performed from the beginning of the command text to the end:

  1. Each variable assignment shall be expanded for tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal prior to assigning the value.


来源:https://stackoverflow.com/questions/37257993/combining-multiple-bash-parameter-substitutions-within-same-variable-set-line-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!