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

Fix arguments for sourced script #147

Merged
merged 1 commit into from
Dec 8, 2023
Merged

Conversation

baodrate
Copy link
Contributor

@baodrate baodrate commented Dec 7, 2023

Quality of life improvement for handling arguments, mostly useful for testing things on the command line.

Proposed Changes

Shifts around the arguments (and sets argv[0] to the target script) so that they would be as you expect if the call at the end of bashio was exec "$@" instead of source "$@".

From the bash manual:

If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged.

This makes handling arguments annoying, because there's no way other than testing [[ $1 = $EXPECTED_SCRIPT_PATH ]] to see if arguments were passed on the command line. And if arguments are passed, there's no way to access the true script's path

Example

given example.sh:

#!/command/with-contenv bashio

bashio::log.info "0='${0}'"
bashio::log.info "1='${1:-NONE}'"
bashio::log.info "2='${2:-NONE}'"

exec /bin/echo "$@"

prior to change:

$ /example.sh
[23:21:36] INFO: 0='/usr/bin/bashio'
[23:21:36] INFO: 1='/example.sh'
[23:21:36] INFO: 2='NONE'
/example.sh
$ /example.sh foo bar
[23:21:39] INFO: 0='/usr/bin/bashio'
[23:21:39] INFO: 1='foo'
[23:21:39] INFO: 2='bar'
foo bar

after change:

$ /example.sh
[23:21:47] INFO: 0='/example.sh'
[23:21:47] INFO: 1='NONE'
[23:21:47] INFO: 2='NONE'
$ /example.sh foo bar
[23:21:51] INFO: 0='/example.sh'
[23:21:51] INFO: 1='foo'
[23:21:51] INFO: 2='bar'
foo bar

Shifts around the arguments and updates $0 so that they would be as you
expect if the script was exec'd instead of source'd
Copy link
Member

@frenck frenck left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes a lot of sense, thanks, @baod-rate 👍

../Frenck

@frenck frenck added the bugfix Inconsistencies or issues which will cause a problem for users or implementors. label Dec 8, 2023
@frenck frenck merged commit 8b96a70 into hassio-addons:main Dec 8, 2023
4 checks passed
@github-actions github-actions bot locked and limited conversation to collaborators Dec 10, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bugfix Inconsistencies or issues which will cause a problem for users or implementors.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants