Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent a command being executed from a source'd file in Bash

Tags:

bash

shell

For security purposes, how can I prevent a command being executed in a file that is source'd? For example:

#!/bin/sh
source file.cfg

Wanted:

get="value"

Unintended:

command
like image 460
Robin pilot Avatar asked Dec 05 '22 03:12

Robin pilot


1 Answers

You could use a mechanism like in Python. Define variables and/or functions and put executable commands into a conditional block:

#!/bin/bash

# Variables and functions comes here
a=1
b=2

function foo() {
    echo "bar"
}

# Put executable commands here
if [ "$0" = "$BASH_SOURCE" ] ; then
    foo
fi

If you chmod +x the file and run it or run it through bash file.sh the executable commands in the conditional statement will get executed. If you source the file only variables and functions will get imported.

like image 104
hek2mgl Avatar answered Mar 03 '23 05:03

hek2mgl