0

Hello and thank you for your time. So, I have been coding a script to get the information from switchs in a local network, however i have met this strange behavior in Bash of which i was not aware and i don't seem to find anything on:

#!/bin/bash
SWITCH1=../SwitchData/switch.txt
p_vlan=($(cut -d ' ' -f1 $SWITCH1))
p_mac=($(cut -d ' ' -f2 $SWITCH1))
p_port=($(cut -d ' ' -f4 $SWITCH1))

for ((i=0;i<"${#p_port[@]}";i++))  
do  
    echo "${p_port[$i]}"
    echo "${p_port[$i]} ${p_mac[$i]} ${p_vlan[$i]}" 
done
echo "${p_port[@]}"

returns:

Fa0/1
b462.6c72.bae4 247
Fa0/1
9200.0b00.0d37 3
Fa0/1
a562.6a32.bae4 3
Fa0/3
a562.6a62.c73b 247
...
Fa0/22 0120.0b00.1950 6 Fa0/22 #from echo "${p_port[@]}"

so as we can see, when ${p_port[$i]} is written with other arrays, it is not written anymore. however, when written alone, the values still appears. also, echo "${p_port[@]}" which should write the whole array only write it's last value. and finally, when writing an equality with another value that should have the exact same value, it returns false, even though it should return true. so if you have any idea as to what might cause this issue, feel free to share your insight.

I must also add some information on the switch.txt file, in fact i have used the command:

sed -e "s/^M//g" ../SwitchData/switch.txt > ../SwitchData/temp.txt
cat ../SwitchData/temp.txt > ../SwitchData/switch.txt

or

sed -e -i "s/^M//g" ../SwitchData/switch.txt

In order to delete the ^M at the end of the file.
Also, changing "s/^M//g" by "s/^M/ /g" correct the issue.

PS: if you have any idea of a title that would be more relevant.

recouer
  • 45
  • 7
  • `In order to delete the ^M at the end of the file` and that did not work, so try something else. Doing `"s/^M/` deletes a character `M` from beginning of the lnie. – KamilCuk Aug 04 '20 at 16:44
  • the ^M at the end of the file was correctly erased, but the behavior from my code was strangely modified from this. – recouer Aug 04 '20 at 16:55
  • when looking at the code with emacs before and after i used the command, i checked that the ^M was properly removed, this behavior stems from the fact that there was nothing to replace it (at least my guess) and i would like to warn people to be aware of that when they code, as well as understand why it would do that. – recouer Aug 04 '20 at 17:06
  • No, `s/x//` is completely valid `sed` to the first occurrence of `x` on each input line (and you can add `/g` to make it remove all occurrences; this will be unnecessary if you only expect one match, like here). – tripleee Aug 05 '20 at 04:26

0 Answers0