---
title: "Bash编程入门（一） "
author: "阿男bluedash"
date: "2012-06-11T01:11:17Z"
tags: []
categories: ["编程语言"]
slug: "bash"
draft: false
lastmod: "2012-06-11T01:11:17Z"
id: 1558069
url: "https://weli.iteye.com/blog/1558069"
---

Shell编程很有趣，Shell编程很复杂，Shell编程离我们很近又似乎很远：使用Linux离不开它，但似乎又不曾仔细了解它。这套文章的目的是带你走进Shell编程的大门，领略它的丰富多彩。

* 本节讲解内容：echo，read与printf。

* 本节使用的shell版本为：


```bash

GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin11)
Copyright (C) 2007 Free Software Foundation, Inc.

```


* 所有本节讲解的内容，都需要你自己动手操作才能明白其含义

* 本文中所用到的所有命令，使用如下格式：


```bash

$ <some_command>
<output result>

```


**echo**

我们可以使用echo命令来输出字串：


```bash

$ echo Hello, world!
Hello, world!

```


**printf**

printf命令可以输出格式化的字串：


```bash

$ printf "%s \n %s\n" Hello world
Hello 
 world

```


例二：


```bash

$ printf "|%10s|%10s|\n" 1 200
|         1|       200|

```


**read**

read用于将字串读进变量，比如我们想将x，y分别赋值1，2：


```bash

$ read x y   
1 2

$ echo $x
1

$ echo $y
2

```


**总结**

最后，我们写个小程序总结一下：


```bash

echo "What's your name?"
read username
printf "%s, %s!" Hello $username

```


将这个文件命名为name.sh，执行它：


```bash

$ sh name.sh 
What's your name?
Jack
Hello, Jack!

```