在修改以冒号分隔的环境变量时,例如 PYTHONPATH、PATH、CPATH、MANPATH、LD_LIBRARY_PATH、PKG_CONFIG_PATH 等......其中一些变量对尾随冒号具有特殊意义,而其他变量则没有。
对于 PYTHONPATH 和 PATH,如果变量之前未设置,可以以不会意外引入尾随(或前导)冒号的方式预先(或附加)新目录:
export PYTHONPATH="/some/path${PYTHONPATH+":"}${PYTHONPATH-}"
解释:
${PYTHONPATH+":"}
扩展为 :
如果设置了 PYTHONPATH,无论 PYTHONPATH 是否为空。
${PYTHONPATH-}
如果设置了将扩展到 PYTHONPATH 的内容,但如果未设置 PYTHONPATH,则 ${PYTHONPATH-}
扩展为空 --- 就像通常的 ${PYTHONPATH}
.
${PYTHONPATH-}
与 ${PYTHONPATH-""}
相同意思是在未设置 PYTHONPATH 时替换 ""(无)。
推荐理由${PYTHONPATH-}
在 ${PYTHONPATH}
这是${PYTHONPATH-}
当 PYTHONPATH 未设置且您的脚本已执行时,不会产生错误 set -u
引发未设置变量的错误。
例如:
export PYTHONPATH=$SPARK_HOME/python:$SPARK_HOME/python/lib/py4j-0.10.7-src.zip:$PYTHONPATH 会引入当前工作目录
[root@node02 ~]# python3 #当前目录为/root
Python 3.7.8 (default, Apr 27 2021, 13:33:25)
[GCC 7.3.1 20180303 (Red Hat 7.3.1-5)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/local/spark-2.4.3-bin-hadoop2.7/python', '/usr/local/spark-2.4.3-bin-hadoop2.7/python/lib/py4j-0.10.7-src.zip', '/root', '/usr/local/python3/lib/python37.zip', '/usr/local/python3/lib/python3.7', '/usr/local/python3/lib/python3.7/lib-dynload', '/usr/local/python3/lib/python3.7/site-packages']
export PYTHONPATH="/tmp${PYTHONPATH+":"}${PYTHONPATH-}" 不会引入当前工作目录
[root@node02 ~]# python3 #当前目录为 /root
Python 3.7.8 (default, Apr 27 2021, 13:33:25)
[GCC 7.3.1 20180303 (Red Hat 7.3.1-5)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/tmp', '/usr/local/python3/lib/python37.zip', '/usr/local/python3/lib/python3.7', '/usr/local/python3/lib/python3.7/lib-dynload', '/usr/local/python3/lib/python3.7/site-packages']