4

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:

  1. the double backslashes are not correct.
  2. the version is not parsed correctly.
Bool.Du
  • 43
  • 1
  • 6

4 Answers4

3

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
  • generally, the variables in double quotes should be interpreted. but if the "\" is followed by "$", the variables was not interpreted as a static string. understand! – Bool.Du Sep 05 '14 at 04:22
  • 1
    I like your answer because you use echo. – Bool.Du Sep 05 '14 at 04:24
1

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

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
264nm
  • 725
  • 4
  • 13
0

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.

Michaël Le Barbier
  • 6,103
  • 5
  • 28
  • 57