help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: feature request: built-in variable for the whole previous command in


From: Koichi Murase
Subject: Re: feature request: built-in variable for the whole previous command input
Date: Fri, 9 Jul 2021 19:03:22 +0900

2021年7月9日(金) 18:16 Ante Bilandzic <abilandzic@gmail.com>:
> There is a built-in variable $_ which retrieves the last word (argument) of
> the previous command input. Would it be possible to add in the same fashion
> a new built-in variable that retrieves the whole previous command input
> (command + all its arguments)?

You can achieve that with the DEBUG trap, which is also the accepted
answer of the Stack Overflow page you mentioned. It's not mentioned on
the Stack Overflow page, but if you want to use $previous_command
globally, you need to additionally run `set -T'.

> At Stackoverflow I was pointed to
> https://stackoverflow.com/questions/6109225/echoing-the-last-command-run-in-bash
> . But none of these suggestions and workarounds are really up to my taste
> (with them scripts get longer and not shorter, as intended with my feature
> request).

It's just two-line addition of "set -T" & "trap DEBUG". I think it's
not convincing to add a new special variable just to reduce the two
lines.

> Use case: We can then write very compactly and elegantly in the scripts
> code snippets like this:
>
> some-command-input || { echo $requested-new-built-in-variable; return 1; }

If the number of use cases is limited, you should instead define a
shell function for each use case. For example for the above case, you
can define a function

function myeval {
  local __command=$1
  eval "$__command"; local __exit_status=$?
  ((__exit_status)) && echo "$__command"
  return "$__exit_status"
}

and write it in an even more compact way:

myeval 'some-command-input' || return 1

--
Koichi



reply via email to

[Prev in Thread] Current Thread [Next in Thread]