Trying bash shell scripting and running into small issue:

# hostname --short
# virsh --readonly list --state-running --name

# set $(hostname --short)=$(virsh --readonly list --state-running --name)
# echo $?
# echo $7phdsn01

Please advise.

# unset $7phdsn01
# set $(hostname --short)=$(virsh --readonly list --state-running --name)
# echo $7phdsn01
  • @MichaelHomer please see my updated question with output for your comment. – alexus Jun 11 '19 at 19:55
  • Your set $(hostname ...)=$(virsh ...) will just set $1 (the 1st positional parameter) to the 7phdsn01=Nagios string and will succeed, that's why you get $? = 0. – mosvy Jun 11 '19 at 20:23

The set command does not set values of shell variables like that in bash. You may want to try with declare instead.

It looks as if you want to use a variable named after the hostname. Unfortunately, the hostname starts with a digit, so it can't be used as the name of a variable.

The command echo $7phdsn01 outputs phdsn01 since $7 (the 7th positional parameter) is unset and expands to nothing, followed by the rest of the string.

I would probably have used

declare -A state

state["$(hostname --short)"]=$(virsh --readonly list --state-running --name)

This would create an associative array called state. The next line sets the value for the key given by the hostname --state command to the output of the virsh command.

The values and keys of the state array could then be had like this:

for host in "${!state[@]}"; do
    printf 'Host %s is in state %s\n' "$host" "${state[$host]}"

If you're doing this for a single host, then obviously there is no need to be that fancy. Instead just use two variables:

host=$(hostname --short)
state=$(virsh --readonly list --state-running --name)

printf 'Host %s is in state %s\n' "$host" "$state"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.