1

I am writing a bash script to get some information from a remote host, but I got a problem, here is my code:

#!/bin/bash -e

NODE_IP="192.168.136.1"
SSH_NODE="ssh -q -t -t -o StrictHostKeyChecking=no root@${NODE_IP}"

# check stack exists or not
stack=`${SSH_NODE} "openstack stack list |grep test | wc -l"`
echo -e "${stack}"
if [ "${stack}" == "1" ]; then
    echo -e "delete existed stack";
fi
echo -e "end"

Output:

1
end

The variable stack outputs 1 but it doesn't equals to "1", I guess there are some unknown characters behind it, so I tried to trim them by using | xargs and | tr -d '\n', but both of them didn't work.

stack=`${SSH_NODE} "openstack stack list |grep test | wc -l | tr -d '\n' | xargs"`
# or trim after return
stack=`${SSH_NODE} "openstack stack list |grep test | wc -l" | tr -d '\n' | xargs`

If I change the code to "contains" instead of "equals", it will work.

if [[ "${stack}" == *"1"* ]]; then

But I wonder what is the unknown character behind my variable.

I would appreciate any help.

Corey
  • 1,217
  • 3
  • 22
  • 39
  • 1
    Try `declare -p stack` to see what it contains, with special characters escaped. – Benjamin W. Jun 03 '20 at 03:52
  • 1
    Or, `printf '%q\n' "$stack"`, which displays nonprinting characters reliably actually more versions of bash. `declare -p` doesn't always do that right. – Charles Duffy Jun 03 '20 at 04:01
  • 2
    BTW, `echo -e` is a bad idea in general. Its behavior is wildly variable based on active runtime configuration; use `printf` instead, as the POSIX spec for `echo` recommends; also, see https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo – Charles Duffy Jun 03 '20 at 04:04
  • 1
    What does ```echo -e "${stack}" | hexdump``` result? – Book Of Zeus Jun 03 '20 at 04:28
  • Thanks for all, I have some clues to troubleshoot this issue, @BenjaminW. `declare -p stack` shows `"eclare -- stack="1`. – Corey Jun 03 '20 at 04:32
  • 1
    @CharlesDuffy, `printf '%q\n' "$stack"` shows `$'1\r'`. – Corey Jun 03 '20 at 04:33
  • @BookOfZeus, `echo -e "${stack}" | hexdump` shows `0000000 0d31 000a 0000003`. – Corey Jun 03 '20 at 04:34
  • 3
    @Corey So, you got a carriage return in your variable. `tr -d '\r'` will remove it – oguz ismail Jun 03 '20 at 04:43
  • @oguzismail Yeah, you're right, thanks! – Corey Jun 03 '20 at 05:34

0 Answers0