如何在 Bash 中将变量与字符串连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7707873/
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 00:56:24  来源:igfitidea点击:

How connect variable with a string in Bash?

linuxbash

提问by Elham abbasi

I am writing a bash script , I used 1 variable in my bash file like below

我正在编写一个 bash 脚本,我在我的 bash 文件中使用了 1 个变量,如下所示

list=`/home/ea/students'

I wrote below link in my bash but I got error

我在 bash 中写了以下链接,但出现错误

cat $list /admin.txt

Do you know how can I connect variable and string together?

你知道如何将变量和字符串连接在一起吗?

回答by Johnsyweb

Firstly you need to use single quotes (''') around strings, not backticks ('`')

首先,您需要'在字符串周围使用单引号 (' '),而不是反引号 ('`')

list='/home/ea/students'

To append a string to a variable, do the following:

要将字符串附加到变量,请执行以下操作:

list=${list}/admin.txt

Demo:

演示:

echo $list
/home/ea/students/admin.txt

回答by imm

Try this:

尝试这个:

list='/home/ea/students'
...
cat "${list}/admin.txt"

回答by Dimitre Radoulov

You can go with either:

你可以选择:

cat "$list/admin.txt"

In this case the braces '{}' are not mandatory as the / is not a valid identifier name character.

在这种情况下,大括号“{}”不是强制性的,因为 / 不是有效的标识符名称字符。

... or, if you need a variable, recent bashversions provide more concise way for appending:

...或者,如果您需要一个变量,最近的bash版本提供了更简洁的附加方式

bash-4.1$ list=/home/ea/students
bash-4.1$ list+=/admin.txt
bash-4.1$ printf '%s\n' "$list"
/home/ea/students/admin.txt