Skip to content

Instantly share code, notes, and snippets.

@ssfang
Last active April 15, 2016 05:41
Show Gist options
  • Save ssfang/069e6034808705b813a9f9df34ff6d33 to your computer and use it in GitHub Desktop.
Save ssfang/069e6034808705b813a9f9df34ff6d33 to your computer and use it in GitHub Desktop.
Shell Parameter Manipulation

举例

  • 变量可重入追加
#在CFLAGS变量后追加localCFLAGS变量值
CFLAGS="$CFLAGS $localCFLAGS" #若原来变量为空,则会带有前导空格,此外还有重复调用会多次冗余追加
CFLAGS="${CFLAGS+$CFLAGS }$localCFLAGS" #解决结果前导空格,但还是会冗余追加
CFLAGS="${oldCFLAGS=${CFLAGS+$CFLAGS }}$localCFLAGS" #解决前导空格和冗余追加,但产生新全局变量保存原值

#CFLAGS=originalCFLAGS

# localCFLAGS=/opt/xx/include && CFLAGS="$CFLAGS $localCFLAGS" && echo CFLAGS=\"$CFLAGS\"
## Simple, but if CFLAGS is null, then the outputted CFLAGS has a leading space.

#localCFLAGS=/opt/xx/include && CFLAGS="${CFLAGS+$CFLAGS }$localCFLAGS" && echo CFLAGS=\"$CFLAGS\"
## Strip the outputted CFLAGS a leading space if CFLAGS is null.
## But, if executed more than once in a same shell, CFLAGS will include multiple localCFLAGS-es

localCFLAGS=/opt/xx/include && CFLAGS="${oldCFLAGS=${CFLAGS+$CFLAGS }}$localCFLAGS" && echo CFLAGS=\"$CFLAGS\"
## Solve both the above problems to CFLAGS(a leading space if null and a repeatedly appended value if reentrant)
## But add a global variable to save old value in the shell.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment