6

不可避免的shell scripting

 3 years ago
source link: https://zhuanlan.zhihu.com/p/343072379
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

不可避免的shell scripting

一个人NB的不是标签

In the simplest case, a script is nothing more than a list of system commands stored in a file. At the very least, this saves the effort of retyping that particular sequence of commands each time it is invoked.

shell 脚本的学习,主要是通过写来学会,但是它跟常见的编程语言有相同的地方:比如条件判断,循环,比较大小等等。掌握这些基本知识点,你就可以写shell脚本了!

很多时候你也可以用python, ruby, nodejs 来写脚本,参见Python一节。但shell script还是要学一学,因为你得看懂别人写的shell script。


if 条件
then
  echo "条件为真"
else
  echo "条件为假"
fi

去掉\n,为

if [ 3 > 2 ]; then echo "true"; else echo "false"; fi

While循环

while 条件
do
  echo "doing while"
done

获取命令行输出

获取gcc 的版本号

gcc_version=$(gcc --version | grep ^gcc | awk '{print $3}')
echo $gcc_version

从上面的例子,可以看到variable=value。注意等号两边没有空格!因为空格在shell里面是用于分隔的,有意义。

条件主要用于判断某个情况为真或者为假,然后做相应的处理。它们经常放于[]内,注意要与括号有空格,比如

if [ 4 > 3]

常见的条件判断

[ -d folder-path ] 文件夹是否 存在

[ -f file-path] 文件是否存在

[[ "4.8.3" < "8.3.0" ]] 字符串比较,注意一共有两个[]

读取用户输入并存到变量中

read -p 'please input your name: ' your_name
echo $your_name
read -sp 'please input your password: ' password
echo $password
  1. command1 && command2
# command2 只有在command1执行成功的时候才会执行,比如 
mkdir name && echo "name folder create"

2. #!/bin/env bash

叫做sha-bang,至于脚本第一行,用于指定应该有什么程序来运行当前的脚本,如果直接运行的时候。

function pr() {
echo $1 #函数的第一个参数
echo $2 #函数的第二个参数
}
pr good morning

双引号和单引号

双引号变量会被替换,而单引号不会,如

var="good"
p="$var morning"
echo $p # good morning
pp='$var morning'
echo $pp # $var morning

特殊的符号

https://tldp.org/LDP/abs/html/special-chars.html


Python的插足

记得在我毕业找工作的时候,面试官问我如何用shell统计代码有多少行,我说我选择用Python来做,毕竟那会我shell script用不熟。

实际上,大部分shell script可以做的活,Python都可以干。复杂一点的还是Python更好。仅仅有些时候shell script更方便,比如container里面一般没有Python安装。

如果用Python,以下是常用的替换结构

运行命令并获取命令的输出

out = subprocess.check_output(['ls', '-l'])

References:

Shell Programming!

https://stackoverflow.com/questions/4760215/running-shell-command-and-capturing-the-output

How to implement common bash idioms in Python?

https://medium.com/capital-one-tech/bashing-the-bash-replacing-shell-scripts-with-python-d8d201bc0989

https://germaniumhq.com/2019/03/13/2019-03-13-Replacing-Shell-Scripts-With-Python/

ninjaaron/replacing-bash-scripting-with-python

How do I tell if a regular file does not exist in Bash?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK