some strings won't echo -n but will echo?

I am attempting to create a very simple script that executes a command on a Cisco switch using ssh and then parses the output in bash to pick out switch names and IP addresses.

Since the switch names are coming back as name.sub.domain, and all I want is the “host” name, I wanted to trim the results with ${var%%.}. If I echo that out it works. But when I try to put it on the same line as the corresponding IP address, using `echo -n ${var%%.}’ the string is not displayed.

I have also attempted to assign ${var%%.*} to a new variable, but that doesn’t change the behavior.

How can that be?

Here’s a version of what I’m doing:


#!/bin/bash

#get a list of CDP neighbor details and pull out name and IP address

function getips {
    ssh $1 'sh cdp ne det' | grep -e "Device ID" -e "IP address" | uniq | cut -d':' -f2
}

# All my IP addresses start with with 10

function isip {
    local arg=$1
    test ${arg#10} != $arg
}

# With the '-n' argument, echo completely swallows names without '.'s in them
# Without '-n' echo displays the trimmed name, as expected.
function trimips {
    local arg=$1
    for f in $(getips $arg); do isip $f && echo $f || echo -n ${f%%.*}; done
}


Works for me.

$ f=a.b.c.d
$ echo $f
a.b.c.d
$ echo -n ${f%%.*}
a$

Sure your problem isn’t the ||? Since the first expression succeeds the second one isn’t evaluated. Note that && and || have equal precedence, unlike programming languages you may be used to.

Why don’t you add “echo $1” in the isip function rather than “isip $f && echo $f” ?

That’s the strange thing. If I redirect the output into a file and then process it, it works. I think the problem has to do with the ssh call being part of the for loop. Two processes may be modifying the same memory location.