3
\$\begingroup\$

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

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Thanks for the info! \$\endgroup\$ – Legorooj Jul 25 at 7:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.