shell基礎 變數

2022-07-03 22:36:12 字數 3164 閱讀 6911

變數的賦值

#定義變數,注意等號兩邊沒有任何空格

variable=

#定義環境變數

export variable=

#雙引號:可含空格、可轉義特殊字元

variable="

"

#$() 或 反引號:將命令結果賦值給變數

variable=$( )

variable=` `

#將變數值賦值給變數

gg=$aa$bb

變數的取值

#取值

$variable

#標準寫法,建議使用此方法
$ 

#示例:

#day=sunday

#echo

$day

sunday

# echo

"hello sunday

">$day_file.txt

# ls

# echo

"hello sunday

">$_file.txt

# ls

sunday_file.txt

變數的取消與檢視

#unset:取消變數和函式

unset variable

unset function

#env

檢視系統所有的環境變數

#set 檢視所有的系統預設變數+使用者自定義變數

區域性變數/使用者變數區域性變數:只在當前的shell中有效;

使用者變數:針對與當前使用者有效, .bashrc 下可以檢視。

全域性變數/環境變數

當前建立變數的shell即為父shell,全域性變數可以從父shell傳遞到子shell、孫shell···

注意環境變數只能向下傳遞而不能向上傳遞。

一些常見的預設變數(可通過 man bash檢視):

#變數bash:顯示當前的bash shell

[root@localhost shell]#

echo

$bash

/bin/bash

#變數bash_version:顯示當前bash shell版本

[root@localhost shell]#

echo

$bash_version

4.1.2(1)-release

#變數hostname:主機名

[root@txy_host test]#

echo

$hostname

txy_host

#變數hosttype:主機架構

[root@txy_host test]#

echo

$hosttype

x86_64

#變數machtype:主機型別的gnu標識

[root@txy_host test]#

echo

$machtype

x86_64-redhat-linux-gnu

#變數lang:系統的語言環境

[root@txy_host test]#

echo

$lang

c#設定語言環境為中文

# export lang=zh_cn.utf-8

#變數pwd:當前目錄

[root@txy_host test]#

echo

$pwd

/shell/test

#變數oldpwd:上一次訪問目錄

[root@txy_host test]#

echo

$oldpwd

/shell

#變數euid:顯示當前使用者的uid

[root@localhost ~]# echo

$euid

0#變數cdpath:可以快速進入此目錄

#cd時會首先檢視當前目錄是否有network-scripts,若沒有則進入cdpath定義的目錄

[root@localhost shell]# cdpath="

/etc/sysconfig

"[root@localhost shell]# cd network-scripts

/etc/sysconfig/network-scripts

#變數funcname:用在函式內,顯示當前函式名

[root@txy_host test]#

cat funcname.sh

#/bin/bash

funcname()

funcname

[root@txy_host test]# bash funcname.

shfuncname

特殊變數1.位置引數$0:預留儲存實際指令碼名字;無論指令碼是否有引數,此值均可用。

$1-$9:第1—9個引數

$:位置引數大於9後的表示方法

$#:指令碼引數的個數總和

$*/$@:表示指令碼的所有引數

2. 特定的變數引數

$!   shell最後執行的後台process的pid  

$-   顯示shell使用的當前選項,與set命令功能相同

$$   指令碼執行的當前程序id號

# cat aatest.sh

#!/bin/bash

echo $$

# ./aatest.sh

3520

3.命令返回值執行一條命令後,

$? 值為0表示執行成功,非0則表示執行失敗。 

Shell 基礎 shell 變數

變數中只能包含字母 數字 下劃線,不能以數字開頭 不能包含bash中的關鍵字 變數賦值時,變數和等號 之間不能有空格 yourname abc 注意變數和 之間不能有空格 使用變數時,需要在變數前加 使用 youname或 例子 新建檔案,檔案內容如下 yourname lisen 變數賦值 ech...

Shell基礎 變數

name value declare name value bash裡的變數不僅有值,還有屬性。declare命令可以給變數設定屬性。declare i abc 123 給變數abc賦予integer屬性宣告變數時,如果沒有提供value,變數的值為null 變數宣告後,只能通過unset命令刪除 ...

shell基礎 shell特殊變數

一.變數列表 二.實驗 系統 centos 7 1.特殊變數 root day2 cat p.sh bin bash echo 0 0 echo echo echo echo 1 2 3 1 2 3 root day2 sh p.sh a b c d 0 p.sh a b c d a b c d 4...