简体   繁体   中英

echo and run command after that

I would like to have this command to be run in one line

echo The current version MD5: md5sum xxx.jar
echo The new version MD5: md5sum zzz.jar

I would expect the result:

> The current version's MD5: 2791f2d6e9ac9e6a6a08919f031b2633

> The new version's MD5: 2791f2d6e9ac9e6a6a08919f03000000

Question is how to run them so that they print out in one line

You can use the command substitution :

echo "The .... MD5: $(md5sum xxx.jar)"

or

echo "The .... MD5:" `md5sum xxx.jar`

EDIT

If the file xxx.jar does not exist, the output looks like :

md5sum: xxx.jar: No such file or directory
The current version MD5:

But you can use a bash function to print the md5 or an error.

#!/bin/bash

print_md5() {
    local MSG=$1
    local FILE=$2
    local MD5
    MD5=($(md5sum $FILE 2>&1))
    # MD5 is an array, [0] contains the md5, [1] contains "file"
    if [ $? -ne 0 ]; then
        echo "MD5 error '$FILE'"
    else
        echo "$MSG: ${MD5[0]}"
    fi
}

print_md5 "The current version MD5" xxx.jar
print_md5 "The new version MD5" zzz.jar

Example: (if zzz.jar does not exist)

The current version MD5: 5d8b35c0ac55c90e6829ee9a54437058
MD5 error 'zzz.jar'

You need to parse out the MD5 from the output of md5sum, so:

echo "The current version MD5:`md5sum xxx.jar | awk '{ print $1}'`"

or you can go with the parentheses approach too if you don't like to many funny quotes:

echo "The current version MD5:$(md5sum xxx.jar | awk '{ print $1}')"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM