bash變數類型詳解,bash變數詳解

來源:互聯網
上載者:User

bash變數類型詳解,bash變數詳解

  本地變數:作用於當前shell,對當前shell之外的其他shell進程和當前shell子進程均無效。

  本地變數賦值為

name='value'

  value可以是字串或者是變數,引用變數使用${name}或$name或``.

  註:單引號是強引用而雙引號是弱引用。

[root@izwz9bqngpatc008nw00e7z tmp]# echo '$animal'$animal[root@izwz9bqngpatc008nw00e7z tmp]# echo "$animal"dog[root@izwz9bqngpatc008nw00e7z tmp]# echo "$animals.".[root@izwz9bqngpatc008nw00e7z tmp]# echo "${animal}s."dogs.
[root@izwz9bqngpatc008nw00e7z tmp]# myid = `id -u`-bash: myid: command not found[root@izwz9bqngpatc008nw00e7z tmp]# myid=`id -u`[root@izwz9bqngpatc008nw00e7z tmp]# echo '$myid'$myid[root@izwz9bqngpatc008nw00e7z tmp]# echo "$myid"0
[root@izwz9bqngpatc008nw00e7z tmp]# filename=`date +%F-%H-%M-%S`[root@izwz9bqngpatc008nw00e7z tmp]# echo "$filename"2018-03-19-18-41-21

  使用set顯示已定義的所有變數,unset name 銷毀變數。

  局部變數:生效在shell進程的某段程式碼片段中。

  環境變數:生效在當前shell進程和他的子進程中。

  聲明方式為

export name=valuedeclare -x name=value
[root@izwz9bqngpatc008nw00e7z tmp]# export TES='animal'[root@izwz9bqngpatc008nw00e7z tmp]# echo $TESanimal[root@izwz9bqngpatc008nw00e7z tmp]# declare -x myname='jeffd'[root@izwz9bqngpatc008nw00e7z tmp]# echo $mynamejeffd

  顯示所有環境變數:export,env,printenv。

  銷毀環境變數:unset name。

  不要使用bash內建環境變數。

  唯讀變數:

readonly namedeclare -r name

  位置變數:用於讓指令碼在指令碼代碼中調用通過命令列傳遞給它的參數。

[root@izwz9bqngpatc008nw00e7z tmp]# cat test.sh #!/bin/bashlinecount="$(wc -l $1|cut -d' ' -f1)"echo "$1 has $linecount lines."[root@izwz9bqngpatc008nw00e7z tmp]# chmod +x test.sh [root@izwz9bqngpatc008nw00e7z tmp]# ./test.sh /etc/passwd/etc/passwd has 25 lines.

  特殊變數:$?上一個命令執行狀態的傳回值。

  程式執行可能有兩種傳回值:
  1. 程式執行結果
  2. 程式狀態返回嗎(0-255)
    0 則為執行正確
    1-255 則執行出錯(1,2,127系統預留);

  $#:擷取當前shell命令列中參數的總個數
  $*:擷取當前shell的所有參數 “$1 $2 $3 …,受IFS控制
  $@:這個程式的所有參數 “$1″ “$2″ “$3″ “…”,不受IFS控制
  $0 擷取當前執行的shell指令碼的檔案名稱
  $n 擷取當前執行的shell指令碼的第n個參數值,n=1..9
  $$ 擷取當前shell的進程號(PID)
  $! 執行上一個指令的PID

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.