bash 我们如何在 shell 脚本中将变量与字母分开?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18320133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:18:21  来源:igfitidea点击:

How do we separate variables from letters in shell scripting?

bash

提问by John Hoffman

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

我尝试打印“狗是最好的”。使用这个 bash 脚本。

#!/bin/bash

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

However, I got " are the best." printed out instead because the sin $ANIMALSis not separated from the variable. How do I separate it?

但是,我得到了“是最好的”。而是打印出来,因为sin$ANIMALS没有与变量分开。我如何分离它?

回答by kojiro

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

带牙套: echo "${ANIMAL}s are the best."

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

带引号: echo "$ANIMAL"'s are the best.'

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

使用 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.

大多数时候我不会使用引号。我不觉得它可读,但知道它很好。

回答by phlogratos

Just surround the variable's name with curly braces.

只需用花括号将变量名括起来。

#!/bin/bash

ANIMAL="Dog"
echo "${ANIMAL}s are the best."
exit 

回答by iamauser

#!/bin/bash


ANIMAL="Dog"
echo "{$ANIMAL}s are the best."
exit 

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

答案不再是唯一的,而是正确的……

回答by Imane Fateh

Move your variable outside the quotes in echo :

将变量移到 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

两者都对我来说有效

回答by user unknown

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.