Escape dollar sign in string by shell script
As you know, a dollar sign marks a variable. You have to take it into account when you are typing it.
You can escape the dollar
./dd.sh "sample\$name.mp4"
or just type it with single quotes
./dd.sh 'sample$name.mp4'
To check if there is a dollar sign in a variable, do
[[ $variable == *\$* ]] && echo 'I HAZ A DOLAR!!!' || echo 'MEH'
One option:
# Replace occurrences of $ with \$ to prevent variable substitution:
filename="${filename//$/\\$}"
I just realized my prompt was showing foo
rather than foo$bar$baz
as the name of the current branch. foo$bar$baz
was getting assigned to PS1
and $bar
and $baz
were then expanded. Escaping the dollar signs before including the branch name in PS1
prevents unwanted expansions.
Your issue is not with the echo
but with the assignment to $filename
.
You say
filename="sample$name.mp4"
This will interpolate the string, which means expanding the variable $name
. This will result in $filename
having the value sample.mp4
(since $name
is presumably undefined, which means it expands to an empty string)
Instead, use single quotes in the assignment:
filename='sample$name.mp4'
echo "$filename"
will now result in the expected sample$name.mp4
. Obviously, echo '$filename'
will still just print $filename
because of the single quotes.