Bash – Backslash in variable substitution in Bash

bashquotingshell-scriptvariable substitution

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.

Best Answer

The safe way to interpolate a variable into a string is to use ${var_name}. For example:

#!/bin/bash

devName="/dev/sda"
devTarget="${devName}3"

echo "$devTarget"

This way Bash has no doubts of what the variable to interpolate is.

Btw, interesting how devTarget=$devName\3 works. I'm not sure why.

Related Question