Linux初学者学习笔记

20170729 Shell 脚本编程基础(一)

2017-07-29  本文已影响20人  哈喽别样

一、编程基础概念:

二、shell脚本编程基础

三、变量:命名的内存空间

(一)变量类型:数值型、字符型等

(二)变量命名规则:

(三)bash变量的种类,根据变量的生效范围分类:

(四)本地变量:

<!--father.sh的程序代码-->
#! /bin/bash
#
name="father"
echo "the name in father.sh is $name"
bash son.sh
<!--son.sh的程序代码-->
#! /bin/bash
#
echo "the name in son.sh is $name"

2、执行father.sh脚本,结果如下:



3、根据执行脚本的结果表明,执行son.sh的子进程没有继承到来自父进程的变量name,证明本地变量仅对当前的shell进程有效。

(五)环境变量

<!--father.sh的程序代码-->
#! /bin/bash
#
export name="father"
echo "the name in father.sh is $name"
bash son.sh
<!--son.sh的程序代码-->
#! /bin/bash
#
echo "the name in son.sh is $name"

2、执行father.sh脚本,结果如下:



3、根据执行脚本的结果表明,执行son.sh的子进程继承到来自父进程的变量name,证明环境变量对当前的shell进程及其子进程有效。

(六)只读变量

(七)位置变量和特殊变量

#! /bin/bash
#
echo "the 1st number is $1"
echo "the 2nd number is $2"
echo "the 3rd number is $3"
echo "the 10st number is $10"
echo "the 20st number is $20"
echo "the 35st number is $35"
echo "the 1st number is $1"
echo "the 2nd number is $2"
echo "the 3rd number is $3"
echo "the 10st number is ${10}"
echo "the 20st number is ${20}"
echo "the 35st number is ${35}"

2、执行命令

bash parent.sh `echo {1..100..2}` 

结果如下:


地址变量1.png

3、发现结果不同,这是因为$10表达的意思是地址变量$1的值和字符0,${10}表达的意思是第10个地址变量。使用地址变量时当超出10个时要注意加大括号。

实验(二)
1、编写脚本文件parent.sh,代码如下:

#! /bin/bash
#
echo "the 1st number in parent.sh is $1"
echo "the 2nd number in parent.sh is $2"
echo "the 3rd number in parent.sh is $3"
echo "all of the number in parent.sh is $*"
echo "all of the number in parent.sh is $@"
echo
bash children.sh "$*"
echo 
bash children.sh "$@"

2、编写脚本文件children.sh,代码如下:

# /bin/bash
#
echo "the 1st number in children.sh is $1"
echo "the 2nd number in children.sh is $2"
echo "the 3rd number in children.sh is $3"
echo "all of the number in children.sh is $*"
echo "all of the number in children.sh is $@"

3、执行命令bash parent.sh {1..10},结果如下

4、从结果发现$*$@的作用有所不同,当其被双引号括起来后,$*把所有位置变量当做一个字符串整体传给子进程,而$@则是把每个位置变量分别传给子进程。这导致子进程的变量值的输出结果不同。

上一篇 下一篇

猜你喜欢

热点阅读