Linux command equivalent of hash() in python
Question: In my program In have a log directory. Name of the log directory is very long
so in my python script I used hash function to get the unique code and append
it to fixed string ie:

    
    
    LOG_DIR = "abcdefghijklmnopqrstuvwxyz"
     log_dir_hashed = hash(LOG_DIR)
     new_log_dir = "log_%s" %log_dir_hashed
    

Since I am new to python please tell me if anything can go wrong with above
code? also How to do similar thing in shell script so that result of the
python directory name and shell directory name obtained after hashing is same.


Answer: [`hash()`](https://docs.python.org/3/library/functions.html#hash) is an
implementation detail of python and [`__hash__`
dunders](https://docs.python.org/3/reference/datamodel.html#object.__hash__)
can even override what it does, so you shouldn't be using it like that. It
also has some possibly [surprising
properties](http://stackoverflow.com/questions/7648129/when-is-a-python-
objects-hash-computed-and-why-is-the-hash-of-1-different), like:

    
    
    # This is not a collision produced by the used hashing method, it is
    # how hash() functions. The result though is a collision.
    >>> hash(-2) == hash(-1)
    True
    

Use a well known hash like MD5 or SHA1 etc. If you need cryptographically
secure log dirs, choose a suitable hash based on that. Have a look at
<https://docs.python.org/3/library/hashlib.html>. These have equivalent
command line tools available.

For example:

    
    
    from hashlib import md5
    
    log_dir_hashed = md5('abcdefghijklmnopqrstuvwxyz'.encode('utf-8')).hexdigest()
    new_log_dir = "log_%s" % log_dir_hashed
    

Comparing python:

    
    
    >>> md5('abcdefghijklmnopqrstuvwxyz'.encode('utf-8')).hexdigest()
    'c3fcd3d76192e4007dfb496cca67e13b'
    

and equivalent command line (one way to do it):

    
    
     % echo -n 'abcdefghijklmnopqrstuvwxyz' | md5sum - | awk '{print $1}'
    c3fcd3d76192e4007dfb496cca67e13b
    

