2017-03-02 58 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