Bash variable character replacement ends up to an empty string or a command not valid

£可爱£侵袭症+ 提交于 2019-12-31 05:52:05

问题


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")

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"

fails with the following error

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?


回答1:


+ 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"

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.

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

For example:

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.

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.




回答2:


You don't need to use + to concatenate string in bash, change your command to

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



回答3:


My problem was not related only to the wrong concatenation, but also to the JQ library that after parsing the value from the JSon file was returning text between quotes.

In order to avoid JQ doing this, just add the -rawoutput parameter when calling JQ.



来源:https://stackoverflow.com/questions/20878992/bash-variable-character-replacement-ends-up-to-an-empty-string-or-a-command-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!