一、第一个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]#
参考文档:
本文介绍了几个基本的Shell脚本示例,包括简单的输出、读取用户输入、变量定义及使用、特殊变量的作用以及命令替换等内容,适合Shell脚本初学者。
2725

被折叠的 条评论
为什么被折叠?



