Bash
如何創建 bash 腳本,替代“goto”和“labels”
批量:
@echo off :step1 if exist "file1.txt" (GOTO step2) ELSE (GOTO X) :step2 if exist "file2.txt" (GOTO Z) ELSE (GOTO Y) :X run the script from the beginning and file1.txt and file2.txt are created and the rest of the script is executed :Y run the commands to file1.txt and run the rest of the script :Z run the commands to file2.txt and run the rest of the script
我知道 bash 中不存在“goto”和“labels”,但是在 bash 中做類似於上述操作的替代方法是什麼?
試圖:
#!/bin/bash if [ -e file1.txt ]; then echo "file1.txt ok" if [ -e file2.txt ]; then echo "file2.txt ok" alternative to goto label Z else alternative to goto label Y fi else echo "file1.txt doesn't exist" alternative to goto label X fi
PD:僅用於傳達想法的基本腳本
批處理是什麼(也應該做 bash)(重要的是避免混淆):
完整的腳本執行一些命令並創建文件 file1.txt 和 file2.txt。因此,由於腳本很長並且可以在某些時候被中斷,我想要的是從它被中斷的地方開始腳本。這就是驗證的用途:
- 如果 file1.txt 存在 (Y),則腳本已經創建它,並繼續檢查 file2.txt (Z) 是否存在(腳本的另一部分)。
- 如果 file2.txt 存在(Z),則表示命令從該點開始
- 如果 file2.txt (Z) 不存在,但 file1.txt (Y) 存在,則意味著腳本在創建 file1.txt (Y) 和 file2.txt (Z) 之間的某處被中斷,則它從 file1 開始。 txt (Y)
- 如果 file1.txt (Y) 和 file2.txt (Z) 都不存在,那麼我必須從腳本 (X) 的開頭開始
在確切知道您的批處理腳本應該做什麼之後,我將從簡化它開始:
@echo off if exist "file1.txt" goto skip_part1 run the script from the beginning and file1.txt and file2.txt are created and the rest of the script is executed :skip_part1 if exist "file2.txt" goto skip_part2 run the commands to file1.txt and run the rest of the script :skip_part2 run the commands to file2.txt and run the rest of the script
可以等效地寫為:
@echo off if not exist "file1.txt" ( run the script from the beginning and file1.txt and file2.txt are created and the rest of the script is executed ) if not exist "file2.txt" ( run the commands to file1.txt and run the rest of the script ) run the commands to file2.txt and run the rest of the script
這可以直接翻譯成以下 bash 腳本:
#!/bin/bash if [ ! -e file1.txt ]; then run the script from the beginning and file1.txt and file2.txt are created and the rest of the script is executed fi if [ ! -e file2.txt ]; then run the commands to file1.txt and run the rest of the script fi run the commands to file2.txt and run the rest of the script