简单的shell scripts例子

来源:互联网 发布:非洲大蜗牛 知乎 编辑:程序博客网 时间:2024/05/05 13:04

看了几天的linux,刚开始接触shell脚本的编程。对着书上的课后题,写了几个非常简单的shell脚本,发到博客上来供自己复习思考一下,如有错误,还望指正。


编写shell脚本可以用任意文本编辑器,后缀为sh。编写完后并没有执行的权限,所以要给它加上权限。例如刚写完一个命名为sh01.sh的脚本,在此路径的终端下执行

chmod 755 sh01.sh,然后再敲击命令./sh01.sh执行。


chmod 775 sh01.sh这行命令的意思是,将sh01.sh这个文件的权限更改为-rwxr-xr-x,所以任何人都可以读或者执行这个文件了,而只有文件的拥有者可以写这个文件。

而bash下输入命令,它会去PATH中找文件执行,如果你的当前目录不在PATH中,那就可以用./sh01.sh来执行。“.”代表的是当前目录。好了,下面就贴上几个简单例子。




#!/bin/bash#print 'hello world!' in your screen#author earayu#version 1.0#2015/7/9echo -e "hello world! \a \n"exit 0



#!/bin/bash#input your first name and last name, the programe will print your full name#author earayu#version 1.0read -p 'Please input your first name:' fNameread -p 'Please input your last name:' lNameecho -e "your full name is $fName $lName"


#!/bin/bash#the script will create three files whose names are based on the date#author earayu#version 1.0read -p 'Please input the firstname of the file:' firstnamefirstname=${firstname:-"firstname"}date1=$(date --date='2 days ago' +%Y%m%d)date2=$(date --date='1 days ago' +%Y%m%d)date3=$(date +%Y%m%d)file1=${firstname}$date1file2=${firstname}$date2file3=${firstname}$date3touch "$file1"touch "$file2"touch "$file3"

#!/bin/bash#计算两数字的乘积#author earayu#version 1.0echo -e "Input two numbers and I will cross them!"read -p 'please input a:' aread -p 'please input b:' bdeclare -i adeclare -i bdeclare -i resultresult=$a*$becho "the result of $a*$b is $result"exit 0


#!/bin/bash#check the file or directoryread -p 'Please input the file:' filenametest -e $filename || echo "$filename does not exist" test -f $filename && echo "$filename is regular file"test -d $filename && echo "$filename is directory"test -r $filename && echo "$filename has r"test -w $filename && echo "$filename has w"test -x $filename && echo "$filename has x"

#!/bin/bash#print your identity and your path#author earayu#version 1.0echo 'your ID is :'whoamiecho 'your path is :'pwd

#!/bin/bash#输入一个日期,计算还剩下多少天#author earayu#version 1.0read -p 'Please input a date:' date_1declare -i sec_1=`date --date=$date_1 +%s`declare -i sec_2=`date +%s`declare -i sec=sec_1-sec_2declare -i day=sec/86400echo "${day} left."

#!/bin/bash#输入n,运算1+2+3+...+n#author earayu#version 1.0read -p 'Please input a number:' ndeclare -i result#可替换declare -i i#可替换for ((i=1;i<=n;i++))doresult=result+i#result=$(($result+i))doneecho "the result is :$result"


以后再写shell脚本的话再补充。

1 0