-1

I want to assign a variable conditionally.

This does not work

[[ -v $2]] && [$2 == "init" ] && command="./ops/init.sh"
[[ -v $2]] && [$2 == "destroy" ] && command="./ops/teardown.sh"
[ -z "${2}" ] && command="./ops/help.sh -h"

I am trying check for the existence of the argument and another conditon but I cannot get the syntax right

fpmurphy
  • 4,636
dagda1
  • 195

2 Answers2

1

To start with -v is a zsh extension, so your issue might be just that the wrong shell is executing your script.

The normal way to write this would be to use a case statement.

case "$2" in
    ("init") command="./ops/init.sh" ;;
    ("destroy") command="./ops/teardown.sh" ;;
    ("") command="./ops/help.sh -h" ;;
    (*) echo "$0: unknown option '$2' - expecting 'init' or 'destroy'" >&2
        exit 2 ;;
esac

It is not the best idea to put multiple words into a string as in ./ops/help.sh -h although you will get away with it (and had no choice originally with the shell). Instead consider using an array.

icarus
  • 17,920
0

In shell scripting you need to be very careful about whitespace. You also should be aware of the differences between [ and [[. If unsure, consult the bash(1) manual. I recommend shellcheck to detect common mistakes in your scripts. In your case:

#!/bin/bash
[[ -v $2 && $2 = "init" ]] && command="./ops/init.sh"
[[ -v $2 && $2 = "destroy" ]] && command="./ops/teardown.sh"
[[ -z $2 ]] && command="./ops/help.sh -h"

But as icarus said a case statement is preferable.

Devon
  • 847