xargs command

xargs 命令应该紧跟在管道操作符之后。它使用标准输入作为主要的数据源,将从 stdin 中读取的数据作为指定命令的参数并执行该命令。

例如:
在一组 C 语言源码文件中搜索自负串main:
ls *.c | sargs grep main

Example 1: 将多行输入 –> 单行输出

1
2
3
4
5
6
7
➜   cat example.txt
1 2 3 4
5 6
7 8 9
10 11
➜ cat example.txt | xargs
1 2 3 4 5 6 7 8 9 10 11

Example 2: 将单行输入 –> 多行输出

xargs 的 -n 选项可以限制每次调用命令时用到的参数个数。

1
2
3
4
5
➜   cat example.txt | xargs -n  3
1 2 3
4 5 6
7 8 9
10 11

工作原理:
xargs 命令接收来自stdin的输入,将数据解析成单个元素,然后调用指定命令讲这些元素作为该命令的参数。xargs 默认使用 空白字符 分割输入并执行 /bin/echo

Example 3: 自定义分隔符 -d 选项

1
2
echo "splitXsplit1Xsplit2Xsplit3" | xargs -d X
split split1 split2 split3

Example 4: 结合find使用xargs

find . -type f -name "*.txt" -print0 | xargs -o grep -L image

如果文件系统的有些文件名中包含忠哥,find 命令的 -print0 选项可以使用0(NUL)来分割查找到的元素,然后再用xargs对应的-0选项进行解析

反例:
$find . -type f -name "*.txt" -print | xargs rm -f
这样做很危险,由可能会误删除文件。我们无法预测 find命令输出的分隔符究竟是什么(究竟是‘\n’还是 ‘’)。如果由文件名中包含空格符(‘ ’ ),xargs会将其误认为是分隔符。例如, bashrc text.txt 会被是为 bashrc 和 text.txt 。因此上面的命令不会删除 bashrc text.txt ,而是会把 bashrc删除

正确的姿势:
$find . -type f -name "*.txt" -print0 | xargs -0 rm -f

注意事项

docker ps -a -q | xargs --no-run-if-empty docker rm -f

参数 --no-run-if-empty 可以避免在前面的命令完全没有输出的情况下执行该命令

http vs curl

http不仅是个协议,还是一个命令。

Httpie 是个 HTTP 的命令行客户端,http就是它的命令。

1. Httpie 是什么

Httpie (aych-tee-tee-pie)是一个 HTTP 的命令行客户端。其目标是让 CLI 和 web 服务之间的交互尽可能的人性化。你可以用它很方便的用 http 的命令调试接口,最常用的应该就是 GET 和 POST 了。

2. 安装

Linux上安装

  • Debian, Ubuntu或Linux Mint
    sudo apt-get install httpie

  • Fedora,CentOS/RHEL
    sudo yum install httpie

或者使用python的方式来安装
sudo pip install --upgrade httpie

  • Mac OSX
    brew install httpie

3. http command 能做什么

curl能做的,大部分都能做。

HTTPie 基于 python 编写,内部使用了 Requests 和 Pygments 库。

HTTPie 的用法要比 cURL 直观很多,没有那么多选项,基本上心里怎么想就怎么写,默认输入和输出都是 json 格式 (而 cURL 必须要指定 -H “Content-Type: application/json”)。我们同样实现上面获取 token 的功能,效果如下:

  • example 1:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    ➜  tmp http https://www.devops-tech.cn/
    HTTP/1.1 200 OK
    Accept-Ranges: bytes
    Access-Control-Allow-Origin: *
    Age: 7
    Cache-Control: max-age=600
    Connection: keep-alive
    Content-Encoding: gzip
    Content-Length: 2510
    Content-Type: text/html; charset=utf-8
    Date: Wed, 19 Jun 2019 08:28:44 GMT
    ETag: W/"5d0848b1-2d66"
    ...

others

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
http

HTTPie: HTTP client, a user-friendly cURL replacement.

- Download a URL to a file:
http -d example.org

- Send form-encoded data:
http -f example.org name='bob' profile_picture@'bob.png'

- Send JSON object:
http example.org name='bob'

- Specify an HTTP method:
http HEAD example.org

- Include an extra header:
http example.org X-MyHeader:123

- Pass a user name and password for server authentication:
http -a username:password example.org

- Specify raw request body via stdin:
cat data.txt | http PUT example.org

4. 特点:

1、直观的语法
2、格式化和色彩化的终端输出
3、内置 JSON 支持
4、支持上传表单和文件
5、HTTPS、代理和认证支持
6、支持任意请求数据
7、自定义标题
8、持久性会话
9、类 Wget 下载
10、支持 Python 2.6, 2.7 和 3.x
11、支持 Linux, Mac OS X 和 Windows
12、插件
13、文档
14、测试覆盖率

Bash function skill

bash 函数技巧

1. 递归函数

2.导出函数

函数也可以像环境变量一样用 export 导出

1
2
3
4
5
6
7
8
foo() {echo "This is foo function"}
export -f foo
foo () {
echo "This is foo function"
}
➜ foo
This is foo function

3. 读取命令返回值

命令的返回值被保存在变量 $?
返回值被称为 退出状态 。它可用于确定命令执行成功与否。如果命令成功退出,那么退出状态为0,否则为非0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
➜   cat success_test.sh 
#!/bin/bash
#file name: success_test.sh
#对命令行参数求值,比如 success_test.sh `ls | grep txt`
echo "parameter is :"$@

eval $@

if [ $? -eq 0 ];
then
echo "$CMD executed successfully."
else
echo "$CMD terminated unsuccessfully."
fi

执行:

1
2
3
4
5
➜   success_test.sh 'ls'
parameter is :ls
certbot-auto t1 t3 test.sh
success_test.sh t2 test.jsonnet
executed successfully.

4. 向命令传递参数

1
2
3
4
5
6
7
8
➜   cat showArgs.sh
#!/bin/bash

for i in `seq 1 $#`
do
echo $i is $1
shift
done

执行:

1
2
3
4
➜   showArgs.sh a b cc
1 is a
2 is b
3 is cc

Shell count time

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash

start=$(date +%s)

echo ---------
#type your command, like: sleep 50
sleep 50

end=$(date +%s)

diff=$((end - start))

echo -e "\e[1;32m take time is: $diff \e[m"
1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
echo Count:
tput sc


for count in `seq 0 40`
do
tput rc
tput ed
echo -n $count
sleep 1
done

用 tput sc 存储光标位置。在每次循环中,通过 tput rc 恢复之前的存储的光标位置,在终端中打印出新的 count 值,然后使用 tputs ed 清除从当前位置到行尾之间的所有内容。行被清空之后,脚本就可以显示出新的值。sleep 可以使脚本在每次循环迭代之间延迟1秒钟。

Shell Print text between specified lines or patterns

awk,grep,sed,head,tail 都可以根据条件打印部分行。最简单的方法是使用 grep 打印匹配模式的行。不过,最全能的工具还是 awk.

Example 1: 打印从 M 行到 N 行之间的文本

$ awk 'NR==M,NR==N' filename

也可以从stdin读取输入:
cat filename | awk 'NR==M, NR==N'

Example 2: 打印位于模式 start_pattern 与 end_pattern 之间的文本

awk '/start_pattern/,/end_pattern/' filename

awk中使用的模式为正则表达式

Jenkins trigger downstream job

origin_job 触发 second_job

origin_job 如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//declarative pipeline
pipeline {
agent any

stages {
stage('Stage One'){
steps{
sh "echo *** This is Stage One ***"
}
}

stage('Stage Two'){
steps{
sh "echo ${env.BUILD_NUMBER}"
sh "echo ${env.NODE_NAME} , ${env.JOB_NAME}"
}
}

stage("Invoke second job without parameters"){
steps{
build job: 'second_job'
sleep 30
}
}

stage("Invoke second job with parameters"){
steps{
build job: 'second_job',
parameters:[
string(name:'Para1',value:String.valueOf(JOB_NAME)),
string(name:'Para2',value:String.valueOf(BUILD_NUMBER))
]
}
}

}
}

second_job

点击““参数化构建””手动添加 两个参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
pipeline {
agent any

stages {
stage('Stage One'){
steps{
sh "echo *** This is ${env.JOB_NAME} ,and We are stage one ***"
}
}

stage('Echo origin_job para'){
steps{
sh "echo ${env.Para1}"
sh "echo ${env.Para2}"
}
}
}
}

Shell Script Standards

推荐看看 https://google.github.io/styleguide/shellguide.html

Part1: 命名约定
  • 本文档的命名约定是系统配置文件、脚本文件;
  • 文件名、变量名、函数名不超过20个字符;
  • 命名只能使用英文字母,数字和下划线,只有一个英文单词时使用全拼,有多个单词时,使用下划线分隔,长度较长时,可以取单词前3~4个字母。
  • 文件名全部以小写命名,不能大小写混用(通过U盘交换文件时,大小写可能会丢失,即:大写文件名可能会全部变成小写文件名);
  • 避免使用Linux的保留字如true、关键字如PWD等(见附表);
  • 从配置文件导出配置时,要注意过滤空行和注释
Part2: 代码开头约定
  • 第一行一般为调用使用的语言
  • 下面要有这个程序名,避免更改文件名为无法找到正确的文件
  • 版本号
  • 更改后的时间
  • 作者相关信息
  • 该程序的作用,及注意事项
  • 版权与是否开放共享GNU说明
  • 最后是各版本的更新简要说明

e.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/bin/bash
# -------------------------------------------------------------------------------
# Filename: check_mem.sh
# Revision: 1.1
# Date: 2019/02/10
# Author: xiaoming
# Email: xiaoming#gmail.com
# Description: Plugin to monitor the memory of the system
# Notes: This plugin uses the "" command
# -------------------------------------------------------------------------------
# Copyright: 2009 (c) xiaoming
# License: GPL
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# you should have received a copy of the GNU General Public License
# along with this program (or with Nagios);
#
# Credits go to Ethan Galstad for coding Nagios
# If any changes are made to this script, please mail me a copy of the changes
# -------------------------------------------------------------------------------
#Version 1.0
#The first one , can monitor the system memory
#Version 1.1
#Modify the method of the script ,more fast

Part3: 环境变量
  • 变量:全部是大写字母
  • 变量引用:全部以变量名加双引号引用,如”$TERMTYPE”,或“${TERMTYPE}”,如果变量类型是数值型不引用,如:
  • 如果需要从配置文件导出变量,则在变量前加一大写字母,以识别导出变量与自定义环境变量的区别,如:
  • 变量值的引用尽量以$开头,如$(ls inst_.sh),避免使用ls inst_。sh
  • 循环控制变量可以命名为单个字母, 比如 i、j等。 也可以是更有意义的名称, 比如 UserIndex。
  • 环境变量和全局变量 在脚本开头定义。
  • 函数中使用较多的文件,以环境变量的形式在文件开头定义,仅函数中使用的变量在函数开头定义
Part4: 脚本的基本结构

一个脚本的基本结构是这样的:

1
2
3
4
5
6
7
8
#!SHEBANG

CONFIGURATION_VARIABLES

FUNCTION_DEFINITIONS

MAIN_CODE
Shebang

More Ref:

Ping Or fping

ping 命令我们比较常用,但是这里要介绍下 fping 命令。 fping 比 ping 拥有更多的特性。fping 默认没有包含在Linux发行版中。

ping 命令使用Internet控制协议(Internet Control Message Protocol,ICMP)中的echo 分组检验网络上两台主机之间的连通性。

e.g.

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash

for ip in 192.168.0.{1..255} ;
do
ping $ip -c 2 &> /dev/null ;

uf [ $? -eq 0 ];
then
echo $ip is alive
fi
done

工作原理:

  • &> /dev/null 用于将 stderr stdout 重定向到 /dev/nul ,使终端不会出现任何输出
  • 脚本用 $? 获取退出状态。如果顺利退出,退出状态为0,否则为非0值。
fping

fping 可以为多个IP地址生成 ICMP 分组,然后等待回应。其运行速度要比上面的脚本快得多。

选项如下:

  • 选项 -a 指定显示出所有活动主机的IP地址;
  • 选项 -u 指定显示出所有不可达的主机地址;
  • 选项 -g 指定从 “IP地址/子网掩码;记法或者 “IP地址范围”记法中生成一组地址

e.g.

fping -a 192.168.0.1/24 -g

fping -a 192.168.0.1 192.168.1.255 -g

fping -a 192.168.0.1 192.168.0.5 192.168.0.6

fping -a < ip.list 从列表文件 sdtin 中接收

Small Tools [2]: ffmpeg -- Video conversion tool.

yffmpeg

1.Install (安装)
  • macOS (wait a min)
    1
    brew install ffmpeg
2.Usage (用法)
  • General usage
1
ffmpeg -i video.mp4 -vn sound.mp3
  • More usage
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    ffmpeg

    Video conversion tool.

    - Extract the sound from a video and save it as MP3:
    ffmpeg -i video.mp4 -vn sound.mp3

    - Convert frames from a video or GIF into individual numbered images:
    ffmpeg -i video.mpg|video.gif frame_%d.png

    - Combine numbered images (frame_1.jpg, frame_2.jpg, etc) into a video or GIF:
    ffmpeg -i frame_%d.jpg -f image2 video.mpg|video.gif

    - Quickly extract a single frame from a video at time mm:ss and save it as a 128x128 resolution image:
    ffmpeg -ss mm:ss -i video.mp4 -frames 1 -s 128x128 -f image2 image.png

    - Trim a video from a given start time mm:ss to an end time mm2:ss2 (omit the -to flag to trim till the end):
    ffmpeg -ss mm:ss -to mm2:ss2 -i video.mp4 -codec copy output.mp4

More Ref:- https://ffmpeg.org (官网)

Small Tools [1]: youtube-dl

youtube-dl

youtube-dl 是一个命令行视频下载利器,不仅仅可以下载YouTube的内容,也可以下载其他的视频网站内容

1.Install (安装)

mac 或 linux 上

1
2
sudo curl -L https://yt-dl.org/downloads/latest/youtube-dl -o /usr/local/bin/youtube-dl
sudo chmod a+rx /usr/local/bin/youtube-dl

2.Usage (用法)
  • General usage

    1
    2
    3
    4
    5
    6
    7
    8
    ➜  ~ youtube-dl https://www.youtube.com/watch\?v\=rNh_e6ZA8CI
    [youtube] rNh_e6ZA8CI: Downloading webpage
    [youtube] rNh_e6ZA8CI: Downloading video info webpage
    [download] Destination: 采用最慢起跑方式! 中国飞人起跑不好只排第四, 但后程爆发以0.03秒险胜夺冠-rNh_e6ZA8CI.mp4
    [download] 100% of 13.00MiB in 00:43

    ### 下载到指定目录,并重命名
    youtube-dl https://www.youtube.com/watch\?v\=rNh_e6ZA8CI -o ./youtube-download/running_vedio.mp4
  • Only Download Audio (下载youtube的音频)

(最近发现youtube有些节目,只用听得,比如 读书类、英语类),用-f 参数指定格式

youtube-dl -f 140 https://www.youtube.com/watch\?v\=9rRrsx1jgYc

1
2
youtube-dl -F <your_link>
### -F, --list-formats List all available formats of requested videos


新增一个类似工具

最近发现新的工具 you-get
对国内支持比较好,国内视频下载速度极快(比youtube-dl快很多倍),使用方便,语法简单。

比如:

1
2
3
4
# 下载网易云音乐的mv
you-get https://music.163.com/\#/mv\?id\=5307835
# 然后提取音频
ffmpeg -i 祝你一路顺风\ -\ 吴奇隆.mp4 -vn 祝你一路顺风\ -\ 吴奇隆.mp3

再新增一个类似工具

https://github.com/nilaoda/BBDown

我用这个下载过英文字幕,好用!

下载:对于Mac,直接去下载https://github.com/nilaoda/BBDown/releases osx版本的.

解压后,chmod 加权限;右键打开时会提示”Are you sure you want to open it?”,选择 “Open”; 然后便可命令行使用

使用: e.g. ./BBDown --sub-only https://www.bilibili.com/video/BV1S64y1i7m6

More Ref:

  • Copyrights © 2019-2024 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~