bash shell 编程练习

Posted xiluhua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了bash shell 编程练习相关的知识,希望对你有一定的参考价值。

1. 创建可执行文件 t2.sh 并打印 "hello world!"

[email protected] ~ $ mkdir tscripts
[email protected] ~ $ cd tscripts/
[email protected] ~/tscripts $ echo #!/bin/bash >> t2.sh
[email protected] ~/tscripts $ echo echo "hello world!" >>t2.sh 
[email protected] ~/tscripts $ chmod +x *
[email protected] ~/tscripts $ ./t2.sh 
hello world!

 2. 运行可执行文件的 3中方法

[email protected] ~/tscripts $ ./t2.sh 
hello world!
[email protected] ~/tscripts $ sh t2.sh 
hello world!
[email protected] ~/tscripts $ /bin/sh t2.sh 
hello world!

 3. 使用变量

[email protected] ~/tscripts $ name=zhangsan
[email protected] ~/tscripts $ echo $name
zhangsan
[email protected] ~/tscripts $ echo ${name}
zhangsan
[email protected] ~/tscripts $ 

变量名外面的花括号是可选的,可加可不加,加花括号是为了帮助解释器识别变量的边界

4. for 循环打印 java c c++ php scala,体会 ${} 的作用

#!/bin/bash
for skill in java c c++ php scala;do
    echo "I am good at $skill"
done
 
echo "======================================="
for skill in java c c++ php scala;do
    echo "I am good at $skillScript"
done
 
echo "======================================="
for skill in java c c++ php scala;do
    echo "I am good at ${skill}Script"
done

5. 只读变量,unset 不能取消

[email protected] ~/tscripts $ name=jack
[email protected] ~/tscripts $ readonly name
[email protected] ~/tscripts $ echo $name
jack
[email protected] ~/tscripts $ name=Tom
-bash: name: readonly variable
[email protected] ~/tscripts $ unset name
-bash: unset: name: cannot unset: readonly variable
[email protected] ~/tscripts $ 

6. 非只读变量可以取消,取消后打印为空

[email protected] ~/tscripts $ unname=Jerry
[email protected] ~/tscripts $ unset unname
[email protected] ~/tscripts $ echo $unname

 7. 单引号

①. 单引号里的任何字符都原样输出,单引号变量中的变量是无效的;
②. 单引号字符串中不能出现单引号,对单引号使用转义符后也不行
[email protected] ~ $ name=Leo
[email protected] ~ $ echo $name
$name
[email protected] ~ $ echo $name> 

8. 双引号

①. 双引号里可以有变量
②. 双引号里可以出现转义字符
[email protected] ~ $ echo "I am $name"
I am Leo
[email protected] ~ $ echo "\\I am $name \\"
\I am Leo \

9. 拼接字符串

[email protected] ~ $ echo "He is $name"
He is Leo
[email protected] ~ $ echo "$name is handsome"!
Leo is handsome!
[email protected] ~ $ echo "$name is handsome!"
-bash: !": event not found

10. 获取字符串长度

[email protected] ~ $ echo ${#name}
3

11. 提取字符串

[email protected] ~ $ echo ${name:0:2}
Le

12. 

 

以上是关于bash shell 编程练习的主要内容,如果未能解决你的问题,请参考以下文章

bash编程练习脚本

Linux bash基础特性二

shell编程练习

OpenStack 环境下 SHELL 编程练习(持续更新中)

shell脚本编程练习

5.4shell编程3