'I have a problem trying to put single quotes around a text

I have a password that has special character with an exclamation point.

ABcD!987zyz12388

I'd like to put single quotes around it. This password is fetched and saved to a variable.

$mypass=`fetchpwd $sourceserver $loginacct`;
$mypass="'$mypass'";

print "My password is: $mypass\n";

The return looks like this

My Password is 'ABcD!987zyz12388
'

The end single quote went on the next line. How can I have the last single quote right after the last 8 to something like this 'ABcD!987zyz12388'



Solution 1:[1]

You have a good answer already, but I wanted to share a little programmer trick that might have helped you work out what the problem was by yourself.

You thought that it was adding the quote to your string that was causing the problem. And your program demonstrates that:

$mypass=`fetchpwd $sourceserver $loginacct`;
$mypass="'$mypass'";

print "My password is: $mypass\n";

When you're investigating data being "corrupted" like this, one good first step is to identify exactly when the corruption occurs. And you can do that by printing your data whenever there's a chance that it changes. In this case, it's a good idea to print $mypass as soon as it is first set and before you do anything with it:

$mypass=`fetchpwd $sourceserver $loginacct`;
print "My password is: $mypass\n";
$mypass="'$mypass'";

print "My password is: $mypass\n";

Now, that would have given you two newline characters (the one you explicitly print, but also the extra one that you get from fetchpwd - the one that is causing your problems. And sometimes, two consecutive newlines are hard to spot. So it's a good idea to put characters around values that you're trying to print. I like to use <...>:

$mypass=`fetchpwd $sourceserver $loginacct`;
print "My password is: <$mypass>\n";
$mypass="'$mypass'";

print "My password is: <$mypass>\n";

That would have shown you that the extra newline was present right from the start and, therefore, you adding quotes around it wasn't what was corrupting it. And, hopefully, it would have led to you investigating exactly what was returned by fetchpwd.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dave Cross