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

(主要内容来源于《鸟哥的Linux私房菜》)

【shell script优缺点分析】

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

所以,Shell Script用在系统管理上面是很的,但是在处理大量数值计算时,速度较慢。

【shell script编写的注意事项】

1、如果一行内容太多,则可以使用 [Enter] 来扩展至下一行

2、# 可以作为批注

【如何执行Script】

1、直接命令执行(要具有可读可执行的权限)

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

2、以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"

1、read的基本用法

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

3、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 "
 The result of $firstNumber X $secondNumber is ==> $total"

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

【善用判断式】

1、test命令

echo -e "Please input a filename, I will check the filename's type and 
permission.

"
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"

2、判断符号[]

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

有以下一些注意点:

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 ==> '$@'"

原文地址:https://www.cnblogs.com/wuqi/p/4713088.html