我有一个像这样的 bash 脚本
#!/bin/bash
DATABASE_NAME=my_database
export DATABASE_NAME
run_some_other_command
Run Code Online (Sandbox Code Playgroud)
他们首先声明变量并将其设置为一个值,然后在单独的行中将其导出。就我个人而言,我喜欢只用一行来做:
export DATABASE_NAME=my_database
Run Code Online (Sandbox Code Playgroud)
有一些风格规则反对这种做法吗?我见过别人把报关和出口分开,但不知道为什么。
如果有帮助的话,这个脚本可以在 Linux Mint 上运行,但也可以在其他 Linux 甚至 Mac 上运行。
因为export是命令;当赋值来自命令或子 shell 输出时,它自己的返回码将覆盖/屏蔽赋值命令的返回码:
# the return-code of the getDBName function call
# is masked by the export command/statement
export DATABASE_NAME=$(getDBName)
Run Code Online (Sandbox Code Playgroud)
# Separate export
export DATABASE_NAME
# Allow capture and use of the getDBName return code
if ! DATABASE_NAME=$(getDBName)
then printf 'Failed getDBName with RC=%d\n' "$?" >&2
fi
Run Code Online (Sandbox Code Playgroud)