5 Handy Bash Tricks in 2 Minutes

Jacob Herrington (he/him) - Aug 12 '19 - - Dev Community

This article should only take you a couple of minutes to read, and you'll walk away with a handful of the bash tricks I constantly use.

1. Make a directory and navigate to it

mkdir /foo/bar && cd $_
Enter fullscreen mode Exit fullscreen mode

In bash, $_ is a reference to the last parameter that was used. It can come in handy all over the place. Generally, the best use for $_ is to avoid repeating yourself in cases like the above example.

2. Backup a file without typing it twice

cp /some/path/to/file.txt{,.bak}
Enter fullscreen mode Exit fullscreen mode

This feature of bash is called brace expansion, it has a ton of useful applications. This is just one I sometimes use when I want to create a copy of a file quickly.

3. Backup every file in a folder

for file in * ; do cp "$file" "$file".bak; done
Enter fullscreen mode Exit fullscreen mode

In this oneliner, we are taking advantage of bash's ability to loop over the files in a directory.

Frequently, I find myself using this syntax to avoid using multiple lines.

4. Find a command by its description

apropos "some description"
Enter fullscreen mode Exit fullscreen mode

apropos is a command that looks through the commands on your machine for one that has a description like the one you provided.

It can be extremely useful when you remember what a command does, but not its name.

5. Repeat the last command with sudo

sudo !!
Enter fullscreen mode Exit fullscreen mode

!! is a quick way to repeat the last command. I do this a ton.

Feel free to add your own useful bash tricks in the comments. 🀠

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player