1

I am inexperienced with Bash and scripting in general. I am writing a script involving aws CLI, for which the commands output an id. See below:

#!/bin/bash

# Command 1

VAR1=$(aws ec2 create-vpc --query "Vpc.VpcId" --output text)

# Command 2

VAR2=$(aws ec2 create-subnet --query "Subnet.SubnetId" --output text)

The output of the aws ec2 commands will be something like "id-ffffffff", which I've now captured via $VAR1 and $VAR2

I now want to output the result of each command to the console, but display different messages based on the result of the command. So far, I've done it like this:

#!/bin/bash

VAR1=$(aws ec2 create-vpc --query "Vpc.VpcId" --output text)

if [ $? -eq 0 ]; then
    echo VPC created successfully... ${VAR1}
else
    echo "Command failed"
fi

# Command 2

VAR2=$(aws ec2 create-subnet --query "Subnet.SubnetId" --output text)

if [ $? -eq 0 ]; then
    echo Subnet created successfully... ${VAR2}
else
    echo "Command failed"
fi

The problem is now that I have many lines like the ones I'm using above (10+) and I can't help but think It's silly to repeatedly run the same if/else statement for each line.

Should I use something like a goto? What is best practice here?

Thanks.

1 Answer 1

4

Create a function

report () {
    if [ $1 -eq 0 ]; then
        echo "$2"
    else
        echo "Command failed"
    fi

}

VAR1=$(aws ec2 create-vpc --query "Vpc.VpcId" --output text)

report $? "$VAR1"

VAR2=$(aws ec2 create-subnet --query "Subnet.SubnetId" --output text)

report $? "$VAR2"

It seems you can create a function for the aws ec2 as well.

3
  • Thanks, this looks like the right idea. It doesn't seem to offer me the ability to add unique strings of text depending on the command though... how would I adjust the line.... report $? "$VAR1" to echo a more descriptive output such as "VPC successfully created... "$VAR1". This would differ from the subnet command, as I would want the output for the subnet to be "Subnet successfully created... "$VAR2". Hope this makes sense...
    – swin12
    Jun 5, 2017 at 21:40
  • Just add another parameter to the function.
    – choroba
    Jun 6, 2017 at 7:52
  • Possibly, define an associative array of the texts where the index is a short-form name for the message. Jun 12, 2020 at 9:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .