Search code examples
bashoperatorsquotesdouble-quotes

Understanding bash logic. (Operators and quotes)


bktitle="Bash"
echo "New book title '$bktitle' added successfully!"

I thought single quotes made everything literal? But this was give the output of

New Book title Bash added successfully!
egrep ^[0-9]+$

Why would this line only accept integers? I know this ^ is for starting with, the + is for means the preceding must occur at least once. But for my knowledge of $, I'm not sure. Would it not accept something like 1a?

egrep ^[0-9]+[.][0-9][0-9]

Why would this line only accept decimal numbers for exactly 2 decimal places? I thought the + would only allow for it to make sure that the starting number must be 0-9. So why isn't it accepting something like 1a.00?


Solution

  • I thought single quotes made everything literal? But this was give the output of New Book title 'BASH' added successfully.

    In your example:

    bktitle="BASH"
    echo "New book title '$bktitle' added successfully!"
    

    Inside a double-quoted string (""), single-quotes ('') are not interpreted, but variables are.

    If you did this:

    bktitle="BASH"
    echo 'New book title \'$bktitle\' added successfully!'
    

    Or this:

    bktitle="BASH"
    echo "New book title \'$bktitle\' added successfully!"
    

    Or this:

    bktitle="BASH"
    echo 'New book title $bktitle added successfully!'
    

    You would see (in the first two examples):

    New book title '$bktitle' added successfully!

    Or:

    New book title $bktitle added successfully!

    Single quotes don't interpret variables or double quotes (or \escape sequences).

    Why would this line only accept integers? I know this ^ is for starting with, the + is for means the preceding must occur at least once.. but for my knowledge of $ I'm not sure. but would it not accept something like 1a?

    You're right about ^ and +! [0-9] matches any number between 0 and 9. $ means ends-with, and represents the end of the string.

    ^[0-9]+$
    

    Matches any string containing 1 or more numbers, from beginning to end, and nothing else.

    Now for your last question:

    egrep '^[0-9]+[.][0-9][0-9]' Why would this line only accept decimal numbers for exactly 2 decimal places? i thought the + would only allow for it to make sure that the starting number must be 0-9. so why isn't it accepting something like 1a.00?

    Yes, this would match decimal numbers containing exactly two decimal places.

    If you wanted it to accept letters as well, as long as it starts with a number, you'd need:

    egrep '^[0-9][0-9a-z]+[.][0-9][0-9]'
    

    [0-9a-z] matches any number 0-9, and any letter a-z.