I have a script that I'm currently working on. And I've run into an issue where I need to prompt a user to enter a string, then encrypt that with sha-512, and then insert it into a specific file

So far I have:

pass= grub-crypt --sha512

Which returns the hashed value I need. However, I'm running into the issue where sed will read the special characters from the hash.

I then tried:

sed -i.bak "20i$pass" /foo/bar

But that doesn't work. I assume it's still reading the special characters when it substitutes the variable for the characters in the string. So I wanted to try and add an escape character before every character in the string like this:

sed 's:\(.\{1\\}\)\1:g'

However, this isn't working for me either. I'm new to sed, so any explanation would be very helpful. Thank you.

  • It might help if you posted some example values of $pass for which you're having problems, the exact commands that you're using, and the results that you're getting. – G-Man Says 'Reinstate Monica' Oct 9 '14 at 15:50
  • If you want to capture the output of grub-crypt, you need something like pass=$(grub-crypt --sha512) – user2313067 Oct 9 '14 at 17:01

In cases where special characters such as * . / $ abound in text it's easiest not to use insert the text directly. The alternative is to add backslashes which is a drab manual solution.

Rather use the r sed function - which reads in the following file at the address specified (in this case line 20). Note there is no error handling in this code:

grub-crypt --sha512 > hash.tmp
sed -i.bak '20r hash.tmp /foo/bar      
rm hash.tmp  
  • Unfortunately that did not work, either. I think it is still reading the special characters in the hash. – Afflickted Oct 9 '14 at 14:46
  • updated answer - works for me with special chars like $5ks&-£££%()-$. – suspectus Oct 9 '14 at 15:31
  • 1
    @suspectus: I think the second variant in your first version of the answer should work. Did you really mean to post a revision in which $pass is not quoted at all? – G-Man Says 'Reinstate Monica' Oct 9 '14 at 15:49
  • @G-Man agreed - the variable needs to be quoted. I don't know what I was thinking of. – suspectus Oct 9 '14 at 16:32
  • So an example of the special characters in the has are '$', '.', and '/'. Otherwise. running the following script commands #!/bin/bash pass= grub-crypt ---sha-512 sed -i.bak '20i\ '$pass'' /foo/bar It then prints the hash of the password that I enter, and inserts two blank lines(at line 20) in the file that I'm trying to insert the hash too – Afflickted Oct 9 '14 at 16:35

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.