Search code examples
rubybashbackslash

Create single backslash in Ruby


I would like to execute:

echo aA1.-_#*~^%\':\;?!@=/ | passwd --stdin user

It can be logged in with "aA1.-_#*~^%':;?!@=/".

I tried

str = "aA1.-_#*~^%':;?!@=/"
password = str.gsub("'", "\\\\'").gsub(";", "\\;")

passwd_command = "echo" +
  " #{password}" +
  " | passwd" +
  " --stdin user"

but the result was:

echo aA1.-_#*~^%\\':\\;?!@=/ | passwd --stdin aaa

I executed it:

[root@localhost ~]# echo aA1.-_#*~^%\\':\\;?!@=/ | passwd --stdin aaa
>

The command has not finished. Do you have any suggestions?


Solution

  • I don't know shellwords, but aren't the default Ruby methods sufficient? Like %q and %x?

    See for example: https://simpleror.wordpress.com/2009/03/15/q-q-w-w-x-r-s/