bash-commons

授权协议 Apache-2.0 License
开发语言 SHELL
所属分类 应用工具、 终端/远程登录
软件类型 开源软件
地区 不详
投 递 者 邢寒
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Bash Commons

This repo contains a collection of reusable Bash functions for handling common tasks such as logging, assertions,string manipulation, and more. It is our attempt to bring a little more sanity, predictability, and coding reuse to ourBash scripts. All the code has thorough automated tests and is packaged into functions, so you can safely import itinto your bash scripts using source.

Examples

Once you have bash-commons installed (see the install instructions), you use source to import themodules and start calling the functions within them. Before you import any modules, make sure you source thebootstrap.sh file which sets some important defaults to encourage good code:

source /opt/gruntwork/bash-commons/bootstrap.sh
source /opt/gruntwork/bash-commons/log.sh
source /opt/gruntwork/bash-commons/assert.sh
source /opt/gruntwork/bash-commons/os.sh

log_info "Hello, World!"

assert_not_empty "--foo" "$foo" "You must provide a value for the --foo parameter."

if os_is_ubuntu "16.04"; then
  log_info "This script is running on Ubuntu 16.04!"
elif os_is_centos; then
  log_info "This script is running on CentOS!"
fi

Install

The first step is to download the code onto your computer.

The easiest way to do this is with the Gruntwork Installer(note, you'll need to replace <VERSION> below with a version number from the releasespage):

gruntwork-install \
  --repo https://github.com/gruntwork-io/bash-commons \
  --module-name bash-commons \
  --tag <VERSION>

The default install location is /opt/gruntwork/bash-commons, but you can override that using the dir param, andoverride the owner of the install dir using the owner and group params:

gruntwork-install \
  --repo https://github.com/gruntwork-io/bash-commons \
  --module-name bash-commons \
  --tag <VERSION> \
  --module-param dir=/foo/bar \
  --module-param owner=my-os-username \
  --module-param group=my-os-group

If you don't want to use the Gruntwork Installer, you can use git clone to get the code onto your computer and thencopy it to it's final destination manually:

git clone --branch <VERSION> https://github.com/gruntwork-io/bash-commons.git

sudo mkdir -p /opt/gruntwork
cp -r bash-commons/modules/bash-commons/src /opt/gruntwork/bash-commons
sudo chown -R "my-os-username:my-os-group" /opt/gruntwork/bash-commons

Instance Metadata Service versions

bash-commons supports both Instance Metadata Service (IMDS) version 1 and 2. Gruntwork and AWS both recommend using version 2 of the Instance Metadata Service whenever possible. Although version 1 is still supported and considered fully secure by AWS, version 2 has been specially hardened against specific threat vectors and is therefore preferable.

To understand more about Instance Metadata Service version 2 and its features, read the official AWS documentation on IMDSv2.

There are two ways to specify the version of the Instance Metadata Service that bash-commons should use:

  1. Set the environment variable GRUNTWORK_BASH_COMMONS_IMDS_VERSION to the version of IMDS that you wish to use. Valid values are either 1 or 2.
  2. Change the value of default_instance_metadata_version to either 1 or 2.

Example of dynamic-ubuntu-wait.sh usage:

You can use the dynamic-ubuntu-wait.sh command after you install bash-commons:

bash /opt/gruntwork/bash-commons/dynamic-ubuntu-wait.sh

Alternatively, you can call the script without installing by curling it during your existing provisioning/automated installation process:

curl -LsS https://raw.githubusercontent.com/gruntwork-io/bash-commons/[VERSION]/modules/bash-commons/src/dynamic-ubuntu-wait.sh | bash`

Where [VERSION] could be: v0.0.3. The latest release can be found here

Importing modules

You can use the source command to "import" the modules you need and use them in your code:

source /opt/gruntwork/bash-commons/log.sh

This will make all the functions within that module available in your code:

log_info "Hello, World!"

Available modules

Here's an overview of the modules available in bash-commons:

  • array.sh: Helpers for working with Bash arrays, such as checking if an array contains an element, or joining anarray into a string with a delimiter between elements.

  • assert.sh: Assertions that check a condition and exit if the condition is not met, such as asserting a variable isnot empty or that an expected app is installed. Useful for defensive programming.

  • aws.sh: A collection of thin wrappers for direct calls to the AWS CLI and EC2Instance Metadata. These thinwrappers give you a shorthand way to fetch certain information (e.g., information about an EC2 Instance, such as itsprivate IP, public IP, Instance ID, and region). Moreover, you can swap out aws.sh with a version that returns mockdata to make it easy to run your code locally (e.g., in Docker) and to run unit tests.

  • aws-wrapper.sh: A collection of "high level" wrappers for the AWS CLI and EC2Instance Metadata to simplify commontasks such as looking up tags or IPs for EC2 Instances. Note that these wrappers handle all the data processing andlogic, whereas all the direct calls to the AWS CLI and EC2 metadata endpoints are delegated to aws.sh to make unittesting easier.

  • dynamic-ubuntu-wait.sh: A script that dynamically waits for Ubuntu automatic update mechanism torelease all locks so that apt-get may run without errors.

  • file.sh: A collection of helpers for working with files, such as checking if a file exists or contains certain text.

  • log.sh: A collection of logging helpers that write logs to stderr with log levels (INFO, WARN, ERROR) andtimestamps.

  • os.sh: A collection of Operating System helpers, such as checking which flavor of Linux (e.g., Ubuntu, CentOS) isrunning and validating checksums.

  • string.sh: A collection of string manipulation functions, such as checking if a string contains specific text,stripping prefixes, and stripping suffixes.

Coding principles

The code in bash-commons follows the following principles:

  1. Compatibility
  2. Code style
  3. Everything is a function
  4. Namespacing
  5. Testing

Compatibility

The code in this repo aims to be compatible with:

  • Bash 3
  • Most major Linux distributions (e.g., Ubuntu, CentOS)

Code style

All the code should mainly follow the Google Shell Style Guide.In particular:

  • The first line of every script should be #!/usr/bin/env bash.
  • All code should be defined in functions.
  • Functions should exit or return 0 on success and non-zero on error.
  • Functions should return output by writing it to stdout.
  • Functions should log to stderr.
  • All variables should be local. No global variables are allowed at all.
  • Make as many variables readonly as possible.
  • If a variable is both local and readonly, use local -r.
  • If calling to a subshell and storing the output in a variable (foo=$( ... )), do NOT use local -r in the samestatement or the exit code will be lost.Instead, declare the variable as local on one line and then call the subshell on the next line.
  • Quote all strings.
  • Use [[ ... ]] instead of [ ... ].
  • Use snake_case for function and variable names. Use UPPER_SNAKE_CASE for constants.

Everything in a function

It's essential that ALL code is defined in a function. That allows you to use source to "import" that code withoutanything actually being executed.

Namespacing

Bash does not support namespacing, so we fake it using a convention on the function names: if you create a file<foo.sh>, all functions in it should start with foo_. For example, all the functions in log.sh start with log_(log_info, log_error) and all the functions in string.sh start with string_ (string_contains,string_strip_prefix). That makes it easier to tell which functions came from which modules.

For readability, that means you should typically give files a name that is a singular noun. For example, log.shinstead of logging.sh and string.sh instead of strings.sh.

Testing

Every function should be tested:

  • Automated tests are in the test folder.

  • We use Bats as our unit test framework for Bash code. Note: Bats has not beenmaintained the last couple years, so we may need to change to the bats-corefork at some point (see #150).

  • We run all tests in the gruntwork/bash-commons-circleci-tests Dockerimage so that (a) it's consistent with how the CIserver runs them, (b) the tests always run on Linux, (c) any changes the tests make, such as writing files orcreating OS users, won't affect the host OS, (d) we can replace some of the modules, such as aws.sh, with mocks attest time. There is a docker-compose.yml file in the test folder to make it easy to run the tests.

  • To run all the tests: docker-compose up.

  • To run one test file: docker-compose run tests bats test/array.bats.

  • To leave the Docker container running so you can debug, explore, and interactively run bats: docker-compose run tests bash.

  • If you ever need to build a new Docker image, the Dockerfile is in the .circleci folder:

    cd .circleci
    docker build -t gruntwork/bash-commons-circleci-tests .
    docker push gruntwork/bash-commons-circleci-tests

TODO

  1. Add automated tests for aws.sh and aws-wrapper.sh. We have not tested these as they require either running anEC2 Instance or run something like LocalStack.

License

This code is released under the Apache 2.0 License. Please seeLICENSE andNOTICE for more details.

Copyright © 2018 Gruntwork, Inc.

  • 1.commons-lang3 <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> 1.1 StringUtils 1.判断是否为空 null/“”/" " St

  • 在使用了百度开放接口的一段代码后,出现了如题所示的问题,Android包冲突了,这里有两个解决方式: 1.一般情况下,我们在AndroidStudio中的左侧的工程树中,找到external library,然后将其中一个冲突的jar包删除即可。 2.如果以上方式无法解决,我的情况就是如此,删除以后,每次编译,还是会自动下载下来,那么就使用第二种方式: 在build.gradle文件中加入排除语句

  • CommonCollection Gadget主要是由ConstantTransformer,InvokerTransformer,ChainedTransformer构成。gadget主要通过Transformer接口的transform方法,对输入的对象做变换。 ConstantTransformer不会做任何变换,只会返回类在实例化时传入的对象, InvokerTransformer会对类在

  • 在其他用户下,报错,于是在root用户下进行修改权限 chmod 777 / 看一下: total 98 dr-xr-xr-x. 2 root root 4096 May 1 08:07 bin dr-xr-xr-x. 5 root root 1024 May 1 05:31 boot drwxr-xr-x. 19 root root 3800 May 1 05:46 de

  • 我无法通过SSH从 Java在远程GNU / Linux系统上执行命令.在本地Bash中执行时,以下命令可以正常工作(当然用户和主机不同但行为不变). $ssh user@host.example.com 'hostname' host $ssh user@host.example.com 'hostname -f' host.example.com $ssh user@host.example.

 相关资料
  • 好了,现在我们换了一个遥控器,感觉顺手多了。现在来操练一下,下载一首 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