I was working on a Bash script to help partition a hard drive correctly, and I came across a strange problem where I had to append a number to a variable. It took me a while to get the outcome right since I'm not very experienced with Bash but I managed to make something temporary.
Here is an example of what I was building:
#!/bin/bash
devName="/dev/sda"
devTarget=$devName\3
echo "$devTarget"
The variable devName
was /dev/sda
, but I also needed a variable set for the 3rd partition later on in the script so I used the \
symbol, which let me add the number 3
to the /dev/sda
to make the output /dev/sda3
Even though the \
symbol worked, I was just wondering if this is the right way to do something like this. I used this because in Python it's used to ignore the following character for quotations and such, but I wanted to do the opposite in this situation, so surprisingly it worked. If this isn't the best way to go about adding to variables, could someone please show an example of the best way to do this in Bash.
\3
. It must be something with the order of expansions and escape removing, I guess? – Jan 20 '18 at 06:42$
, whatever else should be escaped). I'd change the title of this question to something more about . Possibly "Backslash in variable substitution". – Jan 20 '18 at 07:00\3
, it's not a surprised thing, if you don't want 3 be as part of your variableNamedevName3
you should have escape it to print itself as alone like you do\\
to print\
and since\
is special character in shell so it interpret as its meaning apart of variable name. – αғsнιη Jan 20 '18 at 07:05variable="special"
and changedevTarget=$devName/my/$variable/partition
you'll get/dev/sda/my/special/partition
. You just need the/
to distinguish the end of the variable name and the beginning of the string. You don't even need to double-quote the end-result. If you don't want the/
just use\\
. – Robert Riedl Jan 20 '18 at 18:04\3
isn't considered part of the name. Then the backslash causes the next character to be interpreted literally, without any special meaning, but3
doesn't have a special meaning anyway so\3
is just equivalent to3
. You could edit the answer to mention this if you like. – David Z Jan 20 '18 at 22:44