2017-03-02 59 views
-2

我不能給出太多解釋,因爲我的英語不好。下面是我想要做的例子;shell腳本 - 我如何進行多次讀取?

try.sh

#!/bin/sh 
echo -n "Enter the port:" 
read ports 
if [ ! -d "$ports" ]; then 

mkdir -p /root/port$ports 
echo "The folder was created for $ports" 
wget -q www.example.com/example.tar.bz2 
tar -xjf example.tar.bz2 
su root -c "screen -A -m -d -S 'example$ports' ./example -RunningAsRootIsEvilAndIKnowThat" 
echo "$ports started." 
else 
exit 0 
fi 

膩子;

[email protected]:~# sh try.sh 
Enter the port: 4445, 4546 
Created folder 'port4445' 
Created folder 'port4546' 
4445 started. 
4546 started. 

我該怎麼做?

+1

還有,你在shell腳本試過嗎? – Raptor

+0

什麼都沒有。我不知道怎麼做。 –

+0

爲什麼你用','作爲分隔符?我會簡單地使用空間 – hek2mgl

回答

2
#!/bin/bash 
IFS=, read -p "Enter the Hosts: " -ra hosts </dev/tty 
IFS=, read -p "Enter the Port: " -ra ports </dev/tty 

for host in "${hosts[@]}"; do 
    for port in "${ports[@]}"; do 
     nc -vz $host $port 
    done 
done 

運行:

bash try.sh 
Enter the Port: 80 
Enter the Hosts: 127.0.0.1 
localhost [127.0.0.1] 80 (http) open 

nc -vz $host $port將檢查$host$port

IFS=,拆分輸入聽力,在我們的情況與,認爲它是輸入分隔符。

-p顯示消息。

-a把輸入到數組

+0

更改腳本以期望使用空格分隔的標記而不是逗號分隔的標記可以簡化邏輯並更好地與其他工具集成。 – tripleee

+0

當然,只需更改IFS。 OP提供的例子有',' –

-2

使用$ *讀取參數:

echo $* | awk '{ i=1; while(i<=NF) { print $i; i++; } }' 

for i in $*; do 
    echo $i 
done 
+0

我不想爲Bash。我需要它爲殼牌腳本 –

+0

這工作在通用'sh',但它似乎是一個不同的(雖然切線相關)的問題的答案。我認爲它試圖說:「不要首先交互式讀取輸入,而是讓腳本接受端口號作爲命令行參數,而你和我們都會更快樂」。 – tripleee

+3

Downvote缺乏引用和愚蠢的Awk解決方法沒有明顯的好處。正確的方法是使用''$ @''(是的,使用雙引號)而不是'$ *'並在循環內引用'「$ i」'。 – tripleee