码迷,mamicode.com
首页 > 系统相关 > 详细

bash shell 编程练习

时间:2017-01-14 13:33:20      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:取消   script   c++   转义字符   mod   执行   解释   shell   创建   

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

xiluhua@localhost ~ $ mkdir tscripts
xiluhua@localhost ~ $ cd tscripts/
xiluhua@localhost ~/tscripts $ echo #!/bin/bash >> t2.sh
xiluhua@localhost ~/tscripts $ echo echo "hello world!" >>t2.sh 
xiluhua@localhost ~/tscripts $ chmod +x *
xiluhua@localhost ~/tscripts $ ./t2.sh 
hello world!

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

xiluhua@localhost ~/tscripts $ ./t2.sh 
hello world!
xiluhua@localhost ~/tscripts $ sh t2.sh 
hello world!
xiluhua@localhost ~/tscripts $ /bin/sh t2.sh 
hello world!

 3. 使用变量

xiluhua@localhost ~/tscripts $ name=zhangsan
xiluhua@localhost ~/tscripts $ echo $name
zhangsan
xiluhua@localhost ~/tscripts $ echo ${name}
zhangsan
xiluhua@localhost ~/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 不能取消

xiluhua@localhost ~/tscripts $ name=jack
xiluhua@localhost ~/tscripts $ readonly name
xiluhua@localhost ~/tscripts $ echo $name
jack
xiluhua@localhost ~/tscripts $ name=Tom
-bash: name: readonly variable
xiluhua@localhost ~/tscripts $ unset name
-bash: unset: name: cannot unset: readonly variable
xiluhua@localhost ~/tscripts $ 

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

xiluhua@localhost ~/tscripts $ unname=Jerry
xiluhua@localhost ~/tscripts $ unset unname
xiluhua@localhost ~/tscripts $ echo $unname

 7. 单引号

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

8. 双引号

①. 双引号里可以有变量
②. 双引号里可以出现转义字符
xiluhua@localhost ~ $ echo "I am $name"
I am Leo
xiluhua@localhost ~ $ echo "\\I am $name \\"
\I am Leo \

9. 拼接字符串

xiluhua@localhost ~ $ echo "He is $name"
He is Leo
xiluhua@localhost ~ $ echo "$name is handsome"!
Leo is handsome!
xiluhua@localhost ~ $ echo "$name is handsome!"
-bash: !": event not found

10. 获取字符串长度

xiluhua@localhost ~ $ echo ${#name}
3

11. 提取字符串

xiluhua@localhost ~ $ echo ${name:0:2}
Le

12. 

 

bash shell 编程练习

标签:取消   script   c++   转义字符   mod   执行   解释   shell   创建   

原文地址:http://www.cnblogs.com/xiluhua/p/6285061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!