Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possible function name collision and unexpected behavior due to this... #11

Closed
iusmac opened this issue May 17, 2021 · 0 comments
Closed

Comments

@iusmac
Copy link

iusmac commented May 17, 2021

Example of an undefined behavior:

my_funcs.sh

#!/usr/bin/env bash

log_success() {
    echo "another log_success() function from $BASH_SOURCE file that behaves differently"
}

test.sh

#!/usr/bin/env bash

source assert.sh # this file contains `log_success` function

source my_funcs.sh # this file also contains `log_success` function

# Example from README
expected="Hello"
actual="Hello"
assert_eq "$expected" "$actual"
if [ "$?" == 0 ]; then
  log_success "assert_eq returns 0 if two words are equal"
else
  log_failure "assert_eq should return 0"
fi

Output:

$ ./test.sh 
another log_success() function from my_funcs.sh file that behaves differently

To fix this the tester will be forced to rename all files where log_success function is used.

In advanced and much complex languages this is solved by using namespace mechanism. Since bash does not have something simillar we can craft namespaces simply by appending postfixes. I offer something like this to make the name as unique as possible:

log_success__torokmark () {
...
}

It is still comfortable when using any editor with an autocomplete engine.

Same story with tput codes inside variables with kinda generic names...

assert.sh/assert.sh

Lines 23 to 27 in a845148

RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
MAGENTA=$(tput setaf 5)
NORMAL=$(tput sgr0)
BOLD=$(tput bold)

@iusmac iusmac closed this as completed May 21, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant