第一个script
[[email protected] script]# cat -n sh01.sh 1 #!/bin/bash 2 #Program: 3 #This program shows "Hello World!" in your screen. 4 PATH=/usr/local/java/jdk1.8.0_91/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/root/bin:~/bin 5 export PATH; 6 echo -e "Hello World! \a \n" 7 exit 0
第一行:#!/bin/bash 声明这个script使用的shell名称
第二三行:注释
第四行:环境变量的声明,这样程序执行时可以直接执行一些外部命令,而不必写绝对路径
第五行:使环境变量生效
第六行:主程序部分
第七行:使用exit命令让程序中断,并且传回一个数值给系统,执行完该script后,使用echo $?可以得到该值。
[[email protected] script]# vi sh01.sh [[email protected] script]# ./sh01.sh Hello World! //查看上面script返回给系统的值 [[email protected] script]# echo $? 0
简单的shell script练习
交互式脚本:变量内容由用户确定
[[email protected] script]# cat -n sh02.sh 1 #!/bin/bash 2 PATH=/usr/local/java/jdk1.8.0_91/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/root/bin:~/bin 3 export PATH 4 5 read -p "please input your first name:" firstname #tell user to input their name 6 read -p "please input your last name:" lastname 7 echo -e "\n Your full name is:$firstname $lastname" [[email protected] script]# sh sh02.sh please input your first name:wu please input your last name:chao Your full name is:wu chao [[email protected] script]#
随日期变化:利用日期创建文件
//查看script脚本 [[email protected] script]# cat sh03.sh #!/bin/bash PATH=/usr/local/java/jdk1.8.0_91/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/root/bin:~/bin export PATH echo -e "I will use ‘touch‘ command to create 3 files." read -p "please input your file name:" fileuser filename=${fileuser:-"filename"} date1=$(date -d -2day +%Y%m%d) date2=$(date -d -1day +%Y%m%d) date3=$(date +%Y%m%d) file1=${filename}${date1} file2=${filename}${date2} file3=${filename}${date3} touch "$file1" touch "$file2" touch "$file3" //执行该脚本 [[email protected] script]# sh sh03.sh I will use ‘touch‘ command to create 3 files. please input your file name:testFile [[email protected] script]# //查看结果 [[email protected] script]# ls -l testFile* -rw-r--r--. 1 root root 0 7月 19 12:40 testFile20160717 -rw-r--r--. 1 root root 0 7月 19 12:40 testFile20160718 -rw-r--r--. 1 root root 0 7月 19 12:40 testFile20160719 [[email protected] script]#
注:$()是执行里面的代码得到的结果。${}取变量的值。
数值运算
[[email protected] script]# cat sh04.sh #!/bin/bash PATH=/usr/local/java/jdk1.8.0_91/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/root/bin:~/bin export PATH echo -e "please input two numbers:" read -p "first number:" n1 read -p "second number:" n2 total=$(($n1*$n2)) echo -e "\n The result of $n1 * $n2 is ==> $total" [[email protected] script]# [[email protected] script]# sh sh04.sh please input two numbers: first number:12 second number:23 The result of 12 * 23 is ==> 276 [[email protected] script]#
var=$((运算内容))
用于计算
[[email protected] script]# echo $((23*3)) 69
时间: 2024-10-12 03:17:31