linux下shell的基本知识 ~~~~~执行方法,变量 ,$后面加不同参数,read用法

什么是shell?

什么是shell脚本

如何查看系统的默认shell?(企业面试题)

1:echo $SHELL

2:   grep root /etc/passwd

shell脚本的建立

####脚本执行方法#####
1.sh script.sh | bash script.sh ##没有执行权限时

2.path/script.sh | ./script.sh  ##绝对路径,当前目录下,前体是给了执行权限



3.source script.sh | . script.sh    ##这种方式会使用source或.号来读如指定shell文件,并会把其他shell中的变量值或函数返回给父shell继续使用

脚本开发规范

实例:

####定义变量####
[root@server ~]# a=hello
[root@server ~]# echo $a

         hello
[root@server ~]# b='hello'
[root@server ~]# echo $b
 
         hello
[root@server ~]# c="hello"
[root@server ~]# echo $c

          hello

      对于单个字符无影响
[root@server ~]# a=westos-$a
[root@server ~]# echo $a

          westos-hello 
[root@server ~]# b='westos-$a'
[root@server ~]# echo $b

          westos-$a  原样输出不会解析$b
[root@server ~]# c="westos-$a"
[root@server ~]# echo $c

           westos-westos-hello           
[root@server ~]# a="westos hello"
[root@server ~]# echo $a

          westos hello  
       

注意:建议没有特别要求时,字符串都加双引号,需要原样输出就加单引号

####特殊变量####

$0:获取脚本文件名(如果执行时包含路径,则输出脚本路径,这种情况就要给脚本执行权限,才能用路径的方式执行脚本)


$n(>0): 输出变量值

[root@server mnt]# cat westos.sh
          #!/bin/bash
          echo $1 $2
[root@server mnt]# sh westos.sh hello westos
         hello westos
[root@server mnt]# sh westos.sh hello redhat
          hello redhat

[root@server mnt]# echo \${1..10} > westos.sh
[root@server mnt]# cat westos.sh
             $1 $2 $3 $4 $5 $6 $7 $8 $9 $10
[root@server mnt]# sh westos.sh  {1..10}
             1 2 3 4 5 6 7 8 9 10
[root@server mnt]# sh westos.sh  {a..z}
             a b c d e f g h i a0

[root@server mnt]# sh westos.sh  {a..z}      //需要将10看出一个整体,否则脚本在执行时会默认为$1和0,就会出现上面的错误的结果
             a b c d e f g h i j

$#: 统计变量的个数


$*:
$@:

$?  : 表示上条命令执行结果的返回值, 0表示执行成功,非0表示执行失败

判断上条命令是否正确

 

read用法:通常写在脚本里用来让用户输入

将命令的结果赋值给变量: 

练习:打包日志,要求显示打包时间为当天,当然写在脚本中也是可以的

tar zcf log_$(data +%F).tar.gz /var/log

猜你喜欢

转载自blog.csdn.net/yinzhen_boke_0321/article/details/85238220