Your script shows that you are using #!/bin/sh
in shebang line. That might be an issue, since some default shells dont support arrays.. An example of that would be dash
on Ubuntu. In case where you absolutely must use default shell that cannot use arrays, see Stephane's answer in the link. Alternatively, one could take advantage of word splitting like so:
read -p "Enter ports(space separated):" ports
for port in $ports
do
[ -d "/root/port$port" ] || mkdir -p "/root/port$port" && echo "Created /root/port$port"
done
On the other hand, if we could use a shell with more capabilities ( and in many cases an OS has more than one shell), it would be better to use an array for storing ports. General approach for that I would take when arrays are available ( bash
, ksh
, mksh
,zsh
shells ) is like this:
printf "Enter ports(space separated):"
read ports
arr=( $ports )
Here we're taking advantage of having string , for example, 80 22 23
being split at spaces (known commonly as word splitting) and provide those individual values to array arr
. This is far from ideal, but works.
If you can use bash, it's possible to take advantage of read -a
to read all items as array, and then iterate over the values. For example:
bash-4.3$ read -p "Enter ports(space separated):" -a portsEnter ports(space separated):80 22 25
bash-4.3$ echo ${ports[0]}
80
bash-4.3$ echo ${ports[1]}
22
bash-4.3$ echo ${ports[2]}
25
Same approach could be used on ksh
with read -A
.
Then you could do something like this:
for port in ${ports[@]};
do
[ -d "/root/port$port" ] || mkdir -p "/root/port$port" && echo "Created /root/port$port"
done
I am not familiar with csh
so won't provide solution for that, but the general idea should be similar