Linux Shell程式設計 變數

2021-09-12 03:06:02 字數 2924 閱讀 3098

變數即在程式執行過程中他的值是允許改變的量

變數是用一串固定的字元來表示不固定的值的一種方法

變數是一種使用方便的佔位符,用於引用計算機記憶體位址,該位址可以儲存 script 執行的時可更改的程式資訊

在 shell 中變數是不可能永久儲存在系統中的,必須在檔案中宣告

1.環境級變數

只在當前的shell種生效,shell 關閉則變數丟失

定義方法:

export a=1

2.使用者級變數

寫在使用者的骨檔案中,只針對當前使用者生效

定義方法:

vim ~/.bash_profile

export a=1

3.系統級變數

系統級變數被寫在系統的配置檔案 /etc/profile或者 /etc/profile.d/ 中,對所有的使用者都生效

定義方法:

vim /etc/profile

export a=1

或者cd /etc/profile.d/

vim westos.sh

#!/bin/bash

export a=1

變數名稱中通常包含大小寫字母,數字,下劃線(不是必須的)

變數名稱的格式

westos_linux

westos_linux

westos_linux

\轉譯單個字元

""弱引用,批量轉譯 " " **現的字元

''強引用,批量轉譯 』 』 **現的字元(原樣輸出)

''""的區別:""不能轉譯"\""反向單引號""!""$""?"

${}變數的宣告

$1指令碼後的第1串字串

$2指令碼後的第2串字串

$0獲取shell指令碼檔名,如果執行時包含指令碼路徑,則輸出指令碼路徑

$#指令碼後所跟字串的個數

$*指令碼後跟的所有字串,模式為"1 2 3"

$@指令碼後跟的所有字串,模式為 " 1 " " 2 " " 3 "

$?是命令在執行完成後產生的退出值;範圍[0-255],為0表示沒有錯誤輸出(exit可以設定退出值)

$$獲取當前shell的程序號

[root@shellexample mnt]# read westos

westos hello

[root@shellexample mnt]# echo $westos

westos hello

[root@shellexample mnt]# read -p "input:" i

input:10

[root@shellexample mnt]# echo $i

10

alias xie='vim'
vim ~/.bashrc

alias xie='vim'

vim /etc/bashrc

alias xie='vim'

unalias xie

擴充:

`` 與 $( ) 的區別

[root@shellexample mnt]# export a=`hostname`

[root@shellexample mnt]# echo $a

shellexample.westos.com

[root@shellexample mnt]# export a=$(hostname)

[root@shellexample mnt]# echo $a

shellexample.westos.com

反向單引號是通用的; $( )不通用

yum install perl

[root@shellexample mnt]# vim test1

#!/usr/bin/perl

print `date`

[root@shellexample mnt]# chmod +x test1

[root@shellexample mnt]# /mnt/test1

thu mar 7 01:17:26 est 2019

[root@shellexample mnt]# vim test2

#!/usr/bin/perl

print $(date)

[root@shellexample mnt]# chmod +x test2

[root@shellexample mnt]# /mnt/test2

bareword found where operator expected at /mnt/test2 line 2, near "$(date"

(missing operator before date?)

syntax error at /mnt/test2 line 2, near "date)

"execution of /mnt/test2 aborted due to compilation errors.

Linux shell程式設計 變數

bash主要的變數型別有 使用者自定義變數 環境變數 位置引數變數 預定義變數 1.使用者自定義變數 linux中預設的變數都是字串型 注意 變數賦值時,前後不能有空格 root hadoop200 x 1 root hadoop200 y 2 root hadoop200 echo x y 1 2...

Linux Shell程式設計的特殊變數

特殊變數 0 正在被執行命令的名字。對於shell指令碼而言,這是被啟用命令的路徑 n 該變數與指令碼被啟用時所帶的引數相對應。n是正整數,與引數位置相對應 1,2.提供指令碼的引數號 所有這些引數都被雙引號引住。若乙個指令碼接收兩個引數,等於 1 2 所有這些引數都分別被雙引號引住。若乙個指令碼接...

Linux shell程式設計之bash變數

bash變數 命名規則 必須以字母下劃線開頭,只能由字母下劃線數字組成。長度不能超過255個字元 變數名在有效的範圍內必須唯一 在bash中,變數的預設型別都是字串 一 使用者自定義變數 使用者自定義的變數。區域性變數,只在當前shell有效。格式 變數名 變數值 例如 x 5 等號兩邊不能有空格 ...