2017-05-17 41 views
1

所以我想根據變量的數量創建x個目錄。在bash中使用for循環創建目錄

#!/bin/bash 
countOfCaptureFiles=$(wc -l < allCaptures.txt) 
echo $countOfCaptureFiles 

start=1 
end=countOfCaptureFiles 
for((i=$start;i<=$end;i++)) 
do 
mkdir "SnortAlert${i}" 
done 

在我目前的測試環境countOfCaptureFiles的值是3,所以我希望創建3個目錄名爲SnortAlert1 SnortAlert2 SnortAlert3。

我像下面這樣運行該腳本:./myscript.sh

但是我這樣做,我得到的錯誤,並沒有輸出時,我相信這是與assinging結束= countOfCaptureFiles但我不知道如何要解決這個問題,任何幫助將不勝感激!

+0

代碼你缺少一個'$'='分配。讓它結束'= $ countOfCaptureFiles'。 – codeforester

+0

我已經在我的mac上測試了你的代碼沒有問題$是可選的,因爲i <= $ end被評估爲i <= countOfCaptureFiles並且再次被評估爲i <= 3什麼是錯誤信息?你是否chmod + x myscript .sh'? – thatseeyou

+0

您可以從排序的角度出發,讓您在末尾添加固定寬度的所有整數,例如'001,002,003,...',您可以使用'printf -v name'SnortAlert%03d 「」$ i「',然後是」mkdir「$ name」' –

回答

2

您的代碼正在工作。但是,您可以使用外部程序(如wc,cat)最小化,如下所示。

#!/bin/bash 
i=1 
while read line;do 
    mkdir "SnortAlert${i}" 
    let i=i+1 
done <allCaptures.txt 
0

可以在語句中使用了簡化的`這樣結束了」

#!/bin/bash 
var=$(cat allCaptures.txt) 
for line in $var 
do 
    mkdir "SnowAlert${line}" 
done