Linux shell编程学习(一)

一、创建shell脚本文件

创建shell脚本文件时,必须在文件的第一行指定要使用的shell.

   #!/bin/bash

通常,在shell脚本中,井号(#)用作注释行,shell脚本文件的第一行是个例外,#后面的!号会告诉shell会用哪一个shell,除了bash shell还可以用其他的shell.在shell脚本中,可以使用分号将两个命令放在一行上,但在shell脚本中,可以独立书写命令。shell根据会根据命令在文件中的顺序进行处理。
下面的代码是一个小例子:包含了创建shell文件,添加可执行权限,以及用echo作交互,运行程序。

$ vim test
#!/bin/bash
# This script display the date and who's logged on 
echo The time and date are:
date
echo "Let's see who's logged into the system:"
who
~                                                                                                                            
$ ./test
bash: ./test: Permission denied
$ ls -l test 
-rw-rw-r-- 1 douxiao douxiao 74 510 10:36 test
$ chmod u+x test
$ ls -l test 
-rwxrw-r-- 1 douxiao douxiao 74 510 10:36 test
$ ./test 
The time and date are:
20170510日 星期三 13:52:12 CST
Let's see who's logged into the system:
douxiao  tty7         2017-05-10 09:05 (:0)

二、脚本中使用变量

使用系统环境变量:

    运行shell脚本中的单个命令会有很多限制,通常会需要在shell命令使用其他数据来处理信息。这个可以通过变量来实现。变量允许临时性的将信息存储在shell脚本中,以便和其他命令一起使用。

在脚本中,可以在环境变量名称前面加上美元符$来使用这些变量。

$ vim test1
#!/bin/bash
#display user information from the system.
echo "User info for userid: $USER"
echo UID: $UID
echo HOME: $HOME
$ chmod u+x test1
$ ./test1
User info for userid: douxiao
UID: 1000
HOME: /home/douxiao

echo命令中的环境变量会在脚本运行时替换成当前的值,如过真的需要显示$,需要在前面放置一个(\) 例如:\$15

使用用户变量:

 除了环境变量,shell脚本还允许在脚本中定义和使用自己的环境变量。定义变量允许临时存储数据并在整个脚本中使用,用户变量可以是由字母、数字和下划线组成的文本字符串,长度不超过20个。用户变量区分大小写所以变量Var1和变量var1是不同的。

Note:使用等号将值赋给用户变量,在变量、等号和值之间不能出现空格。

shell脚本会自动决定变量值的数据类型。在shell脚本的整个生命周期里,shell脚本定义的变量会一直保持着他们的值,在shell脚本结束后被删除。下面是定义用户变量的例子。

var1=10
var2=-57
var3=testing
var4="still more testing"

与系统变量类似,用户变量可以通过美元符来引用

$vim test2
#!/bin/bash
days=10
guest="douxiao"
echo "$guest checked in $days days ago"
days=5
guest="xiaoming"
echo "$guest checked in $days days ago"
~   
$ chmod u+x test2
$ ./test2
douxiao checked in 10 days ago
xiaoming checked in 5 days ago

命令替换:

有两种方法可以将命令输出赋给变量:
(1)使用反引号字符(`)
(2)$( )格式

将系统变量date的输出值赋给用户变量testing,调用时可以使用$testing
testing=$(date)
testing =`date`
echo "The date and time are: "$testing
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值