建站(二)

Linux命令

Posted by cj on September 24, 2018

整理一下学习Laravel过程中用到的Linux命令。

lsb_release

Linux Standard Base.

我的机器上执行lsb_release -d将输出Description: Ubuntu 16.04.5 LTS,执行lsb_release -c -s将输出xenial,可以用来判断当前是否为指定的Linux发行版。

DISTRO=$(lsb_release -c -s)
[[ ${DISTRO} -ne "xenial" ]] && { echo "仅支持 Ubuntu 16.04 系统"; exit 1; }

$?

上一条命令的返回值。

可以用echo $?查看,也可以用在bash里判断上一条命令的返回值是否为指定数值。

lsb_release -d | grep 'Ubuntu' >& /dev/null
[[ $? -ne 0 ]] && { echo "仅支持 Ubuntu系统"; exit 1; }

id

Print real and effective user and group IDs.

常用id -u获取当前用户ID,并以是否为0判断是否为root用户。

[ $(id -u) != "0" ] && {
    echo "当前账户并非 root,请用 root 账户执行安装脚本(使用命令:sudo -H -s 切换为 root)"
}

set -e

Change the value of shell attributes and positional parameters, or display the names and values of shell variables. -e Exit immediately if a command exits with a non-zero status.

DIR=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )

在当前脚本中设置一个DIR的环境变量,代表当前脚本的文件夹路径。

Bash maintains a number of variables including BASH_SOURCE which is an array of source file pathnames.

${} acts as a kind of quoting for variables.

$() acts as a kind of quoting for commands but they’re run in their own context.

dirname gives you the path portion of the provided argument.

cd changes the current directory.

pwd gives the current path.

&& is a logical and but is used in this instance for its side effect of running commands one after another.

In summary, that command gets the script’s source file pathname, strips it to just the path portion, cds to that path, then uses pwd to return the (effectively) full path of the script. This is assigned to DIR. After all of that, the context is unwound so you end up back in the directory you started at but with an environment variable DIR containing the script’s path.

Reference