简体   繁体   中英

Bash - what's the difference between reading a variable and directly assigning it?

Just out of curiosity- what is the difference in the following..

I have a script and I'm converting from KB to MB. I'm using command substitution to assign variables, but just don't see the difference in assigning them as follows:

backup_size=$(echo "$client_kb/1024" | bc -l)

&

read backup_size < <(echo "$client_kb/1024" | bc -l)

What is the need for each way of doing things?

Thanks

For a simple value like a number, there's no difference. But try it with values that contain trailing spaces or more than one line:

#! /bin/bash
func () {
    printf $'1  2\n3   '
}

command_substitution=$(func)
read process_substitution < <(func)

set -xv
[[ "$command_substitution" == "$process_substitution" ]]

Other than what @choroba mentioned. It also has impact on error handling . Consider a scenario where you can use the output from sample_func only if it returned a successful error code.

sample_func() {
    echo "Hello world"
    return 1
}

command_substitution=$(sample_func)
rc=$?
echo "Error: $rc"
echo "command_substitution: $command_substitution"

echo '---'

read process_substitution < <(sample_func)
rc=$?
echo "Error: $rc"
echo "process_substitution: $process_substitution"

Ouput:

Error: 1
command_substitution: Hello world
---
Error: 0
process_substitution: Hello world

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