【Linux】深入理解Shell用法,从入门到精通

相关文章

一.Shell背景

1.1 GNU计划

Tips:
The GNU Project is a free software, mass collaboration project that Richard Stallman announced on September 27, 1983. Its goal is to give computer users freedom and control in their use of their computers and computing devices by collaboratively developing and publishing software that gives everyone the rights to freely run the software, copy and distribute it, study it, and modify it. GNU software grants these rights in its license.

1984年,史托曼开始GNU计划, 这个计划的目的是:创建一个自由、开放的Unix操作系统 (Free Unix)。

Tips:
GNU’s not Unix!
GNU并不是 Unix啊!那么GNU又是什么呢? 就是GNU’s Not Unix嘛!..可是无穷循环啊!忙碌~

本章所说的Bash Shell就是来源于GNU,还有一些比较著名的软件来源于GNU:

  • Emacs
  • GNU C (GCC)
  • GNU C Library (glibc)
  • Bash shell

Tips:
In 1991, the Linux kernel appeared, developed outside the GNU project by Linus Torvalds, and in December 1992 it was made available under version 2 of the GNU General Public License. Combined with the operating system utilities already developed by the GNU project, it allowed for the first operating system that was free software, commonly known as Linux.

1.2 Shell

在这里插入图片描述

Important:
我们必须要通过“ Shell ”将我们输入的指令与 Kernel 沟通, 好让 Kernel 可以控制硬件来正确无误的工作。

我们可以发现应用程序其实是在最外层,如同鸡蛋外壳一样,因此就被称呼为壳程序 (shell) 啰!

注意:
只要能够操作应用程序的接口都能够称为壳程序。

  • 狭义:命令行方面的软件,bash 等。
  • 广义:图形接口的软件!因为图形接口其实也能够操作各种应用程序来调用核心工作啊!

Shell有很多版本例如常听到的Bourne SHell (sh) 、在 Sun 里头默认的 C SHell,还有 TCSH,zsh 等等,每一种 Shell 都各有其特点。Bash Shell是Bourne Shell 的增强版本,也是基准于 GNU 的架构下发展出来的!

在你的Mac电脑中有多少可使用的Shells呢,使用如下命令查看:

MacBook-Pro-3:~ sunquan$ cat -n /etc/shells
     1	# List of acceptable shells for chpass(1).
     2	# Ftpd will not allow users to connect who are not using
     3	# one of these shells.
     4	
     5	/bin/bash
     6	/bin/csh
     7	/bin/dash
     8	/bin/ksh
     9	/bin/sh
    10	/bin/tcsh
    11	/bin/zsh
MacBook-Pro-3:~ sunquan$ 

1.3 Bash

而当下日常大多数默认使用的是Bash Shell。我们可以在电脑中man bash一下

MacBook-Pro-3:~ sunquan$ man bash
BASH(1)                                                                BASH(1)

NAME
       bash - GNU Bourne-Again SHell

SYNOPSIS
       bash [options] [file]

COPYRIGHT
       Bash is Copyright (C) 1989-2005 by the Free Software Foundation, Inc.

DESCRIPTION
       Bash  is  an  sh-compatible  command language interpreter that executes
       commands read from the standard input or from a file.  Bash also incor-
       porates useful features from the Korn and C shells (ksh and csh).

       Bash  is  intended  to  be a conformant implementation of the Shell and
       Utilities portion  of  the  IEEE  POSIX  specification  (IEEE  Standard
       1003.1).  Bash can be configured to be POSIX-conformant by default.

Tips:
Bash is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell. First released in 1989, it has been used as the default login shell for most Linux distributions.

早在1989年就发布了Bash,被用来操作操作系统的基本接口。那Bash有哪些优点呢:

1.命令历史记录功能
用户可以在命令终端中通过上下箭头键来切换历史使用的命令,在~/.bash_history里记录了使用过的bash命令

MacBook-Pro-3:~ sunquan$ tail -n 10 ~/.bash_history 
vim awkDemo2
diff awkDemo awkDemo2
eixt (0) | echo $?
eixt (0) ; echo $?
eixt 0 ; echo $?
eixt 0;echo $?
var = sq ; echo var
var = sq ; echo $var
var=sq;echo $var
exit 0;echo $var

2.命令补全功能
通过Tab键可进行命令补全和文件补全

3.alase 别名设置

MacBook-Pro-3:~ sunquan$ ls -l
total 32
drwx------@  6 sunquan  staff   192  5 27  2020 Applications
...
MacBook-Pro-3:~ sunquan$ alias ll='ls -l'
MacBook-Pro-3:~ sunquan$ ll
total 32
drwx------@  6 sunquan  staff   192  5 27  2020 Applications
MacBook-Pro-3:~ sunquan$ 

4.程序化脚本: (shell scripts)
可通过写shell脚本,汇集命令构建更多的功能

二. Shell脚本基本语法

2.1 Getting Start

1. Introduction

shell script 是利用shell的功能所写的一个“程序 (program)”,这个程序是使用纯文本文件。也可被看成批处理文件或一个程序语言,且由于都是利用 shell 与相关工具指令,所以不需要编译即可执行。

2. Setting up Workspace

MacBook-Pro-3:~ sunquan$ vim ~/.bash_profile
export HISTFILESIZE=1024 #设置history记录bash命令的大小
export PATH=${PATH}:/Users/sunquan/Library/shell #shell工作空间
export PATH=${PATH}:/usr/local/bin
export PATH=$PATH:/Users/sunquan/Library/Android/android-ndk-r18b/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/bin/
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
source /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh
# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH
MacBook-Pro-3:~ sunquan$ source ~/.bash_profile

我自己的shell脚本存放在/Users/sunquan/Library/shell下,配置到系统的PATH里,当使用时脚本命令时,系统可自动在该目录下找到相关命令并执行。

3. Hello World

#! /bin/bash
# author: scott sun
# #!是一个约定的标记,告诉脚本用什么shell环境来执行
# a program to show "hello world" in your screen
# how to run : switch the dir
# chmod +x helloworld
# ./helloworld; if your add the scripts'dir in your PATH  variable, you can run helloworld directly
echo "Hello World"
exit 0

Important:
1. 第一行#!/bin/bash宣告这个script使用的shell名称,必须要包含。当这个程序运行的以后,就能够载入bash的相关环境配置文件
2.一个指令的执行结果可以使用$?这个变量来观察。因此exit 0 代表离开script后回传一个0给系统。随后如果下达echo $?则可得到0的值

4. Motivation Example

 #!/bin/bash
 #author : scott sun
 #function: use to count how much commands in your computer.
 IFS=":"
 count=0; nonex=0
 for directory in $PATH ; do
     if [ -d "$directory" ]
     then
         for command in "$directory"/* ; do
             if [ -x "$command" ]
             then
                 count=$[count + 1]
             else
                 nonex=$[nonex + 1]
             fi
         done
     fi
 done
 echo "$count commands, and $nonex that weren't executable"
 exit 0

MacBook-Pro-3:shell sunquan$ countShellCommands 
2438 commands, and 14 that weren't executable
MacBook-Pro-3:shell sunquan$
 

2.2 Variable

定义变量:

myname="sq"

Important:
1. 变量名不能有空格
2.英文字母,数字和下划线,不能使用bash关键字

使用变量

myname="sq"
echo $myname
echo ${myname}
echo "my name is ${myname}"

2.3 Data Type

#!/bin/bash
 vint=1
 vint2=2
 vfloat=1.1
 vString="sq"
 echo "int add int is $[ vint + vint2 ]"
 echo "int add float is $[ vint + vfloat ]"
 echo "int add string $[ vint + vString ]"

MacBook-Pro-3:shell sunquan$ variableDemo 
int add int is 3
/Users/sunquan/Library/shell/variableDemo: line 8: 1.1: syntax error: invalid arithmetic operator (error token is ".1")
int add string 1
MacBook-Pro-3:shell sunquan$

Important:
1. shell没有明确的关键字定义数据类型
2.相同类型的可相加,否则报错
3.整形和字符串不能相加

2.4 String

#!/bin/bash
 myname="scott.sun"
 echo "hello my name is $myname"
 echo 'hello, my name is $myname'
 echo "the length of $myname is ${#myname}"
 echo "substring(1,3) is ${myname:1:3}"
 echo "the first name is "; eval "echo $myname | cut -c1-5"

Important:
1. 单引号原样输出,双引号可显示变量
2. ${#string}输出字符串长度
3. ${string:start:end}截取字符串

2.5 Array

#!/bin/bash
 array=(
     1
     2
     3
     4
     5
     )
 echo $array
 echo ${array[0]}
 echo ${array[5]}
 echo "the length of arr is ${#array[*]}"
 echo "the content of array is ${array[*]}"
 echo "the content of array is ${array[@]}"

MacBook-Pro-3:shell sunquan$ arrayDemo 
1
1

the length of arr is 5
the content of array is 1 2 3 4 5
the content of array is 1 2 3 4 5

Important:
1. array定义如上
2. $array输出第一个元素,通过arr[index]获取数值,操作不输出
3. ${array[*]}, ${array[@]}功能雷同

2.6 Conditional Statements

1. if else

if [ -x "/path/filename" ]
then
    echo "this file can execute"
else
    echo "this file can't execute"
fi

2. switch case

#!/bin/bash
echo "input the num between 1-4"
read num
case $num in
	1) echo "the num is 1"
	;;
	2) echo "the num is 2"
	;;
	3) echo "the num is 3"
	;;
	4) echo "the num is 4"
	;;
	*) echo "the num is out of 1-4"
	;;
esac 

2.7 Looping

1. while

#!/bin/bash
cnt=1
while(( $cnt<=5 ))
do
	echo $cnt
	let "cnt++"
done

Tips:
1. let 用于执行一个或者多个表达式不需要$符号

2. for

#!/bin/bash
for loop in 1 2 3 4 5
do 
	echo "The value is $loop"
done

3. 无限循环

for (( ; ; ))

2.8 基本运算

#  	+	-	*	/	%
#	==	!=	-eq	-ne	-gt	-lt	-ge	-le	
#	!	-o -a (非或与)
#	-z 字符串长度是否为0
#	-n 字符串长度是否部位0
#	$ 字符串是否为空
echo $[ 1 + 2 ]
# -r -w -f -d -x -e
# 可读, 可写 普通文件	是否目录	是否可执行	是否存在
if [ -r $file ]
then
	echo "文件可读"
else
	echo "文件不可读"
fi

2.9 Function

 #!/bin/bash
 
 fun1(){
     echo "the name of command is $0"
     echo "the first params is $1"
     echo "the num of params is $#"
     echo "the str of params is $*"
 }
 fun1 1 2 3 4 str
 exit 0

MacBook-Pro-3:shell sunquan$ funcDemo 
the name of command is /Users/sunquan/Library/shell/funcDemo
the first params is 1
the num of params is 5
the str of params is 1 2 3 4 str

2.10 Import

#!/bin/bash 
# this is first script
. secondScriptName

三.Shell脚本实践

3.1 备忘录

#!/bin/bash
# file name: remember
# func : remember the note
rememberfile="$HOME/.remember_work"
if [ $# -eq 0 ] ; then
	echo "Enter note, end with ^D"
	cat - >> $rememberfile
else 
	echo "$@" >> $rememberfile
fi
exit 0
#!/bin/bash
# remind note
rememberfile="$HOME/.remember_work"
if [ ! -f $rememberfile ]
then
	echo "$0: .remember not exist." >$2
	exit 1
fi

if [ $# -eq 0 ]
then 
	more $rememberfile
else 
	grep -i "$@" $rememberfile | more
fi
exit 0

3.2 导航

#!/bin/bash
if [ $# -le 0 ] ; then 
	open https://baidu.com
elif [ $1 == 'mail' ] ; then
	open mail.163.com
...
fi

Shell还有很多用法,就如同 4.Motivation Example中,电脑里至少有上千个可执行命令,就如同乐高,用这些命令堆出你想像中的积木。你可以和Git,awk,sed,ffmpeg,adb,gradle等等开发环境和命令结合来打造你的完美开发环境。

个人简介

职业:阿里巴巴 - 无线开发专家
WX:sunquan97
邮件:sunquan9301@163.com
添加请注明CSDN + 原因,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值