A collection of Bash starter scripts for easily creating safe and usefulcommand line programs.
Bash Boilerplate is great for making standalone, portable, single-file command lineprograms as well as shell initialization functions. For a frameworkapproach that's useful for task and build files, try Bask,a pure Bash mini-framework for command-centric Bash scripts.
A simple bash script with some basic strictness checks and help features.Useful for simple programs that don't have many features and don't takeoptions other than help.
-h
or --help
.A simple bash script with some basic strictness checks, option parsing,help features, easy debug printing. Useful for regular scripts.
-h
or --help
,debug
printing with --debug
flag,_exit_1
and _warn
functions for error messages,An example of a bash program with subcommands. This contains lots of featuresand should be usable for creating bash programs that do multiple relatedtasks.
-h
or --help
,debug
printing with --debug
flag,_exit_1
and _warn
functions for error messages,Shell function examples and boilerplate. The functions in this file areintended to be included in the interactive shell, which can be done bydefining them in a shell init file like ~/.bashrc
.
Helper functions. These functions are primarily intended to be used withinscripts, but can be adapted for use as shell functions.
Use it. It's super useful.
ShellCheck is a static analysis and linting tool for sh/bash scripts.It's mainly focused on handling typical beginner and intermediate levelsyntax errors and pitfalls where the shell just gives a cryptic errormessage or strange behavior, but it also reports on a few more advancedissues where corner cases can cause delayed failures.
It can be used with Vim viaSyntastic, Emacs viaFlycheck, Sublime Text 3 viaSublimeLinter, VS Code via vscode-shellcheck, and Atom vialinter,atom-lint,or linter-shellcheck.
These boilerplate scripts use some common settings for enforcing strictnessin Bash scripts, thereby preventing some errors.
For some additional background, see Aaron Maxwell's"Unofficial Bash Strict Mode" (redsymbol.net)post.
Add this to the top of every script (note: an extended version of this isalready included in the boilerplate scripts):
# Bash 'Strict Mode'
# http://redsymbol.net/articles/unofficial-bash-strict-mode
# https://github.com/xwmx/bash-boilerplate#bash-strict-mode
set -o nounset
set -o errexit
set -o pipefail
IFS=$'\n\t'
set -o nounset
/ set -u
Treat unset variables and parameters other than the special parameters @
or*
as an error when performing parameter expansion. An 'unbound variable'error message will be written to the standard error, and a non-interactiveshell will exit.
Short form:
set -u
Long form:
set -o nounset
Parameter expansion can be used to test for unset variables when using set -o nounset
.
http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion
The two approaches that are probably the most appropriate are:
${parameter:-word}
If parameter is unset or null, the expansion of word is substituted.
Otherwise, the value of parameter is substituted. In other words, "word"
acts as a default value when the value of "$parameter" is blank. If "word"
is not present, then the default is blank (essentially an empty string).
${parameter:?word}
If parameter is null or unset, the expansion of word (or a message to that
effect if word is not present) is written to the standard error and the
shell, if it is not interactive, exits. Otherwise, the value of parameter
is substituted.
Arrays:
${some_array[@]:-} # blank default value
${some_array[*]:-} # blank default value
${some_array[0]:-} # blank default value
${some_array[0]:-default_value} # default value: the string 'default_value'
Positional variables:
${1:-alternative} # default value: the string 'alternative'
${2:-} # blank default value
With an error message:
${1:?'error message'} # exit with 'error message' if variable is unbound
set -o errexit
/ set -e
Exit immediately if a pipeline returns non-zero.
Short form:
set -e
Long form:
set -o errexit
set -o errexit
with read -rd ''
set -o errexit
is super useful for avoiding scary errors, but there are somethings to watch out for. When using read -rd ''
with a heredoc, theexit status is non-zero, even though there isn't an error, and thissetting then causes the script to exit. read -rd ''
is equivalentto read -d $'\0'
, which means read until it finds a NUL byte, butit reaches the end of the heredoc without finding one and exits witha 1
status. Therefore, when reading from heredocs with set -e
,there are three potential solutions:
Solution 1. set +e
/ set -e
again:
set +e
read -rd '' variable <<HEREDOC
Example text.
HEREDOC
set -e
Solution 2. <<HEREDOC || true
:
read -rd '' variable <<HEREDOC || true
Example text.
HEREDOC
Solution 3. Don't use set -e
or set -o errexit
at all.
More information:
'builtin "read -d" behaves differently after "set -e"' (lists.gnu.org)
set -o pipefail
Return value of a pipeline is the value of the last (rightmost) command toexit with a non-zero status, or zero if all commands in the pipeline exitsuccessfully.
Long form (no short form available):
set -o pipefail
$IFS
Set IFS to just newline and tab.
IFS=$'\n\t'
For some background, seeFilenames and Pathnames in Shell: How to do it Correctly (dwheeler.com)
Explicitness and clarity are generally preferable, especially since bash canbe difficult to read. This leads to noisier, longer code, but should beeasier to maintain. As a result, some general design preferences:
local
, such as those defined outside of a function orautomatically through a for
loop, prefix with double underscores.${NAME}
insteadof $NAME
. Braces are only required for variable references in some cases,but the cognitive overhead involved in keeping track of which cases requirebraces can be reduced by simply always using them.printf
over echo
. For more information, see:http://unix.stackexchange.com/a/65819$_explicit_variable_name
over names like $var
.#!/usr/bin/env bash
shebang in order to run the preferredBash version rather than hard-coding a bash
executable path.Scripts based on this project.
Copyright (c) 2015 William Melody • hi@williammelody.com
我在bash中开发了一个几乎完美无缺的try&catch实现,允许你编写如下代码: try echo 'Hello' false echo 'This will not be displayed' catch echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!" 你甚至可以将try-catch块嵌入其中! try {
对于某些调试或演示需求,它确实可能有用。 我发现Bob Copeland的解决方案http://bobcopeland.com/blog/2012/10/goto-in-bash/优雅: #!/bin/bash # include this boilerplate function jumpto { label=$1 cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0
我试图在 Windows 10 Bash shell上安装matplotlib. 之后,我运行了以下几行: $ipython3 然后 In[1]: %pylab 然后它给了我一个跟随错误: --------------------------------------------------------------------------- TclError Traceback (most rece
好了,现在我们换了一个遥控器,感觉顺手多了。现在来操练一下,下载一首 mp3: 我们使用 wget 这个程序,它非常可靠,完全值得您信赖。 首先找到一个可以下载的地址,复制链接,在终端窗口内点击鼠标中键,把它粘贴进去。 现在终端中大概是这种情形: http://linuxtoy.org/xxx.mp3 按下 Ctrl+a 组合键,我们发现光标移动到了行首。输入 wget 和 空格 wget ht
语法 基本语法 名称 语法 描述 示例 interpreter #!/bin/bash Bash shell 脚本的第一行以 #! 开头,通常也称为 sharp-bang 或缩写版本 sha-bang。后面的路径名称是命令解释器,也就是应该用于执行脚本的程序。 echo echo "arbitrary text" echo "arbitrary text" >&2 文本定向到标准输出 (STDOU
bash 是一个为GNU项目编写的Unix shell。它的名字是一系列缩写:Bourne-Again SHell — 这是关于Bourne shell(sh)的一个双关语(Bourne again / born again)。Bourne shell是一个早期的重要shell,由Stephen Bourne在1978年前后编写,并同Version 7 Unix一起发布。bash则在1987年由B
Bash++ 是一个将 bash 提升到一个新水平的框架,为 bash 引入了新功能。它的设计是为了让人们能够建立更复杂的应用程序,创造更好的产品。 请注意,这个项目是为有 bash 经验的人准备的(不多,只是简单的理解和事情通常如何运作)。 运行示例 (确保你已经安装bash++) cd 进入示例目录。 对你想运行的脚本进行chmod。 chmod +x [SCRIPT.sh] 运行该脚本 ./[SCRIPT].sh
Bash-it 是一款针对bash使用进行优化的软件,提供了终端显示的主题优化、命令补全、命令别名、插件、版本控制目录状态实时显示等实用功能,能让bash更好用!正如软件readme说的那样,本款软件是模仿 http://www.oschina.net/p/oh-my-zsh 的,只不过是使用在bash环境中。 安装本软件需要有bash(这个大多数类Unix系统都具备)、git(如果下载zip包也
Bash-Snippets 这个项目完全是为重度终端用户而生的,里面包含了大量的 Bash 脚本,而且无需任何依赖。 示例: Crypt 封装了 openssl,可用于快速加密和解密文件 crypt -e [original file] [encrypted file] # encrypts filescrypt -d [encrypted file] [output file] # decryp