0

I am trying to figure out how to solve a problem with a "$" causing command expansion as part of a password field. How do you backslash the "$" when using command substitution (unknown) arguments? (i.e. $1, $2)

For example, in a script called 'testPass':

PASSWORD="$1"

echo $PASSWORD

If I type in:

testPass abcd123#$asd

Then the output is:

abcd123#

I have also tried single quotes (echo '$PASSWORD') as most people say online, however this just prints:

$PASSWORD

I have even tried using the printf command, which has also been mentioned online, as so:

printf '%q\n' '$PASSWORD'

However this does something similar, with the following output:

\$PASSWORD

I have searched for a long time to figure this out, however I am new to UNIX so I could be missing something I am unaware of. Please let me know if you have any ideas, thank you.

2

1 Answer 1

2

Your $1 assignments and 'echo' commands are working just fine. ($variables are only expanded once – if the expanded value has something that looks like another variable, that is not expanded again.)

The problem is that the missing $asd part never reaches the script to begin with.

The interactive shell command line performs variable expansion in exactly the same way as shell scripts do. When you type abcd123#$asd, the $asd part acts as a variable name and is expanded to (in this case) an empty value before the whole "testPass" command even runs.

So what you should quote is the command-line arguments themselves:

  • Variable expansion never happens inside single quotes:

    echo 'The password is abcd123#$asd'
    
    testPass 'abcd123#$asd'
    
  • Variables are expanded inside double-quotes, or when there are no quotes at all, but this can be avoided by escaping the $:

    echo The password is abcd123#\$asd
    
    testPass "abcd123#\$asd"
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.