2017-10-20 40 views
0

嗨,大家好,我是這個新手。希望你能幫助我 我寫這(應該很簡單)bash腳本來檢查文件類型是否爲txt或zip。但它不工作Bash:if和typecheck

代碼:

#!/bin/sh 
echo "please insert file" 
read file 
if [ $file == *.txt ] 
then 
emacs $file 
elif [ $file == *.zip ] 
then 
zip $file 
fi 
+1

'sh'通常不是'bash'。 – Cyrus

+1

即使'sh' *是*'bash','''也不做模式匹配。 – chepner

+1

請看看:http://www.shellcheck.net/ – Cyrus

回答

1

使用case語句。

case "$file" in 
*.txt) emacs $file ;; 
*.zip) zip $file ;; 
esac 
+0

thx!解決了我的問題 –

0

您可以使用:

if [ ${file: -4} == ".txt" ]
,因此比較最後4個字符

或使用:

if [[ $file == *.txt ]]
因此使用重新gular表達式(雙括號僅在某些shell中可用,但在bash中可用)。