-1

I am trying to write a fish script that checks on the current vagrant status and does something based on it. A simple example would be:

Check if vagrant is running, if yes do vagrant halt, if no do vagrant up.

I have come up with something like:

# Go to vagrant folder
cd "/vagrant/folder"

# Set status
set status(vagrant status --machine-readable | grep state,running)

# Check status
if  [ status != "" ] 
vagrant halt

# Send notification
notify-send "Vagrant is halted."

else

vagrant up

# Send notification
notify-send "Vagrant is up."

end

I do not know if that string comparison is the way to go or if there is a neater, more precise way to check the vagrant status.

ARAGATO
  • 11
  • 6

1 Answers1

0

Found the solution with test and $status

# Get status
vagrant status --machine-readable | grep state,running

# Check status
if test $status -eq 0

    # Vagrant is running
    vagrant halt

    # Send notification
    notify-send "Vagrant is halted."

else

    # Vagrant is not running
    vagrant up

    # Send notification
    notify-send "Vagrant is up."

end
ARAGATO
  • 11
  • 6
  • You can just directly use `if vagrant status --machine-readable | grep state,running`. (Also `grep` has a "-q" flag in case you want to supress its output) – faho Mar 08 '19 at 14:25
  • Great, thanks faho. How does the if statement know where the case begins and stops. In this particular case could one write it in parantheses as well: if (vagrant status --machine-readable | grep state,running) just to make it more clear for the coder? The -q flag is great, too. Appreciated. – ARAGATO Mar 11 '19 at 05:16
  • No, that means something entirely different. In fish, `()` is the syntax for command substitutions (http://fishshell.com/docs/current/tutorial.html#tut_command_substitutions), which use the output of one command and pass it as argument to another. But what you want here is to check the return code, and not the output. So absolutely no `()`. – faho Mar 11 '19 at 16:56
  • And the `if` knows where the condition stops because it uses one "compound command" - one pipeline of commands that can also include `begin; end` blocks and `; and` or `&&` style logical operators. – faho Mar 11 '19 at 16:57