看了几天的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/9
echo -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.0
read -p 'Please input your first name:' fName
read -p 'Please input your last name:' lName
echo -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.0
read -p 'Please input the firstname of the file:' firstname
firstname=${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}$date1
file2=${firstname}$date2
file3=${firstname}$date3
touch "$file1"
touch "$file2"
touch "$file3"
#!/bin/bash
#计算两数字的乘积
#author earayu
#version 1.0
echo -e "Input two numbers and I will cross them!"
read -p 'please input a:' a
read -p 'please input b:' b
declare -i a
declare -i b
declare -i result
result=$a*$b
echo "the result of $a*$b is $result"
exit 0
#!/bin/bash
#check the file or directory
read -p 'Please input the file:' filename
test -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.0
echo 'your ID is :'
whoami
echo 'your path is :'
pwd
#!/bin/bash
#输入一个日期,计算还剩下多少天
#author earayu
#version 1.0
read -p 'Please input a date:' date_1
declare -i sec_1=`date --date=$date_1 +%s`
declare -i sec_2=`date +%s`
declare -i sec=sec_1-sec_2
declare -i day=sec/86400
echo "${day} left."
#!/bin/bash
#输入n,运算1+2+3+...+n
#author earayu
#version 1.0
read -p 'Please input a number:' n
declare -i result
#可替换
declare -i i
#可替换
for ((i=1;i<=n;i++))
do
result=result+i
#result=$(($result+i))
done
echo "the result is :$result"
以后再写shell脚本的话再补充。