How to Escape Dollar Signs in Bash (2 Methods)


There are two methods you can use to escape dollar signs in Bash:

Method 1: Use Single Quotes when Defining Variables

my_file='c:\users\bobbi\data$new'

By using single quotes when defining a variable, you can prevent Bash from converting $ into a variable.

If you instead use double quotes, then Bash will automatically convert $ into a variable.

Method 2: Use Backslash to Escape Dollar Sign

my_file="c:\users\bobbi\data\$new"

If you do decide to use double quotes when defining a variable, then you can use a backslash immediately before the $ character to escape it.

The following examples show how to use each method in practice.

Example 1: Use Single Quotes to Escape Dollar Signs in Bash

Suppose that we have a folder located at the following path:

  • c:\users\bobbi\data$new

Suppose that we attempt to use the following syntax to define this variable path as a string in Bash:

my_file="c:\users\bobbi\data$new"

The following screenshot shows how to use this syntax in practice:

When we use the echo command to view the variable, we can see that Bash automatically converts $new to a variable and removes it from the string.

To escape this dollar sign when defining this string, we could instead use single quotes:

my_file='c:\users\bobbi\data$new'

The following screenshot shows how to use this syntax in practice:

Bash escape dollar signs using single quotes

Since we used single quotes when defining the variable, Bash did not convert the $ into a variable.

Example 2: Use Backslash to Escape Dollar Signs in Bash

Once again suppose that we have a folder located at the following path:

  • c:\users\bobbi\data$new

Another way to escape the dollar sign when defining the file path as a string is to use a backslash in front of the dollar sign:

my_file="c:\users\bobbi\data\$new"

The following screenshot shows how to use this syntax in practice:

Bash escape dollar sign using backslash

By using a backslash right before the dollar sign, we are able to escape the dollar sign and keep it in the string.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

How to Remove Spaces from String in Bash
How to Get Last Word of a String in Bash
How to Split a String Using Multiple Delimiters in Bash

Leave a Reply