user1537366
user1537366

Reputation: 1187

Avoiding accidental execution of python scripts as bash scripts

I like to run my python scripts directly in bash like so

$ ./script.py

But sometimes I forget the shebang line #!/usr/bin/env python3, and it has the potential to overwrite a file named np if the script has import numpy as np (and if you click a few times when the ImageMagick import command is run).

What can I do to avoid such accidental execution of python scripts as bash scripts? Is there a way to block bash from executing a script that has an extension ".py" as a bash script?

Upvotes: -2

Views: 78

Answers (1)

BoppreH
BoppreH

Reputation: 10193

You can trap the "DEBUG" signal to inspect the command before execution. Then a simple extension check can block .py files but nothing else. You can also test the first line with head -n1 to see if it's the shebang.

Here's a proof of concept:

shopt -s extdebug; stop_cmd () {
    [ -n "$COMP_LINE" ] && return  # not needed for completion
    [ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return # not needed for prompt
    local this_command=$BASH_COMMAND;
    if [[ $this_command == *.py ]] && [[ "$(head -n 1 $this_command)" != '#!"* ]]; then
        echo "Blocking execution of Python script without shebang: $this_command"
        return 1
    else
        return 0
    fi
};
trap 'stop_cmd' DEBUG

Upvotes: 3

Related Questions