编写 Linux Bash 脚本

编写 Linux Bash 脚本

我有 bash 脚本

#!/bin/sh

export DEBIAN_FRONTEND=noninteractive;

apt-get update;
apt-get -y upgrade;

apt-get install -y python-pip python-dev nginx;

##After the command output shows visible commands after + sign in bash
set -x -e 

pip install virtualenv;
virtualenv /home/user/virtualenv;
source /home/user/virtualenv/bin/activate;

pip install gunicorn;

systemctl start gunicorn;
systemctl restart nginx;

命令的输出显示如下

+ virtualenv /home/user/virtualenv
New python executable in /home/user/virtualenv/bin/python
Installing setuptools, pip, wheel...done.
+ source /home/user/virtualenv/bin/activate
++ deactivate nondestructive
++ unset -f pydoc
++ '[' -z '' ']'
++ '[' -z '' ']'
++ '[' -n /bin/bash ']'
++ hash -r
++ '[' -z '' ']'
++ unset VIRTUAL_ENV
++ '[' '!' nondestructive = nondestructive ']'
++ VIRTUAL_ENV=/home/user/virtualenv
++ export VIRTUAL_ENV
++ _OLD_VIRTUAL_PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
++ PATH=/var/www/html/askbotenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
++ export PATH
++ '[' -z '' ']'
++ '[' -z '' ']'
++ _OLD_VIRTUAL_PS1=
++ '[' x '!=' x ']'
+++ basename /home/user/virtualenv
++ PS1='(askbotenv) '
++ export PS1
++ alias pydoc
++ '[' -n /bin/bash ']'
++ hash -r
+ pip install gunicorn
Collecting gunicorn

我想删除+命令之前的那些标志,因为set -x -e

答案1

set -x -e命令将打开跟踪-x(这就是+在输出中产生提示的原因),并且如果-e.

不过,让脚本在出现错误时直接退出仍然是一件好事,所以我建议将该行更改为仅说

set -e

或者,由于跟踪输出到标准错误流,因此您可以/dev/null在运行脚本时将其重定向到:

$ ./myscript 2>/dev/null

...但这也会丢弃您可能真正想看到的任何其他诊断消息。

相关内容