第一個shell文件

該文主要記錄自己學習shell所踩的一些坑!!!

什麼是shell

windows下有.bat後綴的批處理,在linux下也有類似於批處理的東西,那就是shell,一般後綴爲.sh,使用bash運行這種文件。
嚴格說,shell是一種腳本語言,和python, js一樣,與c++,java不同。關於腳本語言和編譯語言的區別可以參考知乎:編程語言 標記語言 腳本語言分別有哪些? 區別是什麼?

爲什麼要學shell

在linux下,使用shell可以方便的與系統交互,實現很多任務的自動化處理。如果還想要更多理由,可以參考豆瓣:我們爲什麼要學習Bash Shell

第一個shell文件

這裏寫下我自己的第一個shell文件,後面簡單介紹這個文件所涵蓋的知識點,只希望能夠點出shell中的若干有趣的點和容易踩到的坑。

#!/bin/bash
str="hello world"
name="lijiguo"
str1="helloworld"

# how to use echo 
echo "the" first line : $str "\n"
echo 'the second line :'${str} ${name} '\n'
echo -e "the third line:" ${str1} "\n next line"

#how to use parameter
echo $0

a=10
b=20
#how to use expression
value=`expr $a + $b`
echo $value
value=`expr $a \* $b`
echo $value

#how to use if statement
if [ $a == $b ]
then
echo "a==b"
else
echo "a != b"
fi

#how to use while statement
idx=1
while (($idx<=5 ))
do
echo $idx
idx=`expr ${idx} + 1`
done

#how to redirect
echo "this is a example" >> test.log
#how to compare str

#how to use python
/bin/python test.py

#how to use case
while :
do
echo "input 1-5, input others to end"
read num
case $num in
1|2|3|4|5) echo "you enter $num"
;;
*) echo "end"
break;
;;
esac
done

程序輸出如下:

the first line : \n
the second line : lijiguo \n
the third line: helloworld
 next line
./blog.sh
30
200
a != b
1
2
3
4
5
python print test
input 1-5, input others to end
1
you enter 1
input 1-5, input others to end
2
you enter 2
input 1-5, input others to end
6
end

下面逐項介紹shell中涉及到的知識點。

文件第一行

#!/bin/bash

這一行指定執行該文件的shell,該行是約定俗成的。

變量賦值

變量賦值這麼簡單的事還要說?
這裏確實要說,等號兩邊不能加空格!不能加空格!不能加空格!而且變量賦值變量前面不加美元符。

使用echo

echo "the" first line : $str "\n"
echo 'the second line :'${str} ${name} '\n'
echo -e "the third line:" ${str1} "\n next line"

參考輸出:

the first line : \n
the second line : lijiguo \n
the third line: helloworld
 next line
  1. 單引號和雙引號,甚至不加引號都可以輸出字符串。
  2. 變量使用時是 $name
  3. echo不會自動轉義輸出,加上-e參數纔會轉義輸出。

如何使用參數

假如我們想向shell中傳入參數,在shell中如何獲取呢?
$0表示shell的文件名,$1表示第一個參數,$2表示第二個參數,以此類推,$*表示將所有參數合成一個字符串返回,$@表示將多有參數分成多個字符串返回。

如何使用表達式

shell不支持直接求解表達式,需要藉助expr。

value=`expr $a + $b`
echo $value
value=`expr $a \* $b`
echo $value

輸出是

30
200

敲黑板敲黑板:
1. 求解的表達式用反引號引起來,是反引號,ESC下面那個
2. 變量和運算符之間要有空格,$a+$b是不對的,$a + $b纔對。
3. 乘法要用\*來實現.
4. 其它運算,都可以這樣實現。

使用if語句

  1. 基本框架是 if condition then else fi
  2. condition中使用[]或者(())將條件表達式括起來。
  3. fi是if倒序,表示if語句結束。

如何使用while語句

  1. 基本框架 while condition do done
  2. 當condition是冒號(:)時,表示無限循環。
  3. do/done表示一個語句塊,兩者成對出現。

如何使用重定向

echo "this is a example" >> test.log

>>兩邊要有空格

如何使用case

while :
do
echo "input 1-5, input others to end"
read num
case $num in
1|2|3|4|5) echo "you enter $num"
;;
*) echo "end"
break;
;;
esac
done
  1. ;;表示一個分支結束
  2. *表示others
  3. esac表示case的結束,是case的倒序

結語

新手,上面沒有全面的語法,沒有完整的例程,只是自己踩的一些坑。如有錯誤,還請不吝賜教。

參考

Shell教程|菜鳥教程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章