Bash function for `pv fileName | sha256sum -b`

aliasbash

I'm on Linux Mint 18.2 with GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu).

I'd like to re-define sha256sum with my function defined in .bash_aliases for it to show progress because I use it for 100+GB files often.

The function follows:

function sha256sum {

    if [ -z "$1" ]
    then
    {
        \sha256sum --help
    }
    else
    {
        pv $1 | \sha256sum -b
    }
    fi

}

But there are some culprits, which I can't explain.

For one it behaves unexpectedly, I somehow managed to force it to "eat" the parameter.

Specifically, the following file:

-rw-r--r-- 1 root root 2.0K Jul 24 12:29 testdisk.log

Now it outputs the file's size, never-ending:

vlastimil@vb-nb-mint ~ $ sha256sum testdisk.log 
1.92KiB 0:00:00 [40.8MiB/s] [====================================================>] 100%            
1.92KiB
1.92KiB
1.92KiB
1.92KiB
1.92KiB
1.92KiB
1.92KiB
1.92KiB
1.92KiB
1.92KiB
1.92KiB
...
...
...
^C
[1]+  Stopped                 pv $1 | \sha256sum -b

What am I doing wrong? I tried different structure, with and without braces, with and without semicolon, and like for an hour no better result than this one.

EDIT1:

Removing the \ sign for the function to look like:

function sha256sum {

    if [ -z "$1" ]
    then
    {
        sha256sum --help
    }
    else
    {
        pv "$1" | sha256sum -b
    }
    fi

}

Results in:

1.92KiB 0:00:00 [56.8MiB/s] [====================================================>] 100%            
1.92KiB
1.92KiB
1.92KiB
1.92KiB
...
...
...
^C
[2]+  Stopped                 pv "$1" | sha256sum -b

Best Answer

Each of the occurences of \sha256sum in your function's body is a recursive call to that function. Prefixing the name with a backslash prevents it from being interpreted as an alias, but does not prevent interpreting it as a function.

You want to write command sha256sum instead of \sha256sum; for example, keeping the layout of your original function:

function sha256sum {

    if [ -z "$1" ]
    then
    {
        command sha256sum --help
    }
    else
    {
        pv "$1" | command sha256sum -b
    }
    fi

}
Related Question