如何在 Linux 中多次執行命令?
在某些情況下,您可能希望執行特定命令“N”次。在正常的程式設計中,這可以透過在該程式語言中可用的任何迴圈結構來完成。在 Linux bash 中,我們也有迴圈和其他一些方法可以重複執行命令“N”次。
在本教程中,我們將探索不同的 bash 指令碼,這些指令碼將允許我們多次執行某個命令。
當您想使用 bash 指令碼時,第一步是建立一個。在 Linux 或 macOS 機器上,您可以使用以下命令建立 bash 檔案:
touch mybash.bash
請注意,檔名稱可以是任何名稱,但副檔名必須相同(即 bash)。儲存 bash 指令碼後,使用以下命令執行它:
bash mybash.bash
現在我們知道了如何建立和執行 bash 檔案,讓我們探索所有這些不同的示例。
使用“for”迴圈重複命令
您可以使用“for”迴圈多次列印某個命令。 “for”迴圈有不同的變體,我們將藉助不同的 bash 指令碼探索所有這些變體。
首先,讓我們考慮一個簡單的非條件“for”迴圈,我們將使用它列印一個簡單命令 5 次。請考慮以下 bash 指令碼:
# using a for loop for i in {1..5} do echo 'Sr-no: $i - Welcome to Tutorialspoint' done
儲存此指令碼然後執行它。您將在終端上獲得以下輸出:
Sr-no: 1 - Welcome to Tutorialspoint Sr-no: 2 - Welcome to Tutorialspoint Sr-no: 3 - Welcome to Tutorialspoint Sr-no: 4 - Welcome to Tutorialspoint Sr-no: 5 - Welcome to Tutorialspoint
另一種實現相同目標的更簡單方法是將上述 bash 指令碼程式碼寫在一行中,這可能一開始看起來有點奇怪,但它用更少的行數完成了相同的工作。
# using a for loop for i in {1..5}; do echo 'Sr-no : $i - Welcome to TutorialsPoint'; done
以上兩個 bash 指令碼都使用了非條件“for”迴圈,但您也可以使用基於條件的“for”迴圈來列印某個命令“N”次。例如,請檢視以下 bash 指令碼:
# using a for loop for ((i=0;i<5;i++)); do echo 'Sr-no : $i - Welcome to TutorialsPoint'; done
執行上述 bash 指令碼,您會注意到它產生了相同的輸出。
使用“while”迴圈
您也可以在 Bash 指令碼中使用“while”迴圈來多次列印某個命令。例如,請考慮以下所示的 bash 指令碼。
# using a while loop i=1 while [[ $i -le 5 ]]; do echo 'Sr-no: $i - We all love Linux.' let ++i; done
執行上述指令碼,它將在終端上產生以下輸出:
Sr-no: 1 - We all love Linux. Sr-no: 2 - We all love Linux. Sr-no: 3 - We all love Linux. Sr-no: 4 - We all love Linux. Sr-no: 5 - We all love Linux.
使用 Bash 函式
您可以使用 Bash 函式來多次列印某個命令。例如,請考慮以下所示的 bash 指令碼。
# using a bash function function repeatNTimes(){ for ((i=0;i<$1;i++)); do eval ${*:2} done } repeatNTimes 5 echo 'The tougher it gets, the cooler I get'
這裡我們建立了一個名為“repeatNTimes”的使用者定義函式,然後呼叫它來列印一個字串 5 次。儲存並執行此 bash 指令碼。您將獲得以下**輸出**:
The tougher it gets, the cooler I get The tougher it gets, the cooler I get The tougher it gets, the cooler I get The tougher it gets, the cooler I get The tougher it gets, the cooler I get
結論
在本教程中,您學習了在 Linux 中多次重複命令的不同方法。