mtekeli mtekeli - 2 months ago 6
Linux Question

Bash script to parse the output of a command

For instance command below

# sha512sum /home/bin.tar


gives this output:

7847a537b5db4434c075f18319caf12090cb0f19640190cbdf27e28a7b40b568127dfe9ec1c06604a87887ad403b618edeb42d1c41366b7a3e91d47b8d754ea4 /home/bin.tar


How can I assign only hash part of this output to a variable in bash in order to compare the calculated hash with other hash in another variable?

What I have tried only assigns the parts that matches condition in grep (I only need the first part):

#! /bin/sh

RESULT="$(sha512sum /home/bin.tar | grep -o " /home/bin.tar")"

echo "Result:"

echo $RESULT

exit


Output

Result:
/home/bin.tar

Answer

This should do it:

RESULT="$(sha512sum /home/bin.tar | cut -d' ' -f1)"

or

RESULT="$(sha512sum /home/bin.tar)"
RESULT="${RESULT%% *}"

or

RESULT="$(sha512sum /home/bin.tar | grep -o '^[^ ]*')"
Comments