Linux Shell 備忘 筆記

1. 輸出重定向

文件描述符 含義
0 輸入STDIN
1 標準輸出 STDOUT
2 標準錯誤 STDERR

0,1,2 爲內置描述符,3-9爲保留自定義描述符

文件描述符 含義
> 將命令輸出寫入到文件或設備(如打印機),而不是命令提示符窗口或句柄。
< 從文件而不是從鍵盤或句柄讀入命令輸入。
>> 將命令輸出添加到文件末尾而不刪除文件中已有的信息。
>& 將一個句柄的輸出寫入到另一個句柄的輸入中。
<& 從一個句柄讀取輸入並將其寫入到另一個句柄輸出中。
| 從一個命令中讀取輸出並將其寫入另一個命令的輸入中。也稱作管道。
# 臨時重定向
echo "Test" >&1 #標準輸出
echo "Error" >&2 #標準錯誤
# 永久重定向 
exec 0<testfile.txt
exec 1>logfile.txt
exec 2>error.txt

2. 函數退出碼:

code 含義
0 命令成功結束
1 一般性未知錯誤
2 不適合的Shell命令
126 命令不可執行
127 沒有找到命令
128 無效的退出參數
128+x 與Linux信號x相關的嚴重錯誤
130 通過Ctrl+C終止的命令
255 正常範圍外的退出狀態碼

3. 結構化命令

#----------------
if [ command ]
then
	commands 
fi
#-----------------
if [ command ]
then 
	commands
else 
	commands
fi
#-----------------
if [ command ]
then 
	commands
elif [ command ]
then 
	commands
fi
#test指令

# 字符串比較
# str1 = str2
# str1 != str2
# str1 < str2
# str1 > str2
# -n str1		長度是否非0
# -z str1		長度是否爲0
# 數值比較
# n1 -eq n2 	檢查n1與n2相等
# n1 -ge n2 	n1是否大於或等於n2
# n1 -gt n2 	n1是否大於n2
# n1 -le n2		n1是否小於等於n2
# n1 -lt n2 	n1是否小於n2
# n1 -ne n2	 	n1是否不等於n2
# 文件比較
# -d file	是否一個目錄
# -e file 	是否存在
# -f file	是否存在並且是一個文件
# -r file	是否存在並可讀
# -s file	是否存在並非空
# -w file	是否存在並可寫
# -x file	是否存在並可執行
# -O file	是否存在並歸屬當前用戶	
# -G file	是否存在並歸屬當前組
# file1 -nt file2	file1是否比file2新
# file1 -ot file2	file1是否比file2舊
#-----------------
if test condition
fi
if [ condition ]
then 
fi
#-----------------
if [ condition1 ] && [ condition2 ]
if [ condition1 ] || [ condition2 ]
if (( xxxx )) 數學表達式
if [[ xxx ]] 可使用字符串的模式匹配 
#-----------------
case $val in
val1)
 	commands;;
val2)
	commands;;
*)
	commands;;
esac;
#-----------------
for a in xxx
do 
done 
for (( i=0;i<10;i++ ))
do
done
#-----------------
# 多個測試命令以最後一個命令爲最後返回值
while test command
do 
	commands
done
#-----------------
until test command
do
	commands
done
#-----------------
break x#跳出的層數
#-----------------
continue

4. #相關

標記 說明
$# 命令數字
$@ 所有參數 分隔
$* 所有參數 一個整體

5. 環境變量

  • 全局環境變量
printenv
env $VAR
  • 局部環境變量
set 
unset
  • Shell環境變量(按照加載順序)

    • /etc/profile
    • /etc/bashrc(部分系統有)
    • $HOME/.bash_profile
    • $HOME/.bashrc
    • $HOME/.bash_login
    • $HOME/.profile

bashrc和profile.d文件夾下面的文件一般通過profile文件進行加載

6.Shell 文件相關

文件頭指定的爲默認執行程序。eg.

1. #!/bin/bash
2. #!/usr/bin/bash
3. #/usr/bin/python

7. 浮點數解決方案

bc
var1=$(echo "scale=4; 3.44 / 5" | bc)

8. sed

流式文件編輯器

9. gawk

對Sed編輯器的一個封裝版本

10.常用命令

# file
cp
mv 
ls
ln
cat
less
more
tail
head
# user
useradd
userdel
usermod
groupadd
groupdel
groupmod
# permission
chmod
passwd
su
sudo
# program
nohup
systemctl
service
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章