2017-10-20 39 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中可用)。