busybox-w32 icon indicating copy to clipboard operation
busybox-w32 copied to clipboard

$_ is unreliable

Open ale5000-git opened this issue 5 years ago • 1 comments

Create a script named script_name.sh:

#!/usr/bin/env ash
LAST_COMMAND="$_"

if test -n "$LAST_COMMAND"; then SCRIPT="$LAST_COMMAND"; else echo 'ERROR: The script name cannot be found'; return 1 2>&- || exit 1; fi;
unset LAST_COMMAND
unset _
echo "$SCRIPT"

Inside busybox ash run . ./script_name.sh 2 times.

Here the result:

~ $ . ./script_name.sh
ERROR: The script name cannot be found
~ $ . ./script_name.sh
./script_name.sh

ale5000-git avatar Mar 27 '19 14:03 ale5000-git

$_ isn't unreliable, it's just not specified in POSIX and does different things in different shells.

The bash man page says:

At shell startup, set to the absolute pathname used to invoke the shell or shell script being executed as passed in the environment or argument list. Subsequently, expands to the last argument to the previous command, after expansion. Also set to the full pathname used to invoke each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file currently being checked.

busybox-w32 ash, in common with upstream BusyBox and dash, only implements the second sentence, though this isn't documented in the dash man page.

Using $_ to determine which script is being executed is non-portable.

rmyorston avatar Mar 28 '19 08:03 rmyorston