Shell 脚本中的小技巧

作者: 运维开发_西瓜甜 | 来源:发表于2019-03-07 11:20 被阅读40次

关于变量

一,在shell 脚本中定义默认值

1.   对默认变量直接赋值



read -p "input>>:" nub

nub=${nub:-30}

echo ${nub}

2.   对默认变量用可变值赋值



read -p "input>>:" nub

nub=${nub:-$(date +%Y%m%d)}

echo ${nub}

@和*的区别

[lf@x201t~]$vim my_fun.sh

#!/bin/bash

# $@ and $* 

my_fun (){

    echo "$#"

}

echo 'the number of parameter in "$@"   is'    $(my_fun  "$@")

echo 'the number of parameter in $@      is'    $(my_fun  $@)

echo 'the number of parameter in "$*"     is'     $(my_fun  "$*")

echo 'the number of parameter in $*        is'     $(my_fun  $*)

执行测试


[lf@x201t ~]$ sh a.sh p1 "p2 p3" p4

the number of parameter in "$@" is 3  

the number of parameter in $@ is 4

the number of parameter in "$*" is 1

the number of parameter in $* is 4

看出区别了吗?关键 $@ 靠谱一点

  1. 关于 > 和 <
[lf@x201t ~]$ cat     <file     >file.bak

[lf@x201t ~]$ cat   file;cat   file.bak 

this is a test

this is a test

[lf@x201t ~]$ cat    <file       >file

[lf@x201t ~]$ cat    file

[lf@x201t ~]$                            =====> 这行输出是空的,文件  file 已经没内容了 

为什么在最后 cat 看不到 file 文件的内容了呢?

这是因为文件 file 这时真的是个空文件。 why???

因为 IO重定向中,标准输出是要先准备好,才会从标准输入读入到标准输出。是不是有点绕。

就像接力赛中,传递接力棒一样的道理;你没看到接棒的人,你肯定不会把接力棒送出去一样。

所以, cat <file >file 命令中, > 会先把文件 file 清空,之后 才会执行 > file;结果就是空空。

  1. for 循环中 变量的取值方式

a. 从一组字符串中取值

for  var     in    one    two    three   four   five 

    do

         echo    ****************************

         echo   '$var   is '    $var

done

b. 从位置变量中取值

for    var;do

    do

         echo  '-----------------------------'

         echo   '$var   is '    $var

    done

c. 从累计变化的格式中取值

#!/bin/bash 

for    ((var=1;var<=10;var++))

do

         echo   ------------------------ 

        echo   '$var   is '    $var

done

d. 从命令结果中取值

#!/bin/bash

  for   var   in   $(cat    file.txt)

  do

       echo   ------------------------ 

       echo   '$var   is '    $var

 done

相关文章

网友评论

    本文标题:Shell 脚本中的小技巧

    本文链接:https://www.haomeiwen.com/subject/zlgguqtx.html