问题
I want to echo a Windows shared folder address to users in a Linux shell script, the address are strings like this: \\hostname\release\1.02A01. and the last string(1.02A01) is a version number, it's changed each time when I run the script. I tried something like this in sh (not bash ), but it doesn't work:
version=$1 # version number are get from the parameter
repository="\\\hostname\release\$version"
echo $repository # I get this: \hostname\dir$version
Here are the two errors:
- the double backslashes are not correct.
- the version is not parsed correctly.
回答1:
1) In unix/linux sh, the backslash("\") has to be escaped/preceded with a backslash("\").
2) The string concatenation you are doing INSIDE quotes is LITERAL, if you want the value of $version, you have to put it OUTSIDE the closing quote.
I put this in a shell ( shell1 ) in centos linux and executed it under "sh":
sh-4.1# cat shell1
version=$1
repository="\\\\hostname\\release\\"$version
echo $repository
This is the output:
sh-4.1# ./shell1 1.02A01 <br>
\\hostname\release\1.02A01
回答2:
To avoid needing to escape the backslashes, use single quotes instead of double quotes.
repository='\\hostname\release\'"$version"
The double quotes are needed for $version
to allow the parameter expansion to occur. Two quoted strings adjacent to each other like this are concatenated into one string.
回答3:
Ah the BASH escape trap.
Maybe try:
version=`echo $1`
repository='\''\hostname\release\'$version
Tested with:
~ $ cat stack
#!/bin/bash
string="1.02A01"
version=`echo $string`
repository='\''\hostname\release\'$version
echo $repository
~ $ bash stack
\\hostname\release\1.02A01
回答4:
Do not use echo
to output text and use printf
instead. The echo
command has several portability issues and the printf
function is much easier to use because it has a clear “print what I meant” part — the format string — with placeholders for text replacement.
repository="\\\\hostname\\release\\$version"
printf '%s\n' "$repository"
You should reserve the use of echo
for the most simple bits of information, like tracing messages, or even not use it at all.
来源:https://stackoverflow.com/questions/25678262/how-to-echo-a-double-backslash-plus-a-variable-version-number-like-hostname