首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >半小时入门Shell编程

半小时入门Shell编程

作者头像
趣学程序-shaofeer
发布2020-05-16 22:03:02
7260
发布2020-05-16 22:03:02
举报
文章被收录于专栏:upuptop的专栏upuptop的专栏

本文引导

  • shell概述
  • shell解释器
  • Shell脚本入门
  • Shell中的变量
    • 系统变量
    • 自定义变量
    • 特殊变量:$n
    • 特殊变量:$#
    • 特殊变量:`、@`
    • 特殊变量:$?
  • 运算符
  • 条件判断
  • 流程语句(重点)
    • if判断
    • case语句
    • for循环
    • while循环
  • read(读取用户输入)
  • 函数
    • 系统函数
    • 自定义函数

Shell学习

shell概述

shell是一个命令行解释器,它接收应用程序/用户命令,然后调用操作系统内核。

shell解释器

  1. Linux提供的解释器有
[shaofei@upuptop-pc ~]$ cat /etc/shells /bin/sh/bin/bash/usr/bin/sh/usr/bin/bash
  1. bash和sh的关系
[shaofei@upuptop-pc bin]$ ll | grep bash-rwxr-xr-x    1 root root    964600 Aug  8  2019 bashlrwxrwxrwx    1 root root         4 Oct 28  2019 sh -> bash
  1. Centos默认的解析器是bash
[shaofei@upuptop-pc bin]$ echo $SHELL/bin/bash

Shell脚本入门

  1. 脚本格式 脚本以 #!/bin/bash 开头(指定解析器)
  2. 第一个shell脚本
[shaofei@upuptop-pc sh]$ touch helloworld.sh[shaofei@upuptop-pc sh]$ vim helloworld.sh 

#!/bin/bashecho "helloworld"
  1. 脚本的常用执行方式

(1) 采用bash或sh+脚本的相对路径或绝对路径(不用赋予脚本+x权限)

[shaofei@upuptop-pc sh]$ sh helloworld.sh helloworld
[shaofei@upuptop-pc sh]$ bash helloworld.sh helloworld

(2)采用输入脚本的绝对路径或相对路径执行脚本(必须具有可执行权限+x)

[shaofei@upuptop-pc sh]$ chmod 777 helloworld.sh [shaofei@upuptop-pc sh]$ ./helloworld.sh helloworld[shaofei@upuptop-pc sh]$ /home/shaofei/sh/helloworld.sh helloworld

❝注意:第一种执行方法,本质是bash解析器帮你执行脚本,所以脚本本身不需要执行权限。第二种执行方法,本质是脚本需要自己执行,所以需要执行权限。 ❞

  1. 多命令处理
[shaofei@upuptop-pc sh]$ touch batch.sh[shaofei@upuptop-pc sh]$ vim batch.sh 
#!/bin/bashecho 'hello'cd /home/shaofei/shecho 'cccc' > a.txt

Shell中的变量

系统变量

  1. 常用的系统变量

HOME,SHELL等

  1. 案例
[shaofei@upuptop-pc sh]$ echo $HOME/home/shaofei[shaofei@upuptop-pc sh]$ echo $PWD/home/shaofei/sh[shaofei@upuptop-pc sh]$ echo $USERshaofei
显示当前Shell中所有变量:set
[shaofei@upuptop-pc sh]$ setBASH=/bin/bashBASHOPTS=checkwinsize:cmdhist:expand_aliases:extquote:force_fignore:histappend:hostcomplete:interactive_comments:login_shell:progcomp:promptvars:sourcepathBASH_ALIASES=()BASH_ARGC=()BASH_ARGV=()BASH_CMDS=()BASH_LINENO=()BASH_SOURCE=()
………………

自定义变量

  1. 基本语法 a. 定义变量:变量名=变量值 b. 撤销变量:unset 变量名 c. 声明静态变量:readonly 变量, 注意不能unset
  2. 定义规则 a. 变量名可以使用字母、数字、下划线组成,但是不能以数字开头。「环境变量建议全部大写」b. 「等号前后不能有空格」c. 在bash中,变量类型默认是字符串类型,无法直接进行数值计算 d. 变量的值如果有空格必须要用"双引号"引起来
  3. 案例
创建变量A并赋值为5
[shaofei@upuptop-pc sh]$ A=5[shaofei@upuptop-pc sh]$ echo $A5
给变量A重新赋值为9[shaofei@upuptop-pc sh]$ A=9[shaofei@upuptop-pc sh]$ echo $A9
撤销变量A[shaofei@upuptop-pc sh]$ unset A[shaofei@upuptop-pc sh]$ echo $A
创建静态的变量B[shaofei@upuptop-pc sh]$ readonly B=2[shaofei@upuptop-pc sh]$ echo $B2
静态变量不能重新赋值[shaofei@upuptop-pc sh]$ B=10-bash: B: readonly variable
静态变量不能unset[shaofei@upuptop-pc sh]$ unset B-bash: unset: B: cannot unset: readonly variable
在bash中,变量默认类型都是字符串类型,无法直接进行数值运算[shaofei@upuptop-pc sh]$ C=1+2[shaofei@upuptop-pc sh]$ echo $C1+2
变量的值如果有空格,需要使用双引号或单引号括起来[shaofei@upuptop-pc sh]$ D=I LOVE YOU-bash: LOVE: command not found[shaofei@upuptop-pc sh]$ D="I LOVE YOU"[shaofei@upuptop-pc sh]$ echo $DI LOVE YOU
可把变量提升为全局环境变量,可供其他Shell程序使用[shaofei@upuptop-pc sh]$  vim helloworld.sh 
在helloworld.sh文件中增加echo $B#!/bin/bash
echo "helloworld"echo $B
没有打印$B的值
[shaofei@upuptop-pc sh]$ sh helloworld.sh helloworld
修改B变量为全局环境变量[shaofei@upuptop-pc sh]$ export B[shaofei@upuptop-pc sh]$ sh helloworld.sh helloworld2

特殊变量:$n

  1. 基本语法

$n 功能描述:n为数字,代表该脚本名称,1-代表第一到第九个参数,十以内的参数,十以上的参数需要用大括号包含,如{10}

  1. 案例

输出该脚本的文件名称、输入参数1和输入参数2的值

[shaofei@upuptop-pc sh]$ touch param.sh[shaofei@upuptop-pc sh]$ vim param.sh 
#!/bin/bashecho $0  $1 $2
[shaofei@upuptop-pc sh]$ sh param.sh  1 2 3param.sh 1 2

特殊变量:$#

  1. 基本语法

$# (获取所有的参数个数,常用于循环)

  1. 案例
[shaofei@upuptop-pc sh]$ vim param.sh #!/bin/bashecho $#[shaofei@upuptop-pc sh]$ sh param.sh 1 2 3 4 55

特殊变量:$*$@

  1. 基本说法

$* (功能描述:这个变量代表命令行中所有的参数,$*把所有的参数看做一个整体)$@(功能描述:这个变量代表命令行中所有的参数,不过$@把每个参数区别对待)

  1. 案例
[shaofei@upuptop-pc sh]$ vim param.sh 
#!/bin/bashecho $@echo $*
[shaofei@upuptop-pc sh]$ sh param.sh 1 2 3 4 51 2 3 4 51 2 3 4 5

特殊变量:$?

  1. 基础语法

$? (功能描述:最后一次执行的命令的返回状态。如果这个变量的值为0,证明上一个命令正确执行;如果这个变量的值为非0,则证明上一个命令执行不正确了)

  1. 示例:
[shaofei@upuptop-pc sh]$vim param.sh #!/bin/bashecho $?
[shaofei@upuptop-pc sh]$ ./helloworld.sh helloworld
[shaofei@upuptop-pc sh]$ sh param.sh 0

运算符

  1. 基础语法

(1) $((运算式))$[运算式](2) expr +,-,*,/,% 加,减,乘,除,取余

「注意:expr 运算符之间要有空格」

  1. 实例 (1)计算3+2的值
[shaofei@upuptop-pc sh]$ expr 3 + 25

(2)计算3-2的值

[shaofei@upuptop-pc sh]$ expr 3 - 2  1

(3)计算(2+3)* 4的值

第一种方式[shaofei@upuptop-pc sh]$ expr `expr 2 + 3 ` \* 420
第二种方式[shaofei@upuptop-pc sh]$ echo $(((3+2)*4))20
第三种方式  [shaofei@upuptop-pc sh]$ echo $[(2+3)*4]20

条件判断

  1. 基本语法[ condition ]「注意:condition前后有空格」
  2. 常用的判断条件

(1) 两个整数之间比较

= 字符串比较-lt 小于(less than)-le 小于等于(less equal)-eq 等于(equal)-gt 大于(greater)-ge 大于等于(greater equal)-ne 不等于(Not equal)

(2) 按照文件权限进行比较-r 有读的权限(read)-w 有写的权限(write)-x 有执行的权限(execute)

(3) 按照文件类型进行判断

-f 文件存在并且是一个常规的文件(file)-e 文件存在(existence)-d 文件存在且是一个目录(directory)

案例:

  1. 23 是否大于等于 22
[shaofei@upuptop-pc ~]$ [ 22 -ge 23 ][shaofei@upuptop-pc ~]$ echo $?      1[shaofei@upuptop-pc ~]$ [ 23 -ge 23 ] [shaofei@upuptop-pc ~]$ echo $?      0
  1. HelloWorld.sh 是否有写的权限
-rw-rw-r-- 1 shaofei shaofei  5 May  8 23:02 a.txt-rw-rw-r-- 1 shaofei shaofei 65 May  8 23:01 batch.sh-rwxrwxrwx 1 shaofei shaofei 38 May  8 23:36 helloworld.sh-rw-rw-r-- 1 shaofei shaofei 31 Dec  8 01:01 k.sh.template-rw-rw-r-- 1 shaofei shaofei 22 May  9 21:56 param.sh-rw-rw-r-- 1 shaofei shaofei 59 Dec  8 01:01 start.sh.template-rwxrwxrwx 1 shaofei shaofei 21 Nov 20 09:58 test1.sh[shaofei@upuptop-pc sh]$ [ -r helloworld.sh ][shaofei@upuptop-pc sh]$ echo $?0[shaofei@upuptop-pc sh]$ [ -x batch.sh ][shaofei@upuptop-pc sh]$ echo $?1
  1. /home/shaofei/aaa.txt 是否存在
[shaofei@upuptop-pc sh]$ [ -e /home/shaofei/aaa.txt ][shaofei@upuptop-pc sh]$ echo $?1
  1. 多条件判断(&& 表示前一条命令执行成功时,才执行后一条命令,|| 表示上一条命令执行失败后,才执行下一条命令)
[shaofei@upuptop-pc sh]$ [ -e /home/shaofei/aaa.txt ] || echo falsefalse[shaofei@upuptop-pc sh]$ [ -e /home/shaofei/aaa.txt ] && echo false  [shaofei@upuptop-pc sh]$

流程语句(重点)

if判断

  1. 基本语法
if [ 条件判断式 ]; then
   程序代码
fi

或者

if [ 条件判断式 ]
then     程序代码
fi

「注意:」

  • [ 条件表达式 ] 中括号和条件判断式之间必须有空格
  • if后面要有空格
  • 第一种方式 then 前面要有分号
  1. 案例

❝输入一个数字,如果是1 则输出 true 如果是2 则输出 false 如果是其他数字则不做任何操作 ❞

[shaofei@upuptop-pc sh]$ vim if.sh 
#!/bin/bash
if [ $1 -eq 1 ]; then        echo truefi
if [ $1 -eq 2 ]; then        echo falsefi
[shaofei@upuptop-pc sh]$ sh if.sh 1true[shaofei@upuptop-pc sh]$ sh if.sh 2false
[shaofei@upuptop-pc sh]$ sh if.sh 123[shaofei@upuptop-pc sh]$

case语句

  1. 基础语法
case $变量名 in    "value1")        如果变量等于value1,执行程序    ;;       "value2")        如果变量等于value2,执行程序    ;;      ……省略其他分支……
esac

「注意」

  • case行尾必须为单词 in,每一个模式匹配必须以)结束。
  • 双分号;;表示命令序列结束,相当于java中的break
  • 最后可以使用*)表示默认模式,相当于java中的break
  • 最后以esac结束
  1. 案例

❝输入一个数字,如果是1 则输出 true 如果是2 则输出 false 如果是其他数字输出default ❞

[shaofei@upuptop-pc sh]$ vim case.sh #!/bin/bash
case $1 in        1)        echo true;;        2)        echo false;;        *)        echo default;;
esac


[shaofei@upuptop-pc sh]$ sh case.sh 1true[shaofei@upuptop-pc sh]$ sh case.sh 2false[shaofei@upuptop-pc sh]$ sh case.sh 3default[shaofei@upuptop-pc sh]$

for循环

  1. 基本语法
  • 第一种方式
for  (( 初始值;循环控制条件;变量变化 ))
    do        程序    done
  • 第二种方式
for  变量 in 变量1,变量2,变量
    do        程序    done
  1. 实例

❝计算1-100的和 ❞

[shaofei@upuptop-pc sh]$ vim for1.sh 
#!/bin/bash
sum=0for ((i=1;i<=100;i++))    do        sum=$[$sum+$i] # or sum=$(( $sum+$i ))    done
echo $sum
[shaofei@upuptop-pc sh]$ sh for1.sh

❝打印所有的输入参数 比较和@ ❞

  • $*$@都不被双引号""包括的时候,没有区别,$*$@都表示传递给函数或脚本的所有参数,不被双引号""包含时,都以$1 $2 …$n的形式输出所有参数。
[shaofei@upuptop-pc sh]$ vim  for2.sh
#!/bin/bash
echo ---------$*
for i in $*        do                echo $i        done

echo --------$#
for j in $@        do                echo $j        done
echo --------end
[shaofei@upuptop-pc sh]$ sh for2.sh 1 2 3 4---------1 2 3 41234--------41234--------end
  • 当它们被双引号""包含时,"$*"会将所有的参数作为一个整体,以"$1 $2 …$n"的形式输出所有参数;"$@"会将各个参数分开,以"$1" "$2"…"$n"的形式输出所有参数。
[shaofei@upuptop-pc sh]$ vim  for3.sh
#!/bin/bash
echo ---------"$*"
for i in "$*"        do                echo $i        done

echo --------$#
for j in "$@"        do                echo $j        done
echo --------end

[shaofei@upuptop-pc sh]$ sh for3.sh 1 2 3 4---------1 2 3 41 2 3 4--------41234--------end

while循环

  1. 基本语法
while [ 条件表达式 ]     do        程序    done    
  1. 案例

❝计算1-100的和 ❞

[shaofei@upuptop-pc sh]$ vim while.sh #!/bin/bash
sum=0i=0while [ $i -le 100 ]    do        sum=$(( $sum+$i ))        i=$[$i+1]    done
echo  $sum
[shaofei@upuptop-pc sh]$ sh while.sh  5050

「注意:」 while后面有空格.

read(读取用户输入)

  1. 基本语法
read(选项)(参数)	选项:        -p:指定读取值时的提示符;        -t:指定读取值时等待的时间(秒)。    参数    	变量:指定读取值的变量名
  1. 实例
[shaofei@upuptop-pc sh]$ vim read.sh 
#!/bin/bash
read -p "input your name: " -t 3 NAME
echo "Your Name is $NAME !"


[shaofei@upuptop-pc sh]$ sh read.sh input your name: shaofeerYour Name is shaofeer !

函数

系统函数

  • basename
  1. basename基本语法
basename [string/pathname][suffix]

(功能描述:basename命令会删掉所有的前缀包括最后一个(‘/’)字符,然后将字符串显示出来。选项:    suffix为后缀,如果suffix被指定了,basename会将pathname或string中的suffix去掉。
  1. 案例实操
[shaofei@upuptop-pc sh]$ basename /home/shaofei/123.txt 123.txt
[shaofei@upuptop-pc sh]$ basename /home/shaofei/123.txt .txt123
  • dirname
  1. dirname基本语法
dirname 文件绝对路径	    (功能描述:从给定的包含绝对路径的文件名中去除文件名(非目录的部分),然后返回剩下的路径(目录的部分))
  1. 案例实操

获取a.txt文件的路径

[shaofei@upuptop-pc sh]$ dirname /home/shaofei/sh/a.txt /home/shaofei/sh

自定义函数

  1. 基本语法
[ function ] funname[()]{	Action;	[return int;]}funname
  1. 「经验技巧」-(1)必须在调用函数地方之前,先声明函数,shell脚本是逐行运行。不会像其它语言一样先编译。-(2)函数返回值,只能通过$?系统变量获得,可以显示加:return返回,如果不加,将以最后一条命令运行结果,作为返回值。return后跟数值n(0-255)

3.案例实操 (1)计算两个输入参数的和

[shaofei@upuptop-pc sh]$ vim fun.sh 
#!/bin/bash
function sum(){        sum=$[$1+$2]        return $sum
}

sum 1 2
echo $?

[shaofei@upuptop-pc sh]$ sh fun.sh 3
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-05-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 趣学程序 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Shell学习
    • shell概述
      • shell解释器
        • Shell脚本入门
          • Shell中的变量
            • 系统变量
            • 自定义变量
            • 特殊变量:$n
            • 特殊变量:$#
            • 特殊变量:$*、$@
            • 特殊变量:$?
          • 运算符
            • 条件判断
              • 流程语句(重点)
                • if判断
                • case语句
                • for循环
                • while循环
              • read(读取用户输入)
                • 函数
                  • 系统函数
                  • 自定义函数
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档