5

I'm trying to write a shell script in RHEL which will execute grub-md5-crypt and the user will type their password.

Now the problem is how can I grab the encrypted md5 hash displayed to the user in the shell script?

I tried to figure this out but command redirection will not work here. So how can I get the md5 encrypted text in the shell script after the script has executed grub-md5-crypt?

Tarun
  • 266

2 Answers2

10
result=$(grub-md5-crypt | grep xy)
echo $result

If grub-md5-crypt prints to stderr use:

result=$(grub-md5-crypt 2>&1 | grep xy)
echo $result
AlphaBeta
  • 294
  • 1
  • 4
  • It workes if I directly execute it in the shell. But not in my shell script. – Tarun Sep 17 '14 at 16:03
  • @Tarun This works in all shells. If it doesn't work for you, you made some other mistake, or you have an unrelated problem. Ask a new question if you can't figure it out, and be sure to post your code and say how it doesn't work (do you get errors, what happens, etc.). – Gilles 'SO- stop being evil' Sep 17 '14 at 20:27
  • thank you for mentioning 2>&1 for getting result from stderr – kimbaudi Jul 17 '19 at 08:26
2

If it doesn't work in your shell script you might want to use bash. Just add:

#!/bin/bash

It must be in the first line of your file!

This means your script will be using bash interpreter other than normal shell's one (/bin/sh).

Completing noEntry's answer, you can also save output to a file.

grub-md5-crypt | grep xy > output

Or:

result=$(grub-md5-crypt 2>&1 | grep xy)
echo $result > output

This will generate a file names output with whatever would have been printed on screen.