6

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?

0

2 Answers 2

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
4
  • 1
    It workes if I directly execute it in the shell. But not in my shell script.
    – Tarun
    Commented Sep 17, 2014 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.). Commented Sep 17, 2014 at 20:27
  • thank you for mentioning 2>&1 for getting result from stderr
    – kimbaudi
    Commented Jul 17, 2019 at 8:26
  • @Gilles'SO-stopbeingevil' this isn't true, I have the same problem. Output appears on screen but CANNOT be assigned to a variable for unknown reasons.
    – b264
    Commented Apr 24 at 1:42
3

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.

Not the answer you're looking for? Browse other questions tagged .