#每日Linux小练习#06 Shell Script知识点总结(上)

(主要内容来源于《鸟哥的Linux私房菜》)正则表达式

【shell script优缺点分析】shell

shell 使用的是外部的命令 与bash shell的一些默认工具,因此,它经常调用外部的函数库,所以,命令周期上面比不上传统的程序语言。bash

因此,Shell Script用在系统管理上面是很的,可是在处理大量数值计算时,速度较慢。函数

 

【shell script编写的注意事项】工具

一、若是一行内容太多,则可使用 \[Enter] 来扩展至下一行测试

二、# 能够做为批注spa

 

【如何执行Script】code

一、直接命令执行(要具备可读可执行的权限)blog

绝对路径,相对路径,变量PATH功能(例如 ~/bin/)进程

二、以bash进程执行

好比bash shell.sh, sh shell.sh, source shell.sh

 

 【熟悉一下Scipt】

echo -e "I will use 'touch' command to create 3 files"
read -p "Please input your filename" fileuser

filename=${fileuser:-"filename"}

date1=$(date --date='2 days ago' +%Y%m%d)
date2=$(date --date='1 days ago' +%Y%m%d)
date3=$(date  +%Y%m%d)

file1=${filename}${date1}
file2=${filename}${date2}
file3=${filename}${date3}

touch "$file1"
touch "$file2"
touch "$file3"

一、read的基本用法

二、date1=$(date --date='2 days ago' +%Y%m%d) ,使用$()中命令取得信息

三、filename=${fileuser:-"filename"}涉及了“变量的测试与内容替换”

 

echo -e  "You should input 2 numbers, I will cross them"
read -p "first number: " firstNumber
read -p "second number: " secondNumber
total=$(($firstNumber*$secondNumber))
echo -e "\n The result of $firstNumber X $secondNumber is ==> $total"

一、var=$((运算内容))

 

【善用判断式】

一、test命令

echo -e "Please input a filename, I will check the filename's type and \
permission.\n\n"
read -p "Input a filename : " filename
test -z $filename &&  echo "You must input a filename." && exit 0
test ! -e $filename && echo "The filename '$filename' do not exist" && exit 0
test -f $filename && filetype="regular file"
test -d $filename && filetype="directory"
test -r $filename && perm="readable"
test -w $filename && perm="$perm writable"
test -x $filename && perm="$perm executable"

echo "The filename:'$filename'  is a $filetype"
echo "And the permissions are : $perm"

二、判断符号[]

利用[]来进行数据的判断。

有如下一些注意点:

1)中括号内的每一个组件都须要有空格键来分隔

因为中括号用在不少地方,包括通配符,正则表达式等,因此若是要在bash的语法中使用中括号做为shell的判断式时,必需要注意中括号两端须要有空格符来分隔。

2)在中括号内的变量,最好都以双引号括起来

3)在中括号内的常量,最好都以单引号或者双引号括起来

关于2,3两点,举个例子

没有加上双引号,就报错了。

由于,$name 会被替换为 wu qi,而后上面的表达式就变为 

[ wu qi == "wu qi"]

天然就会报错“too many arguments”

 

 

【scriptd的默认变量】

$0 执行的脚本文件名
$1 执行的脚本后面紧跟的第一个参数
$2 执行的脚本后面紧跟的第二个参数
$# 执行的脚本后面紧跟的参数的个数(不包括$0)
$@ "$1"、"$2"、"$3",每一个变量是独立的(用双引号括起来)
$* ""$1c$2c$3"",其中c为分隔字符,默认为空格,因此本例中表明""$1 $2 $3""
   

shift:形成参数变量号码偏移

看个例子吧

echo "************************************* "
echo "************************************* "
echo "Show the effect of shift function"
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"
shift
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"
shift 4
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"

相关文章
相关标签/搜索