Bash变量字符替换最终导致一个空字符串或命令无效 [英] Bash variable character replacement ends up to an empty string or a command not valid

查看:86
本文介绍了Bash变量字符替换最终导致一个空字符串或命令无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个Shell脚本,以通过JQ从JSON文件中检索变量内容. JSON文件为字符串格式(无论是真实字符串还是数字),并且要在我的bash脚本中检索变量,我都做了类似的事情

I am working on a shell script to retrieve variable content from a JSON file via JQ. The JSON file is in string format (no matter whether this is a real string or a number) and to retrieve the variable in my bash script I did something like this

my_domain=$(cat /vagrant/data_bags/config.json | jq ."app"[0]."domain")

上面的代码曾经回显了以"mydomain"开头和结尾的引号.我虽然这是echo命令的正常行为.但是,在将变量与另一个shell命令连接时,系统会引发错误.例如,以下命令

The above code once echoed results in "mydomain" with a beginning and a trailing quote sign. I though this was a normal behaviour of the echo command. However, while concatenating my variable with another shell command the system raise an error. For instance, the following command

cp /vagrant/public_html/index.php "/var/www/"+$my_domain+"/index.php"

失败,并出现以下错误

cp: cannot create regular file `/var/www/+"mydomain"+/index.php': No such file or directory

在此阶段,我无法确定是我用加号进行了错误的串联,还是变量有效地包含了引号,而引号在任何情况下最终都会产生错误.

At this stage, I wasn't able to identify whether it's me doing the wrong concatenation with the plus sign or the variable is effectively including the quotes that in any case will end up generating an error.

我试图替换变量中的引号,但最终导致系统引发找不到命令"错误.

I have tried to replace the quotes in my variable, but I ended up getting the system raising a "Command not found" error.

有人可以暗示我在做什么错吗?

Can somebody suggest what am I doing wrong?

推荐答案

+不用于bash(或perl或php)中的字符串连接.只是:

+ is not used for string concatenation in bash (or perl, or php). Just:

cp /vagrant/public_html/index.php "/var/www/$my_domain/index.php"

在带双引号的文本字符串中包含一个变量称为 interpolation ,这是我们需要$前缀以表明这是一个变量的原因之一.特别是在单引号字符串内不进行插值.

Embedding a variable inside a double-quoted text string is known as interpolation, and is one of the reasons why we need the $ prefix, to indicate that this is a variable. Interpolation is specifically not done inside single quoted strings.

大括号${my_domain},因为/目录分隔符不是变量名中的有效字符,因此没有歧义.

Braces ${my_domain} are not required because the / directory separators are not valid characters in a variable name, so there is no ambiguity.

例如:

var='thing'
echo "Give me your ${var}s"    # Correct, appends an 's' after 'thing'
echo "Give me your $vars"      # incorrect, looks for a variable called vars.

如果一个变量(如"vars")不存在,那么(默认情况下)它不会抱怨,它只会给出一个空字符串.在c-shell(csh或tcsh)中更需要大括号(括号),这是因为用于修改变量的附加语法(其中包括特殊的结尾字符).

If a variable (like 'vars') does not exist then (by default) it will not complain, it will just give an empty string. Braces (graph brackets) are required more in c-shell (csh or tcsh) because of additional syntax for modifying variables, which involves special trailing characters.

这篇关于Bash变量字符替换最终导致一个空字符串或命令无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆