---
title: "Linux shell编程 2 ---- shell变量"
author: "caobihole"
date: "2013-09-22T16:24:00Z"
tags: []
slug: "linux-shell-2-shell"
draft: false
lastmod: "2013-09-22T19:49:51Z"
id: 1945579
url: "https://caobihole.iteye.com/blog/1945579"
---

1 shell变量

1 在shell编程语言里面有两种变量的类型，字符串和整型

2 定义shell变量

name=string

1 name是变量名，变量名用小写字母命名

2 =是赋值符号，=的两边不能有空格，否则将视为命令

3 string是被赋值的变量，比如字符串或者是整数

3 在shell里面我们使用$来取得变量的值

2 字符串变量

1 v1=centos

v2="this is a shell"（在所有的脚本语言里面字符串可以用单引号也可以使用双引号来赋值）

2 通过第一点，我们发现如果被赋的值有空格，我们必须要使用引号，如果没有空格可以则可以省略引号

3 练习：使用shell来测试字符串变量

![](http://img.blog.csdn.net/20130922152048250)

![](http://img.blog.csdn.net/20130922152219890)

3 整型变量

1 a=10

b=20

2 整型变量的注意事项和字符串变量一样

3 练习：利用整型变量来进行四则运算

1 在shell里面如果要进行两个整型数的四则运算，我们必须使用$(())来做

![](http://img.blog.csdn.net/20130922153031953)

![](http://img.blog.csdn.net/20130922153108296)

4 shell字符串变量表达式

1 ${#string}，用来计算字符串string的长度

![](http://img.blog.csdn.net/20130922155123250)

![](http://img.blog.csdn.net/20130922155210656)

2 ${string:position}，从position位置开始提取字符串

![](http://img.blog.csdn.net/20130922155349625)

![](http://img.blog.csdn.net/20130922155437875)

3 ${string:position:length}从位置position开始提取长度为length的子串

![](http://img.blog.csdn.net/20130922155644046)

![](http://img.blog.csdn.net/20130922155713390)

4 ${string#substring}，从开头删除substring子串

![](http://img.blog.csdn.net/20130922161511031)

![](http://img.blog.csdn.net/20130922161517109)

5 ${string#I\*.}，删除从I开始到.的所有字符（最短匹配）

比如删除从t开始到s结束的最短匹配

![](http://img.blog.csdn.net/20130922161826015)

![](http://img.blog.csdn.net/20130922161938593)

6 ${string##I\*.}，删除从I开始到.的所有字符（最长匹配）

比如删除从t开始到s结束的最长匹配

![](http://img.blog.csdn.net/20130922162233468)

![](http://img.blog.csdn.net/20130922162314750)