四时宝库

程序员的知识宝库

构建shell脚本文件小笔记(shell脚本结构)

创建shell脚本文件

vi 1.sh

#!/bin/bash #指定要使用的shell

#This script displays the date and who's logged on. #注释行

date

who

执行脚本时,

①在文件所在目录,bash 1.sh;

②在文件所在目录,./1.sh或者将shell脚本文件所处的目录添加到PATH环境变量中,

另外还需要赋予文件执行的权限,chmod u+x 1.sh。

显示消息

如果你在文本中使用到了单引号或双引号,那就使用另一种把字符串圈起来。

echo “This is a test to see if you’re paying attention”

-n参数

echo -n “The time and date are: ”

date

输出结果为:The time and date are: Fri Jan 12 15:16:35 CST 2018

使用变量

1.环境变量

只要在脚本在引号中看到美元符,它就会以为你在引用1个变量,所以需要使用反斜线来将美元符解释成为实际的美元符。

#echo “The cost of the item is \$15”

The cost of the item is $15

2.用户变量

var1=10

3.反引号

反引号允许你将shell命令的输出赋给变量。

testing=`date`

echo The date and time are: $testing

The date and time are: Fri Jan 12 15:40:08 CST 2018

today=`date +%y%m%d`

ls /usr/bin -al >log.$today

重定向输入和输出

> >> < <<

在命令行上使用内联输入重定向

wc << EOF

>test string 1

>test string 2

>test string 3

>EOF

3 9 42

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接