Error in two scripts: “unary operator expected” and “integer expression expected”

僤鯓⒐⒋嵵緔 提交于 2019-12-12 01:44:59

问题


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:


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).



来源:https://stackoverflow.com/questions/24108548/error-in-two-scripts-unary-operator-expected-and-integer-expression-expected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!