How to pass unknown command line arguments containing special characters (bash)?

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.

Harold

Posted 2019-10-29T00:12:34.863

Reputation: 1

1

First of all, welcome to Super User! We are always glad to help, but you apparently have two Super User accounts: this one and this one. Please take the time to utilize the following Help Center tutorial and ask the Super User staff to merge your accounts: I accidentally created two accounts; how do I merge them?

– Run5k – 2019-10-29T00:40:00.453

This question has an answer here: https://unix.stackexchange.com/a/379190/58455

– ecube – 2019-10-31T00:37:30.857

Answers

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"
    

user1686

Posted 2019-10-29T00:12:34.863

Reputation: 283 655