Showing posts with label Shell. Show all posts
Showing posts with label Shell. Show all posts

Introduction to Shell Script on UNIX (1)

Introduction to Shell Script on UNIX (1)

Shell解析器


可以通过以下命令查看系统所提供的解析器

$cat /etc/shells

HelloWorld example (helloworld.sh)

创建脚本程序

$touch helloworld.sh
$vi helloworld.sh
Edit:
#!/bin/bash
echo "helloworld"

or $cat > helloworld.sh
#!/bin/bash
echo "HelloWorld!" 


Note:

First line: #!/bin/bash

Exit cat > by ctrl + c

脚本的执行方式

1 bash/sh + 脚本的相对路径/绝对路径

sh

$sh ./helloworld.sh


$sh /home/qfhou/bash_study/helloworld.sh 

Similarly for bash

$bash ./helloworld.sh

$bash /home/qfhou/bash_study/helloworld.sh

2 采用输入脚本的相对路径/绝对路径执行脚本 (脚本需要具有可执行权限)

赋予helloworld.sh可执行权限
$chmod +x ./bash_study/helloworld.sh

Note: 

Search cmd history

ctrl + r + string

(reverse-i-search)`ch': chmod +x ./bash_study/helloworld.sh

Full history

$history

执行脚本

$./helloworld.sh

$/home/qfhou/bash_study/helloworld.sh

变量

定义

$变量名=变量值  (=前后不能有空格)

显示变量值

$echo $变量名

撤销变量
$unset 变量名 (not unset $变量名)

静态变量声明(不能撤销)
$readonly B=9

把变量提升为全局环境变量,可供其他 Shell 程序使用

$export 变量名

特殊变量

$n
功能描述:n 为数字,$0 代表该脚本名称,$1-$9 代表第一到第九个参数,十以
上的参数,十以上的参数需要用大括号包含,如${10}

$#
功能描述:获取所有输入参数个数,常用于循环 , 判断参数的个数是否正确以及
加强脚本的健壮性

parameter.sh


Results


$*

(功能描述:这个变量代表命令行中所有的参数,$*把所有的参数看成一个整体)

$@

(功能描述:这个变量也代表命令行中所有的参数,不过$@把每个参数区分对待)

Test (parameter.sh)



Output




$?

(功能描述:最后一次执行的命令的返回状态。如果这个变量的值为 0,证明上一
个命令正确执行;如果这个变量的值为非 0(具体是哪个数,由命令自己来决定),则证明
上一个命令执行不正确了。)

Note: True -> 0; False -> 1

Last execution:





Featured Posts

SnowPro Badges and Certificates

SnowPro Badges and Certificates Online Verification https://achieve.snowflake.com/profile/richardhou888/wallet

Popular Posts Recommended