Shell 腳本中的小技巧

關于變量

一,在shell 腳本中定義默認值

1.   對默認變量直接賦值



read -p "input>>:" nub

nub=${nub:-30}

echo ${nub}

2.   對默認變量用可變值賦值



read -p "input>>:" nub

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

echo ${nub}

$@$* 的區(qū)別

[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  $*)

執(zhí)行測試


[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

看出區(qū)別了嗎?關鍵 $@ 靠譜一點

  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 已經(jīng)沒內容了 

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

這是因為文件 file 這時真的是個空文件。 why???

因為 IO重定向中,標準輸出是要先準備好,才會從標準輸入讀入到標準輸出。是不是有點繞。

就像接力賽中,傳遞接力棒一樣的道理;你沒看到接棒的人,你肯定不會把接力棒送出去一樣。
這里 接棒人就是 輸出即 >, 送棒人就是 輸入 <, 就是把輸入重定向接收的內容,輸出到輸出重定向。
那么,輸出重定向就要先準備好,也就是先被執(zhí)行,執(zhí)行的結果就是把 file 文件清空。

所以, cat <file >file 命令中, > 會先把文件 file 清空,之后 才會執(zhí)行 > file;結果就是空空。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Shell 腳本中的小技巧 關于變量 一,在shell 腳本中定義默認值 [圖片上傳失敗...(image-54c...
    花澤菠菜xqc閱讀 329評論 0 0
  • 官網(wǎng) 中文版本 好的網(wǎng)站 Content-type: text/htmlBASH Section: User ...
    不排版閱讀 4,727評論 0 5
  • 一、Python簡介和環(huán)境搭建以及pip的安裝 4課時實驗課主要內容 【Python簡介】: Python 是一個...
    _小老虎_閱讀 6,352評論 0 10
  • 第 2 章 SHELL 基礎知識2.1 shell腳本我們在上面簡單介紹了一下什么是shell腳本,現(xiàn)在我們來進一...
    LiWei_9e4b閱讀 1,650評論 0 0
  • 建立一個腳本 Linux中有好多中不同的shell,但是通常我們使用bash (bourne again shel...
    某人在閱讀 2,120評論 0 0

友情鏈接更多精彩內容