Error in two scripts: “unary operator expected” an

2019-08-26 11:35发布

I wrote two scripts which try to do the same action in two different ways, but I get errors each time I run those. Kindly requesting your help to correct my scripts and to improve my knowledge as well. All I am trying to do the vps setup in a single script. Following two scripts are just a portion of it which get errors each time.

1) Script to set hostname through cpanel xml-api for a vps in openvz node

cat vpstest.sh

#/bin/bash
hostname_status=`curl -sku root:PASSWORDHERE "https://ip.x.x.x:2087/xml-api/sethostname?hostname=server.domain.com" | awk -F"[<>]" '/status/{print $3}' | head -n1`
    if [ $hostname_status -eq 1 ]; then
      echo "Hostname set"
    else
      echo "Failed setting hostname"
    fi

Output:

# ./vpstest.sh
./vpstest.sh: line 3: [: -eq: unary operator expected
Failed setting hostname

2) Script to set hostname via command line in an openvz node

cat vpstest1.sh

#!/bin/bash
hostname_status=`vzctl set containerID --hostname server.domain.com --save`
    if [ "$hostname_status" -eq 1 ] ; then
      echo "Hostname set"
    else
      echo "Failed setting hostname"
    fi

Output:

# ./vpstest1.sh
./vpstest1.sh: line 3: [: CT configuration saved to /etc/vz/conf/containerID.conf: integer expression expected
Failed setting hostname

Can someone help to clear these errors?

1条回答
小情绪 Triste *
2楼-- · 2019-08-26 12:02

First, the output of vzctl set containerID --hostname server.domain.com --save seems not be an integer value whereas -eq is only provided to do comparisons between integers values.

This would explain the following error :

integer expression expected

Then, you should read this reminder about the necessity (or not) to protect your variables with double quotes.

This would explain the following error, you could use something like :

./vpstest.sh: line 3: [: -eq: unary operator expected

If you want to check the status of a command :

command >/dev/null 2>&1 && echo "success" || echo "fail"
# or
if command >/dev/null 2>&1; then
    echo "success"
else
    echo "fail"
fi

You could also check the variable $? which correspond to the status of the previous command (0 when that command success or another integer value which is 1 in most of cases, or more).

查看更多
登录 后发表回答