Hidden features of Bash
Shell scripts are often used as glue, for automation and simple one-off tasks. What are some of your favorite "hidden" features of the Bash shell/scripting language?
- One feature per answer
- Give an example and short description of the feature, not just a link to documentation
- Label the feature using bold title as the first line
See also:
- Hidden features of C
- Hidden features of C#
- Hidden features of C++
- Hidden features of Delphi
- Hidden features of Python
- Hidden features of Java
- Hidden features of JavaScript
- Hidden features of Ruby
- Hidden features of PHP
- Hidden features of Perl
- Hidden features of VB.Net
Solution 1:
insert preceding line's final parameter
alt-. the most useful key combination ever, try it and see, for some reason no one knows about this one.
press it again and again to select older last parameters.
great when you want to do something else to something you used just a moment ago.
Solution 2:
If you want to keep a process running after you log out:
disown -h <pid>
is a useful bash built-in. Unlike nohup
, you can run disown
on an already-running process.
First, stop your job with control-Z, get the pid from ps
(or use echo $!
), use bg
to send it to the background, then use disown
with the -h flag.
Don't forget to background your job or it will be killed when you logout.
Solution 3:
Almost everything listed under EXPANSION section in the manual
In particular, parameter expansion:
$ I=foobar
$ echo ${I/oo/aa} #replacement
faabar
$ echo ${I:1:2} #substring
oo
$ echo ${I%bar} #trailing substitution
foo
$ echo ${I#foo} #leading substitution
bar
Solution 4:
My favorite:
sudo !!
Rerun the previous command with sudo.
Solution 5:
More magic key combinations:
Ctrl + r begins a “reverse incremental search” through your command history. As you continue to type, it retrieves the most recent command that contains all the text you enter.
Tab completes the word you've typed so far if it's unambiguous.
Tab Tab lists all completions for the word you've typed so far.
-
Alt + * inserts all possible completions, which is particularly helpful, say, if you've just entered a potentially destructive command with wildcards:
rm -r source/d*.c
Alt + *rm -r source/delete_me.c source/do_not_delete_me.c
-
Ctrl + Alt + e performs alias, history, and shell expansion on the current line. In other words, the current line is redisplayed as it will be processed by the shell:
ls $HOME/tmp
Ctrl Alt + els -N --color=tty -T 0 /home/cramey