Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It's not working for me in a non-interactive Bash script on Bash 4.4.

$_ is nto documented in the man page but is in the Info manual. It is not only set to the last argument of a command but also to the script name on script startup.

  $ bash --version
  GNU bash, version 4.4.20(1)-release (i686-pc-linux-gnu)
  [ ... ]
Contents of script:

  $ cat underscore.sh
  #!/bin/sh
  # ^^ mistake here, should be /bin/bash

  test -e foo && echo $_ exists

  echo 'value of $_' = $_
Test:

  $ touch foo
  $ ./underscore.sh
  ./underscore.sh exists
  value of $_ = ./underscore.sh
I'm seeing nothing but the behavior of $_ being set to the script, and not affected.

But at the interactive prompt:

  $ test -e foo && echo $_ exists
  foo exists
This doesn't look like something I can rely on in scripts.

In the first place, I code in POSIX, except in the rare situation of making something that is strictly geared toward Bash.

Magic global variables subject to hidden side effects are garbage; I already feel dirty enough when I have to use $?.

This piece of crap also breaks under the DEBUG trap:

  $ debug() {
  > :
  > }
  $ trap debug DEBUG
  $ test -e foo && echo $_ exists
  debug exists
  $ test -e bar && echo $_ exists
  !1!
(That !1! is how non-zero exit status is printed in my setup.)

Sorry, I'm not going back to a 1978 way of writing shell tests, in order to use some broken magic variable.



Wow, I wasn’t aware of all these shortcomings! I will stop using it in my scripts too.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: