shell運行

shell可以在終端用命令行運行,也可以將命令寫入到文本文件,文件後綴名為.sh。注意首行要寫#!/bin/bash,代表著解釋器所在的路徑。#用來添加註釋。

$ps | grep $$可以用來查看當前所用的解釋器,也就是用來運行的程序。$which bash可以用來查看解釋器所在的路徑

變數

賦值

我們可以用=來給變數賦值。

比如

$first_date=ABC$echo $first_date

在這裡first_date前面的$代表著輸出這個命令或者變數

在和其他字母排在一起的時候我們還可以把變數名用{}將變數括弧包起來防止混淆。

$My_first_character=ABC$echo "My characters are ${My_first_character}DEF"

輸出結果

My characters are ABCDEF

命令

除了變數名以外,$()或者````裡面還可以加入linux執行語句,用來執行。

比如

$list=`ls`$dir=/tmp/my-dir/file_$(/bin/date +%Y-%m-%d).txt$echo $dir

在這裡$()裡面的內容被當做linux命令執行後替換了所在位置的內容。

練習

The target of this exercise is to create a string, an integer, and a complex variable using command substitution. The string should be named BIRTHDATE and should contain the text "Jan 1, 2000". The integer should be named Presents and should contain the number 10. The complex variable should be named BIRTHDAY and should contain the full weekday name of the day matching the date in variable BIRTHDATE e.g. Saturday. Note that the date command can be used to convert a date format into a different date format. For example, to convert date value, $date1, to day of the week of date1, use:

在這裡注意兩點運用linux命令既可以用$()也可以用``這個符號。等號前後不要有空格。

在命令行當中傳遞參數到shell腳本當中

#!/bin/bashecho $3BIG=$5echo A $BIG costs $6echo $#

我們可以在終端運行shell腳本的時候,後面跟上要傳入的參數,$num是寫到shell腳本裡面的內容,代表著在終端傳入的第幾個參數。

比如

$ ./bin/my_shell.sh apple 5 banana 8 "Fruit Basket" 15

以上就是在運行my_shell.sh這個腳本,把後面6個參數傳入,當然,按照這個腳本裡面的代碼,只有第3個,第5個,第6個參數用上。

$#列印出傳入參數的個數。

陣列

shell裡面的陣列用括弧表示。

$my_array=(apple banana "fruit")$echo $my_array

返回元素的個數用${#arrayname[@]}的方式

$echo ${#my_array[@]}

取出對應的元素

$echo ${my_array[3]}#取出第4個元素

賦值

my_array[4]=pear

$echo ${my_array[4]}$echo ${my_array[${#my_array[@]}-1]}

基本運算

基本運算的表達式是$((expression)),運算的表示是跟python的語法一樣的。

字元串的基本操作

列印字元串長度

$string=abcdef$echo ${#string}

列印子字元串裡面的首個出現在父字元串的位置

expr index

$string=This is us $substring=hat$expr index "$string" "$substring"


推薦閱讀:
相關文章