summaryrefslogtreecommitdiff
path: root/src/content/tils/2020/11/12/useful-bashvars.adoc
blob: 84b93c323d44cb52a2e10427d345f7c9613afb02 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
= Useful Bash variables
:categories: shell

:bash:                   https://www.gnu.org/software/bash/
:bash-bang-bang:         https://www.gnu.org/software/bash/manual/bash.html#Event-Designators
:bash-dollar-underscore: https://www.gnu.org/software/bash/manual/bash.html#Special-Parameters

{bash}[GNU Bash] has a few two letter variables that may be useful when typing
on the terminal.

== `!!`: the text of the last command

The {bash-bang-bang}[`!!` variable] refers to the previous command, and I find
useful when following chains for symlinks:

[source,shell]
----
$ which git
/run/current-system/sw/bin/git
$ readlink $(!!)
readlink $(which git)
/nix/store/5bgr1xpm4m0r72h9049jbbhagxdyrnyb-git-2.28.0/bin/git
----

It is also useful when you forget to prefix `sudo` to a command that requires
it:

[source,shell]
----
$ requires-sudo.sh
requires-sudo.sh: Permission denied
$ sudo !!
sudo ./requires-sudo.sh
# all good
----

Bash prints the command expansion before executing it, so it is better for you
to follow along what it is doing.

== `$_`: most recent parameter

The {bash-dollar-underscore}[`$_` variable] will give you the most recent
parameter you provided to a previous argument, which can save you typing
sometimes:

[source,shell]
----
# instead of...
$ mkdir -p a/b/c/d/
$ cd a/b/c/d/

# ...you can:
$ mkdir -p a/b/c/d/
$ cd $_
----

== Conclusion

I wouldn't use those in a script, as it would make the script terser to read, I
find those useful shortcut that are handy when writing at the interactive
terminal.