1

This bash script tries to get the string "ami-774b7314" from the output of the following command so that it can be used as input to another command in the same script:

aws ec2 describe-images --region ap-southeast-2 --owners amazon --output text --query 'Images[].{A1name:Name,A2id:ImageId}' --filters Name=is-public,Values=true,Name=name,Values=amzn-ami-*.*.*-amazon-ecs-optimized | sort

amzn-ami-2016.03.i-amazon-ecs-optimized ami-22a49541
amzn-ami-2016.03.j-amazon-ecs-optimized ami-862211e5
amzn-ami-2016.09.a-amazon-ecs-optimized ami-73407d10
amzn-ami-2016.09.b-amazon-ecs-optimized ami-5781be34
amzn-ami-2016.09.c-amazon-ecs-optimized ami-774b7314 <===== this line

and to verify it is in the format ami-and-a-mix-of-alphanumeric else echo "bad string" and exit the script

How can it be done?

1 Answer 1

4

The tail command may be used for this. It gives you the last few (10 by default) lines of input as output (the "tail" of it).

With the -n flag you may specify exactly how much of the tail you'd like to have:

aws ec2 ... | sort | tail -n 1

To verify that it follows the right format, you may do

line="$( aws ec2 ... | sort | tail -n 1 )"

if [[ ! "$line" =~ ^amzn-ami-[0-9]{4}\.[0-9]{2}\.[a-z]-amazon-ecs-optimized\ ami-[0-9a-z]{8}$ ]]; then
    echo "bad string"
    exit 1
fi

If you only want the last bit of the last line, use cut to cut it out:

line="$( aws ec2 ... | sort | tail -n 1 | cut -d ' ' -f 2 )"

The -d ' ' -f 2 bit says "use space as the field delimiter and give me the second field".

Then the regular expression becomes shorter too:

if [[ ! "$line" =~ ^ami-[0-9a-z]{8}$ ]]; then
    echo "bad string"
    exit 1
fi
3
  • cut -d ' ' -f 2 is still giving the whole line. I also tried -d ' ' -f 1 for no avail. it seams like the space delimiter is not working with this line... any idea?
    – Fred J.
    Jan 8, 2017 at 22:41
  • @FredJ. "Works for me". I copied your example data into a file and used it as it was. Is there a tab there maybe?
    – Kusalananda
    Jan 8, 2017 at 22:45
  • @FredJ. If there's a tab, change -d ' ' to -d $'\t'.
    – Kusalananda
    Jan 8, 2017 at 22:48

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.