How do we separate variables from letters in shell scripting?

前端 未结 5 569
误落风尘
误落风尘 2020-12-11 14:37

I tried printing \"Dogs are the best.\" with this bash script.

#!/bin/bash

ANIMAL=\"Dog\"
echo \"$ANIMALs are the best.\"
exit 

However, I

相关标签:
5条回答
  • 2020-12-11 15:26

    With braces: echo "${ANIMAL}s are the best."

    With quotes: echo "$ANIMAL"'s are the best.'

    With printf: printf '%ss are the best.\n' "$ANIMAL"

    I wouldn't use the quotes one most of the time. I don't find it readable, but it's good to be aware of.

    0 讨论(0)
  • 2020-12-11 15:27

    Move your variable outside the quotes in echo :

    #!/bin/bash
    
    ANIMAL="Dog"
    echo $ANIMAL"s are the best."
    exit 
    

    OR :

    #!/bin/bash
    
    ANIMAL="Dog"
    echo "${ANIMAL}s are the best."
    exit 
    

    Both worked for me

    0 讨论(0)
  • 2020-12-11 15:39

    Just surround the variable's name with curly braces.

    #!/bin/bash
    
    ANIMAL="Dog"
    echo "${ANIMAL}s are the best."
    exit 
    
    0 讨论(0)
  • 2020-12-11 15:41

    Useless quotation, useless exit. A finished script needs no help to exit but the exit will bite you when sourcing that script.

    ANIMAL=Dog
    echo ${ANIMAL}s are the best.
    
    0 讨论(0)
  • 2020-12-11 15:42
    #!/bin/bash
    
    
    ANIMAL="Dog"
    echo "{$ANIMAL}s are the best."
    exit 
    

    The answer is no longer unique, but correct...

    0 讨论(0)
提交回复
热议问题