Linux Shell脚本学习笔记

本文介绍了几个基本的Shell脚本示例,包括简单的输出、读取用户输入、变量定义及使用、特殊变量的作用以及命令替换等内容,适合Shell脚本初学者。

一、第一个Shell脚本(hello-01.sh

#!/bin/bash
echo "Hello World!"
echo "Hello Shell!"

shell脚本执行

chmod 755 hello-01.sh 
sh hello-01.sh 
./hello-01.sh 

二、第二个Shell脚本

下面的脚本使用 read 命令从 stdin 获取输入并赋值给 name变量,最后在 stdout 上输出

[root@localhost testshell]# ll
total 8
-rwxr-xr-x. 1 root root 52 Mar 21 18:32 hello-01.sh
-rw-r--r--. 1 root root 68 Mar 21 18:44 hello-02.sh
[root@localhost testshell]# chmod 755 hello-02.sh 
[root@localhost testshell]# sh hello-02.sh 
What is your name?
Tian Ming
Hello Tian Ming!
[root@localhost testshell]# cat hello-02.sh 
#!/bin/bash
echo "What is your name?"
read name
echo "Hello $name!"

三、shell变量的定义(hello-03.sh

shell变量的定义时,等号(=)两边不能有空格

[root@localhost testshell]# chmod 755 hello-03.sh 
[root@localhost testshell]# cat hello-03.sh 
#!/bin/bash
TVDrama="game of thrones"
echo $TVDrama

myUrl="http://see.xidian.edu.cn/cpp/u/xitong/"
echo $myUrl
unset myUrl
echo $myUrl
[root@localhost testshell]# sh hello-03.sh 
game of thrones
http://see.xidian.edu.cn/cpp/u/xitong/

四、Shell特殊变量

[root@localhost testshell]# chmod 755 hello-04.sh 
[root@localhost testshell]# cat -n hello-04.sh 
     1  #!/bin/bash
     2  # $ representing the ID of the current Shell process, that is, PID
     3  echo $$
     4  echo "File Name: $0"
     5  echo "First Parameter : $1"
     6  echo "First Parameter : $2"
     7  echo "Quoted Values: $@"
     8  echo "Quoted Values: $*"
     9  echo "Total Number of Parameters : $#"
    10
[root@localhost testshell]# sh hello-04.sh 
4704
File Name: hello-04.sh
First Parameter : 
First Parameter : 
Quoted Values: 
Quoted Values: 
Total Number of Parameters : 0

五、Shell替换

  • 这里 -e 表示对转义字符进行替换。如果不使用 -e 选项,将会原样输出
  • 命令替换的语法: command 【注意是反引号,不是单引号,这个键位于 Esc 键下方。】
[root@localhost testshell]# chmod 777 hello-05.sh 
[root@localhost testshell]# cat hello-05.sh 
#!/bin/bash
sky=10
echo -e "Value of sky  is $sky  \n"

DATE=`date`
echo -e "Date is $DATE"

USERS=`who | wc -l`
echo -e "Logged in user are $USERS"

UP=`date ; uptime`
echo -e "Uptime is $UP"
[root@localhost testshell]# sh hello-05.sh 
Value of sky  is 10  

Date is Fri Mar 30 01:42:08 PDT 2018
Logged in user are 5
Uptime is Fri Mar 30 01:42:08 PDT 2018
 01:42:08 up  2:10,  5 users,  load average: 0.04, 0.04, 0.05
[root@localhost testshell]#

参考文档:

  1. http://c.biancheng.net/cpp/view/2739.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值