1

I need to pass a string argument to a bash script that may contain a $ character. I don't want to force a \ to be inserted into the string outside of the script.

I tried to do that within the script, but couldn't figure out how to do this.

I had a similar issue at a later point in the script where I read in a string using "read". I could only get it to work by forcing the user to enter \$, which is not going to work for my application.

Any suggestions ?

1
  • Please explain or give some sample in how yourscript.sh is run, how are arguments passed and which kind of form. Commented Dec 14, 2012 at 13:33

1 Answer 1

3

If you don't want to have to escape the $ with a backslash, then the only other alternative is to surround the argument in single quotes. It's not possible to pass a 'naked' $ into your script because the shell will try to expand it. Using single quotes prevents shell expansion and will preserve the $.

For example:

myscript.sh '$foo'
Sign up to request clarification or add additional context in comments.

2 Comments

just to clarify: "it's not possible to pass a naked $, because the shell will expand it" really means, that the parent shell (where you run your script and provide arguments) will do the expansion. your script (running in a separate shell, which could be different from the parent shell) will never see the $args .
Thanks for your feedback. So to use this technique I guess I would write a small parent script in another shell type that won't expand the $, and then call my bash script with ' chars around my string. I'll give that a shot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.