shell指令碼判斷檔案字尾
阿新 • • 發佈:2020-12-25
技術標籤:Linux
shell指令碼判斷檔案字尾
有時候需要判斷檔名字尾來區分檔案型別,進而進行不同的操作。以下是獲取檔名字尾和檔名字首的兩個函式,由於shell指令碼函式只能返回0-255,為了將結果返回,就直接使用echo
輸出,可以用$()
進行捕獲。
#!/bin/bash # --------------------------------------------------------------------------- # # 獲取檔名字尾 # Parameter1: 檔名 # output: Yes # return: None # --------------------------------------------------------------------------- # function FileSuffix() { local filename="$1" if [ -n "$filename" ]; then echo "${filename##*.}" fi } # --------------------------------------------------------------------------- # # 獲取檔名字首 # Parameter1: 檔名 # output: Yes # return: None # --------------------------------------------------------------------------- # function FilePrefix() { local filename="$1" if [ -n "$filename" ]; then echo "${filename%.*}" fi }
使用示例:
# --------------------------------------------------------------------------- # # 判斷檔案字尾是否是指定字尾 # Parameter1: 檔名 # parameter2: 字尾名 # output: None # return: 0: 表示檔案字尾是指定字尾;1: 表示檔案字尾不是指定字尾 # --------------------------------------------------------------------------- # function IsSuffix() { local filename="$1" local suffix="$2" if [ "$(FileSuffix ${filename})" = "$suffix" ]; then return 0 else return 1 fi } file="demo.txt" IsSuffix ${file} "txt" ret=$? if [ $ret -eq 0 ]; then echo "the suffix of the ${file} is txt" fi