您的位置:首页 > 运维架构 > Shell

Ubuntu--(3)shell快速入门

2016-10-10 21:42 204 查看

运行shell文件方法

sh -x script_name       //将执行脚本并显示所有变量的值
sh -n script_name       //不执行脚本,只检查语法
sh -v script_name       //执行脚本前把脚本内容显示在屏幕上
sh script-file          //这个好像会有问题
./script-file


变量运算

a=10
b=20
echo $(($a+$b))
echo ((3**2))


数字比较选项

test int_num1 option int_num2

或者

if [ int_num1 option int_num2 ]

-eq         //equal相等返回真
-ne         //not equal不等返回真
-lt         //lower than小于返回真
-le         //lower or equal小于或者等于
-gt         //greater than大于等于
-ge         //greater of equal大于等于返回真


定义数组

declare [-afirx]
-a          //定义数组
-f          //定义函数
-i          //定义整数
-r          //定义为只读
declare -a myarry=(5 6 7 8)
echo ${myarry[2]}


字符串运算:

${#string}					//$string的长度
${string:position}			//$position开始提取字符串
${string:position:length}	//$从位置position开始提取长度为$length的子串
${string#substring}			//$从开始删除最短匹配子串
${string##substring}		//$从开始删除最长匹配子串
${string%substring}			//$从结尾删除最短匹配子串
${string%%substring}		//$从结尾删除最长匹配子串


与字符串比较有关的选项

if [ -z "$str1" ]
-z str              //当字符串str长度为0时返回真
-n str              //当字符串str长度大于0时返回真
str1=str2           //当字串str1与str2相等时返回真
str1!-str2          //当字符串str1与str2不等时返回真


test判断

-f                  //文件是否存在
-d                  //目录是否存在
-r                  //文件是否有读权限
-w                  //文件是否有写权限
-x                  //文件是否有执行权限


例如:

test -f $filename && echo 'exist'||echo 'not exist'
test -d $filename && echo 'exist'||echo 'not exist'
test -r $filename && echo 'exist'||echo 'not exist'
test -w $filename && echo 'exist'||echo 'not exist'
test -x $filename && echo 'exist'||echo 'not exist'


用于文件测试的test选项

if [ -x /file1 ]

-b file             //当文件是块设备时返回真
-c file             //当文件是字符设备时返回真
-d pathname         //当pathname是下一个目录时返回真
-e pathname         //当指定的文件或者目录存在时返回真
-f file             //当file为常规文件(不包括符号链接、管道、目录等)返回真
-g pathname         //当pathname指定的文件或者目录设置了SGID位时返回真
-h file             //当file是符号链接时返回真
-p file             //当file是命名管道时返回真
-r pathname         //当pathname抒写的文件或者目录是可读时返回真
-s file             //当file存在且当大小为0时返回真
-u pathname         //当pathname指定...设定了SUID位时返回真
-w pathname         //当pathname指定...文件可写时返回真
-x pathname         //当pathname指定...文件可执行时返回真
-o pathname         //当pathname指定...文件被当前用户拥有时返回真


[]判断

在中括号中必须都要使用空格来分隔

在中括号中的变量,最好都要双引号括起来

在中括号中的常数,最好都以单引号括起来

[ '$a' == '$b' ] && echo 'Yes' || echo "No"
[ '12' == '10' ] && echo 'Yes' || echo "No"
[ '12' != '10' ] && echo 'Yes' || echo
4000
"No"


单分支判断

if[]; then
echo statement
fi


双分支判断

if[]; then
echo statement
else
echo statement
fi


多分支判断

if[]; then
echo statement
elif
echo statement
elif
echo statement
fi


case多分支

case $name in
1)
echo statement;;
2)
echo statement;;
*)
echo statement;;
esac


循环

while condition; do
statement
done;


例如:

i=10
while (($i>=5)); do
echo $i;
((i--));
done;


建议下面的用[]

i=10
while [ $i -gt 5 ]; do
echo $i;
((i--));
done;


until

until condition; do
statement
done;


例如:

a=10
until (($a<0)); do
echo $a;
((a--));
done


建议下面的用[]

i=10
until [ $i -lt 1 ]; do
echo $i;
((i--))
done;


for

for(()); do
statement
done;


例如:

for ((i=0; i<10; i++)); do
echo $i
done;


函数

例子:

function print(){
echo "Your input is $1"
}

echo "this program will print your selection!"
case $1 in
"one")
print 1;;
"two")
print 2;;
"three")
print 3;;
*)
print "Usage $0 (one|two|three)";;
esac


运行方法,要传入参数:

./shell_example one

echo $SHELL 看当前所用shell
$#     传递到脚本的参数个数
$*     传递到脚本的参数,与位置变量不同,此选项参数可超过9个
$$        脚本运行时当前进程的ID号,常用作临时变量的后缀
$!     后台运行的(&)最后一个进程的ID号
$@     与$#相同,使用时加引号,并在引号中返回参数个数
$-     上一个命令的最后一个参数
$?     最后命令的退出状态,0表示没有错误,其他任何值表明有错误


逻辑操作符

-a      逻辑与
-o      逻辑或
!       逻辑非


例子: [ -r shell.c –a –w test.c ]

Example

#! /bin/bash
#display the message "hello world!"

echo "hello world!"

echo "下面定义变量:"
log="monday"
echo "the value of logfile is: " $log
echo "可以直接放在双引号内部:$log"

echo "下面面展示位置参数:"
echo "\$0 = ** $0 **"
echo "\$1 = ** $1 **"
echo "\$2 = ** $2 **"
echo "\$3 = ** $3 **"
echo "\$4 = ** $4 **"

echo "显示有多少文件需要列出"
echo "$# file(s) to list"

echo "\$# 包含参数的个数 $#"
echo "将参数列表的值逐一付给变量file"
echo "\$@ 包含参数列表"
for file in $@
do
ls -l $file
done

echo "\$* 包含参数列表"
for file in $*
do
ls -l $file
done

echo "双引号阻止Shell对大多数特殊字符的解释,\$ \`除外"
echo '单引号阻止Shell对所有字符解释 $log'
echo "倒引号括住的命令会被执行,并将执行结果当作表达式的值:" `date`

num=1;
echo "表达式求值:" $num=$[$num+3]
echo $[(7 + 8) / (6 - 3)]
echo $num = $[1 + 2]
echo "\$[2#10 + 1] = 3 " $[2#10 + 1]
echo "\$[16#10 + 1] = 17 " $[16#10 + 1]
echo "\$[8#10 + 1] = 9 " $[8#10 + 1]
echo "expr 运算符:"
expr 1 + 2


Example:

#! /bin/bash

echo "please be attention to the use of hte blankspace:"
password="join"
test "$password" = "join"
[ "$password" = "join" ]

echo "为字符串变量加上一个双引号是一个好习惯"
echo "Shell对字符区分大小写"
echo "please input a test password:"
read password
if [ -z "$password" ]
then
echo "the length of the password you input is 0"
fi

echo "test FOR:"
for i in 1 2 3 4 5
do
echo $i
done

echo "注意这里的符号,不是单引号,是Esc键下面的那个"
for i in `seq 5`
do
echo $i
done


Example:

#! /bin/bash

sum=0
number=1
while test $number -le 100
do
sum=$[ $sum + $number ]
let number=$number+1
done
echo "the sum is $sum"


Example:

#! /bin/bash

echo -n "Enter a number(>0):"
while read n
do
sum=0
count=0

if [ $n -gt 0 ]
then
while [ $count -le $n ]
do
sum=$[ $sum + $count ]
let count=$count+1
done
echo "the sum is $sum"
else
echo "please input a number greater than zero"
fi

echo -n "Enter a number(>0):"
done


Example:

#! /bin/bash

sum=0
number=1

until ! test $number -le 100
do
sum=$[ $sum + $number ]
let number=$number+1
done
echo "the sum is $sum"


统计当前目录下文件的个数

#! /bin/bash

count=0

for file in `ls`
do
if ! [ -d $file ]
then
let count=$count+1
fi
done
echo "there are $count files"


脚本执行命令

exit 强行退出一个脚本

Eample:捕获INT信号,并显示信息提示用户怎样退出程序

#! /bin/bash

trap `echo "type quit to exit"` INT
while [ "$input" != 'quit' ]
do
read input
done


Eample:捕获EXIT信号退出时输出Goodbye

#! /bin/bash

trap `echo "Goodbye"; exit· EXIT

echo "Type 'quit' to exit"
while [ "$input" != "quit" ]
do
read input
done


命令表

可以用一个命令的退出值来控制是否执行另一条命令

a&&b        //与命令表,当且仅当a执行成功才执行b
a||b        //或命令表,当且仅当a执行失败才执行b
a;b         //顺序命令表,先执行a,再执行b


cut命令以特定的方式分割行,并输出特定的部分Example:

city.txt文件内容如下:

Beijing010
Shanghai021
Tianjin022
Hangzhou0571


对文件city.txt取每行的第3到6个字符前输出

$ cut -c 3-6 city.txt


-f选项提取行中指定的字段,字段间的分割符由-d选项指定,默认分割符为Tab键,下面提取city.txt第二字段

$ cut -f 2 city.txt


diff命令确定两个版本的源文件存在哪些修改,Example:

city2.txt内容如下

Beijing011
Shanghai021
Tianjin022
HangZhou0571


判断city1.txt与city2.txt的修改

$ diff city.txt city2.txt


sort 命令对输入以字母排序,Example:

$ sort city.txt
$ sort -r city.txt //以字母逆序排序
$ sort -k 2 -r city.txt//指定按字段,默认第一个字段


uniq 命令从已经排好序的输入中删除重复行,Example:

$ sort city.txt | uniq


tr 命令按用户指定的方式对字符执行替换,Example:

alph.txt文件内容如下:

HCC DEF GAI
jkl mno pqr
StU vwx yz
12A Cft pOd
Hct Yoz cc4


$ tr "ABH" "HCA" < alph.txt    //将所有的:A->H, B->C, H->A
$ tr "ABC" "[Z*]" < alph.txt   //将所有ABC替换为Z
$ tr --delete " " < alph.txt   //删除所有空格


wc命令用来统计文件中字节、单词以及行的数量,Example:

$ wc city.txt


substr命令提取字符串中的一部分,三个参数,原始串,开始位置,字符数 ,Example:

$ expr substr "hello world!" 1 7


seq命令用于生成下一个整数序列,Example:

$ seq 5
$ seq -1 3
$ seq 9 -3 0


定制安全的delete命令

##建立回收机制
##将需要删除的文件移动到~/.trash中
##分三步完成:a>在用户主目录下添加.trash目录,用作回收站
##          b>在每次删除文件或者目录时向用户确认
##          c>在需要删除的目录或者文件移动到~/./trash中
#! /bin/bash

if [ ! -d ~/.trash ]
then
mkdir ~/.trash
fi

if [ $# -eq 0 ]
then
# 提示信息
echo "Usage:delete file1 [file2, file3 ...]"
else
echo "you are about to delete these files:"
echo $@

# 要求用户是否确认删除
echo -n "are u sure to do that? [y/n]:"
read reply

if [ "$reply" != "n" ] && [ "$reply" != "N" ]
then
for file in $@
do
# 判断文件或者目录是否存在
if [ -f "$file" ] || [ -d "$file" ]
then
mv -b "$file" ~/.trash/
else
echo "$file: no such file or directory"
fi
done
# 如果回答N或者n
else
echo "no file removed"
fi
fi
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell快速入门