script
do not want to type codes every time, want to be efficient, want to be lazy,then just use script to handle repetitive tasks.
what is script in linux?
it is just like script in theatrical situation,actor does what script told them,and the same computer does the script told them.
how to use script?
easy example 1:
#!/usr/bin/bash
#the first example
#Asha 2017/4/17
echo hello world.
the first two characters #! is called shebang, it tells computer where to find and use bash which is the interpreter. if we do not use it, our shell will use the shell we currently using.
the # character in the second line, it tells system the something after that is just a comment,so system will not show and run it.
the third line,we just recommend to write down who and when you create the script.
easy example 2:
#!/usr/bin/bash
#the second example
#Asha 2017/4/17
creator='asha'
echo the script name is $0, $creator creates it,and we have $# command line arguments.
echo they are $*.
echo the third command line argument is $3.
here we introduce the variable,there are two type variables here,one is created by us,and another is created by the system.here we have to notice that do not put any space in the equals sign when you create the variable.
$0 contains the script name;
$1-$9 contains the command line arguments,starts from 1;
$# contains how many command line arguments;
$* contains every value of command line arguments;
easy example 3:
#!/usr/bin/bash
#the third example
#Asha 2017/4/17
inside_directory=`ls $1`
echo we have $inside_direcory inside this directory.
here we use a tick ` character, we use it to give the result from command line to a variable.
easy example 4:
#!/usr/bin/bash
#the fourth example
#Asha 2017/4/17
date=`date +%F`
mkdir ~/logs_$date
cp ~/logs ~/logs_$date
echo copy from logs to logs_$date is done
easy example 5:
#!/usr/bin/bash
#the fifth example
#Asha 2017/4/17
if [ $# != 1]
then
echo you should have the directory to be copied.
exit
fi
if [ ! -d ~/logs/$1 ]
then
echo the directory is not existed.
exit
fi
date=`date +%F`
if [ -d ~/logs/$1_$date ]
then
echo you already have backup tody,are you sure to overide it?
read answer
if [ ! $answer == 'y' ]
then
exit
fi
else
mkdir ~/logs/$1_$date
fi
cp -r ~/logs/$1 ~/logs/$1_$date
echo we have backuped the $1 directory.