2

I am trying to pass an ip and port to my bash script from a list of devices but the script is reading it as multiple devices instead of port. So in the example from below it's trying to telnet to 4 devices as it's reading the ports as a device.

for device in `cat device-list.txt`;
do
  hostname=$(echo $device | cut -d : -f 1)
  port=$(echo $port | cut -d : -f 2)
  ./script.exp $device $username $password $port ;
done

I am trying to use cut to take the port and pass it through as a variable so my telnet should be e.g. abc.abc.com 30040 as one device and so on.

 # Telnet
spawn telnet $hostname $port

This is my list of devices

abc.abc.com 30040
abc.abc.com 30041

I have tried searching this site already for answers.

umläute
  • 28,885
  • 9
  • 68
  • 122
JelBoy
  • 37
  • 5

3 Answers3

4

I see two errors (lines 4 & 5). It should be

 for device in `cat device-list.txt`;
 do
   hostname=$(echo $device | cut -d : -f 1)
   port=$(echo $device | cut -d : -f 2)
   ./script.exp $hostname $username $password $port ;
 done
Ajay M
  • 2,490
  • 1
  • 15
  • 22
1

You can use the Bash built-in read function to extract hostname and port from the lines in a loop:

while read -r hostname port || [[ -n $hostname ]] ; do
    ./script.exp "$hostname" "$username" "$password" "$port"
done <device-list.txt
pjh
  • 6,388
  • 2
  • 16
  • 17
0

@pjh has the correct answer.

But here's some notes on your script:

  1. you iterate over all the words of the file, rather than its lines.

  2. using cut -d :, you specify the delimiter between fields as :. However, in your file you don't use : as the delimiter, but space ()

  3. you calculate the $hostname variable by parsing $device, but then you use $device when calling the script

  4. you calculate the $port variable by parsing the $port variable, which doesn't make any sense.

Here's an example on how to parse each line with cut:

cat device-list.txt | while read device; do
  hostname=$(echo $device | cut -d" " -f 1)
  port=$(echo $device | cut -d" " -f 2)
  ./script.exp $hostname $username $password $port
done
umläute
  • 28,885
  • 9
  • 68
  • 122