Anders
Anders

Reputation: 6218

Simple solution for handling special characters in shell script input

I have a script which can overwrite values in a configuration file using options, for example, option --password can overwrite the setting in the configuration file (please note, this is not a discussion about security). However a password can contain contain characters, that are by bash, recognized as special characters, and those characters needs to be escaped or placed within " ".

Now I understand this. Although I can't say whom will be using this script in the future, so I would like to save he or she the trouble of having an incorrect password simply because, he or she forgot to place the password within " " or escape the special character.

What is the best way of dealing with such an input?

Thanks in advance.

Upvotes: 2

Views: 10445

Answers (2)

Derzu
Derzu

Reputation: 7146

There is a simple, but not very intuitive solution.

Encapsulate the character that is causing problem with '"CARACTER"'. And put all the password string between single quotes.

In my case the character that was causing the problem was the ' (single quote).

So if I have a command like that:

mycommand --password 'AAA'PWD' 

Replace by that:

mycommand --password 'AAA'"'"'PWD'

Now my password is a concatenation of three strings. Explanation:

'AAA' + "'" + 'PWD' # plus sign is just to make clear the contatenation.

That's works.

Upvotes: 1

clt60
clt60

Reputation: 63892

Hm.. Double quotes are not enough. Must use single quotes, because the rare situation, for example

mycommand --password "AAA$PWD" #is worng for any exported environment varname
mycommand --password 'AAA$PWD' #ok

Here is no way avoid this, because your users using a sort of shell, what have variable expansions and metachar-globbing. Your command getting already expanded args, so here is no way catch this in your script.

The only way - as @Bohemian told above - reading the password from a tty. You can write a simple wrapper around your current script, what will read the password from a tty and after will execute your script with properly escaped --pasword argument.

Upvotes: 5

Related Questions