一、基本參數
1、-f參數:指定Shell腳本文件名
#!/bin/bash echo "Hello World"
執行:./test.sh
輸出:Hello World
2、-n參數:不執行腳本內容,用於檢查語法錯誤
#!/bin/bash -n echo "Hello World"
執行:./test.sh
輸出:無,因為腳本沒有實際執行。
3、-x參數:列印執行的每一條命令及結果
#!/bin/bash -x ls pwd
執行:./test.sh
輸出:
ls
file1 file2
pwd
/home/user/test
二、標準輸入輸出參數
1、重定向標準輸出到文件
#!/bin/bash echo "Hello World" > output.txt
執行:./test.sh
輸出:output.txt文件中包含字元串”Hello World”
2、從文件中讀取輸入
#!/bin/bash read name echo "Hello $name"
執行:./test.sh \< input.txt
輸入:John
輸出:Hello John
3、將命令的標準輸出重定向到標準錯誤輸出
#!/bin/bash ls /fake/dir 2>&1 >&2
執行:./test.sh
輸出:ls: cannot access ‘/fake/dir’: No such file or directory
三、參數替換
1、${var}替換成變數var的值
#!/bin/bash var="World" echo "Hello ${var}"
執行:./test.sh
輸出:Hello World
2、${var:-default}如果var未定義,則使用默認值default
#!/bin/bash echo "Hello ${var:-World}"
執行:./test.sh
輸出:Hello World
3、${var:=default}如果var未定義,則設置為默認值default
#!/bin/bash echo "Hello ${var:=World}" echo "var is now set to $var"
執行:./test.sh
輸出:
Hello World
var is now set to World
4、${var:+othervalue}如果變數var被設置,則使用othervalue
#!/bin/bash var="Hello" echo "${var:+World}" echo "${var:+Everyone}"
執行:./test.sh
輸出:
World
Everyone
四、通配符
1、*匹配任意長度的任何內容
#!/bin/bash for file in * do echo "$file" done
執行:./test.sh
輸出:當前目錄下的所有文件和目錄名稱
2、?匹配一個字元
#!/bin/bash ls ????
執行:./test.sh
輸出:列出4個字元長的文件名
3、[]匹配中括弧中任意一個字元
#!/bin/bash ls [abc]*
執行:./test.sh
輸出:列出以a、b、c開頭的文件名
五、管道
1、將ls命令的輸出通過管道符號發送給grep命令,用於搜索:
#!/bin/bash ls | grep "file"
執行:./test.sh
輸出:列出所有文件名中包含”file”的文件
2、將ping命令的輸出通過管道符號發送給awk命令,用於處理:
#!/bin/bash ping -c 3 www.google.com | awk '/^rtt/ { print $4 }'
執行:./test.sh
輸出:ping的三次響應時間
六、條件語句
1、if語句
#!/bin/bash if [ -f file.txt ] then echo "file.txt exists" else echo "file.txt does not exist" fi
執行:./test.sh
輸出:如果當前目錄下存在file.txt文件,則輸出”file.txt exists”,否則輸出”file.txt does not exist”
2、case語句
#!/bin/bash echo "Enter a number between 1 and 3: " read num case $num in 1) echo "You entered 1" ;; 2) echo "You entered 2" ;; 3) echo "You entered 3" ;; *) echo "Invalid input" ;; esac
執行:./test.sh
輸入:2
輸出:You entered 2
七、循環語句
1、for循環
#!/bin/bash for i in {1..5} do echo "Count: $i" done
執行:./test.sh
輸出:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
2、while循環
#!/bin/bash i=5 while [ $i -gt 0 ] do echo "Count: $i" i=$((i - 1)) done
執行:./test.sh
輸出:
Count: 5
Count: 4
Count: 3
Count: 2
Count: 1
3、until循環
#!/bin/bash i=1 until [ $i -gt 5 ] do echo "Count: $i" i=$((i + 1)) done
執行:./test.sh
輸出:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
八、函數
1、定義函數
#!/bin/bash function print_input { echo "You entered: $1" } print_input "Hello World"
執行:./test.sh
輸出:You entered: Hello World
2、函數返回值
#!/bin/bash function calc_sum { total=$(( $1 + $2 )) echo $total } result=$(calc_sum 10 20) echo "The result is: $result"
執行:./test.sh
輸出:The result is: 30
以上是Linux運維常用的Shell參數及實例的介紹,可以在日常的運維工作中大顯身手!
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/256613.html