Script to create shell aliases

Posted on

Problem

Can anybody find anything to pick apart in this script?

#  Copyright (c) 2019. Legorooj

import sys
import os

docstring = '''
add_alias [alias] [command]'''
if len(sys.argv) <= 1:
    print(docstring)
else:
    alias, cmd = sys.argv[1], sys.argv[2]
    print('Adding alias...')
    os.system(f'echo "alias {alias}={cmd}" >> ~/.bashrc && source ~/.bashrc')
    print('Alias added')

If ran like:

add_alias bob "echo bob", it adds an alias as if you ran

echo "alias bob="echo bob"" >> ~/.bashrc && source ~/.bashrc

Solution

We need to do some basic sanity checking of the inputs – alias names can’t contain whitespace, for example, and any newlines in the expansion will be treated as the end of the alias definition (and the following text will then be a new command in your .bashrc).

The source ~/.bashrc in the call to os.system() looks pointless, as that shell terminates immediately after.

The script is missing a shebang. (For example #!/usr/bin/env python)

The length check len(sys.argv) <= 1 is not enough, sys.argv[2] will crash with IndexError when there is only one script argument instead of two. (You probably meant to write len(sys.argv) <= 2)

I don’t think this script has enough value over adding aliases manually.

Leave a Reply

Your email address will not be published. Required fields are marked *