bash that bin
bash that bin

Reputation: 3

How to see the command that ran a bash function?

I am trying to make shortcuts for doing hashing. code is in .bashrc

code:

hash() {
    python3 -c "import hashlib; print(hashlib.$0($1).hexdigest())"
}

alias sha256=hash
alias md5=hash
alias sha1=hash
alias sha512=hash

but when i did sha256 hello it said

Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: module 'hashlib' has no attribute 'bash'

Upvotes: 0

Views: 40

Answers (2)

chepner
chepner

Reputation: 531375

Aliases are expanded before $0 is set, and $0 refers the process name, not the name of a shell function being called. Instead of aliases, define additional functions:

hash() {
  python3 -c "import hashlib; print(hashlib.$1($2).hexdigest())"
}

sha256 ()  { hash sha256 "$1"; }
md5 ()  { hash md5 "$1"; }
sha1 ()  { hash sha1 "$1"; }
sha512 ()  { hash sha512 "$1"; }

Also, it's better to pass the function name and argument as shell arguments, rather than dynamically constructing a Python script. Something like

hash() {
  python3 -c '\
import sys
import hashlib
fname, s = sys.argv[:2]
f = getattr("hashlib", fname)
print(f(s).hexdigest())' "$@"
}

Upvotes: 1

Rakesh B E
Rakesh B E

Reputation: 892

I think you have a file called haslib.py. rename the name so python interpreter will load the buit in module.

Upvotes: 0

Related Questions