shell的环境变量
默认情况下shell脚本程序会在一个新创建的环境下执行,所以脚本程序对环境变量所做的任何修改都会丢失。
这里就出现了bash script.sh与source script.sh (或者是 . ./script.sh)的区别。
实验:
export_test.sh
#!/bin/sh
export ZHENG="/helloworld"
shell执行:
(1)
bash export_test.sh
echo $ZHENG
(2)
source export_test.sh
echo $ZHENG
(3)
. ./export_test.sh
echo $ZHENG
为了实验的可比性,每次都是重新开启shell执行。
其结果是:
(1)没有ZHENG的定义,(2)(3)有。
bash执行时 是另外开启一个shell执行脚本。诸位可以试一下:开启俩个shell,在其中一个export ZHENG=”hello Leteno” 在另一个shell中echo $ZHENG. (结果是获取不到的)
而source与. 呢?
在shell脚本程序中,点命令的作用有点类似于C 或C++语言里的#include指令
—摘自《Linux程序设计》P44
这里的#include 我理解为内联inline,也就是说. 会将脚本直接粘贴到当前的shell中执行,也就是说. ./export_test.sh 等同于在shell中执行
#!/bin/sh
export ZHENG=”/helloworld”
至于source。。。 应该等同于. 吧 – –
P.S. export 导出的变量,可以在shell调用的任何脚本上使用。而name=”abc”只是一个局部变量,无法在其他脚本上运行(除非传参)
(如果想保存环境变量,请到.bashrc中修改,可以测试一下,在.bashrc 添加export语句,再到当前的shell echo,另开shell,测试echo,把.bashrc修改回来,再echo(包括在当前shell以及另开的shell) 会有意外收获哦 OvO)
精益求精 OvO
#!/bin/sh
if [ -f .profile ]; then
exit 0
fi
exit 1
========>>>
[ -f .profile ] && exit 0 || exit 1
是不是有点类似于greeting=(ismale)?"Good moring Sir" :"Good moring Madom";
膜拜膜拜
还有些细节: 比如反引号`比单引号'兼容老版本,编程时多用`
关于美元符号$
$的用处很多:
命令 | 含义 |
---|---|
$attri | 变量attri的内容 常常写成${attri} |
$0 | 当前文件名(一般用于返回当前执行的脚本名) |
$n | 传入的参数($1 表示传入的第一个参数, 以此类推) |
$# | 传入参数的个数 |
$* | 传入的参数列表 (可以用 for attri in $* 逐个获取) |
$$ | 当前进程的进程号 |
$(command) | 执行命令,将返回命令输出结果 |
$((1+2)) | 用于算术运算 比expr更高效 |
其实如果你把终端下的命令看作是shell(int argc, char *argv[])函数的输入
0
1 就清楚了
比如 $ ls zheng
输入到shell的参数是2个,第一个($0) 是 ls,也就是当前执行的脚本名,第二个参数($1)是zheng,也是脚本的第一个参数。。。
shell测试与调试
bash命令 支持对脚本的测试和调试,有三个选项:
选项 | 含义 |
---|---|
-x | 跟踪执行的过程(以+为标记) |
-v | 在执行scripts之前,先将scripts内容显示在屏幕 |
-v | 不执行scripts,只检查语法 |
如:
sample.sh
#!/bin/bash
# this is a simple script
# read name, and say hello to her/him (am i a gentleman >v0)
read -p "please enter your name:" name
echo "here is a message from mr.leteno"
echo "hello ${name}"
执行:
bash -xv sample.sh
结果:
#!/bin/bash
# this is a simple script
# read name, and say hello to her/him (am I a gentleman >v0)
read -p "please enter your name:" name
+ read -p 'please enter your name:' name
please enter your name:zheng
echo "here is a message from Mr.Leteno"
+ echo 'here is a message from Mr.Leteno'
here is a message from Mr.Leteno
echo "hello ${name}"
+ echo 'hello zheng'
hello zheng
其中 + 表示当前命令执行情况, 可以看到有些"地方"${}都替换成实际值(原谅我实在想不出可以替代"地方"的名词)
题外话:
以前总吐槽printf 中的-d 为什么要这么奇葩,-i不好吗?
现在回想一下,毕竟年轻,-d表示的是decimal(特指十进制数字),而int表示的是 integer(整型 或者说数字),-d就比int要准确许多,试想还有hex(16) Oct(8). 其实,到最底层,也都是0101,或者说,97 可以是数字97, 也可以是字符’a’…. 所以说,int是不贴切的,我们认识的int是decimal的int. 也可以说,一个数据,从不同的角度上看,可以有不同的结果:
6265 6175 7469 6675 6c 或许没意义,但是有些人却能从中发现beautiful……