Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we separate variables from letters in shell scripting?

Tags:

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

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

However, I got " are the best." printed out instead because the s in $ANIMALS is not separated from the variable. How do I separate it?

like image 850
John Hoffman Avatar asked Aug 19 '13 17:08

John Hoffman


People also ask

How do you escape characters in shell script?

In a shell, the most common way to escape special characters is to use a backslash before the characters. These special characters include characters like ?, +, $, !, and [. The other characters like ?, !, and $ have special meaning in the shell as well.

What does this %s mean in shell scripting?

-S filename ] can be read as "not is-socket filename". So the command is checking whether a "socket" (a special kind of file) exists with each name in the loop. The script uses this command as the argument to an if statement (which can take any command, not just [ ) and sets DOWN to true if any of them does not exist.


2 Answers

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.

like image 54
kojiro Avatar answered Sep 30 '22 02:09

kojiro


Just surround the variable's name with curly braces.

#!/bin/bash  ANIMAL="Dog" echo "${ANIMAL}s are the best." exit  
like image 24
phlogratos Avatar answered Sep 30 '22 02:09

phlogratos