I have a script that parses a command:
while read line; do
# The third token is either IP or protocol name with '['
token=`echo $line | awk '{print $3}'`
last_char_idx=$((${#token}-1))
last_char=${token:$last_char_idx:1}
# Case 1: It is the protocol name
if [[ "$last_char" = "[" ]]; then
# This is a protocol. Therefore, port is token 4
port=`echo $line | awk '{print $4}'`
# Shave off the last character
port=${port::-1}
else
# token is ip:port. Awk out the port
port=`echo $token | awk -F: '{print $2}'`
fi
PORTS+=("$port")
done < <($COMMAND | egrep "^TCP open")
for p in "${PORTS[@]}"; do
echo -n "$p, "
done
This prints out ports like:
80,443,8080,
The problem is that trailing slash ,
How can I get the last port to not have a trailing , in the output ?
Thanks
read linetoread f1 f2 token f4 _-- no moreawkneeded if you letreaddo the splitting, and then you can assignportfrom either$f4or$f2depending on the test.$COMMAND | ...is quite buggy; see BashFAQ #50 describing why, and various better-behaved alternatives. You also might consider using lower-case names for your own variables -- all-caps names are used for variables meaningful to the shell and operating system's tools, as specified by POSIX @ pubs.opengroup.org/onlinepubs/9699919799/basedefs/…echo -n "${array[0]}"; unset array[0]; for p in "${array[@]}"; do echo -n ", $p"; done?printf '%s' "${array[0]}"; printf ',%s' "${array[@]:1}"; no need for anyechos, explicit looping, nor changing the array. That said, it's a good approach, and if you don't mind I'll fold it into my answer.