Javascript required
Skip to content Skip to sidebar Skip to footer

How to Make a C Command Happen Once and Then Never Happen Again

A final is never just a terminal. An elaborate prompt can mean someone digs deeply into optimizing the tools she uses, while the information it contains can give you an idea of what kind of engineering she's done. What you lot type into the command line can tell you virtually surroundings variables, hidden configs, and Bone defaults yous never knew well-nigh. Yous tin can go far speak shorthand merely known to your terminal and you. And all of it tin help you work more efficiently and effectively.

Fustigate (a term used for both the Unix shell and the control language; I'll be using the 2nd meaning in this postal service) is usually a skill mentioned but in job descriptions for site reliability engineers and other ops jobs. Those aforementioned job posts oft ask for automation skills, which is a positive way of asking for someone who'south professionally lazy in a fashion that results in efficiency. The good news is that developers can also learn a few tricks from the land of ops to make their days easier and their work ameliorate.

Your ain personal(ized) terminal

There are lots of ways to customize your command line prompt and terminal to make you more efficient at work. We'll commencement with perchance the nigh powerful i: meet ~/.bashrc and ~/.bash_profile.

This file exists under several different names, depending on your OS and what you're trying to reach, and it tin can hold a lot of things that tin can make your life easier: shorter aliases for common commands, your custom PATH, Fustigate functions to populate your prompt with environs information, history length, command line completion, default editors, and more. With a piffling observation of your terminal habits (and a piddling cognition of Fustigate, the command linguistic communication used in many terminals), you can put all kinds of things in here that will make your life easier.

Which file y'all use depends on your OS. This post gives a rundown on the purposes and tradeoffs of the two files. If you use a Mac, though, use ~/.bash_profile. Run source ~/.bash_profile once you've saved your changes, so they're live in your terminal (or just shut your final window and open a new one).

What else should yous put in your beautifully customized new file? Let's start with aliases.

When automating things in ops work, I watch what operations I practise more than a couple of times, make notes on what I did, and put those on a list of likely script ideas. Once it's clear I'll exist doing it once more and again, I know information technology's worth the time to put a solution into code. You can do the aforementioned thing with your ain habits. What commands are yous typing all the time? What values are you frequently using? These can all be aliases.

For example, git commit and git checkout can become gc and gco (or whatever matches your mental map of abbreviations). Simply you tin can go farther than that past aliasing long commands with lots of flags and arguments. Here's how to make one:

alias $preferredAlias='$commandToAlias'

alias is the Bash command here (yous can make an alias directly on the control line too, and it will simply be available for that session until yous close that terminal). $preferredAlias is your squeamish, short proper noun for $commandToAlias, the longer, more cumbersome command you lot're typing all the time. No spaces around the = and don't forget the single directly quotes around the control yous're aliasing. You can as well chain commands together using &&. Ever sat next to someone whose command line navigation was completely opaque because they'd optimized their work into a flurry of short aliases? At present you can be that person, as well.

Here are a couple I use:

  • mkcd='mkdir $one && cd $1' (consolidating a common pair of operations; the $1 takes the first argument, in this case the new file yous want to cd into)
  • tfplan='terraform init && terraform plan' (preventing a common mistake for me; this can be used to chain any two commonly paired commands)

If you frequently piece of work across different OSes (varying flavors of Linux, Mac Bone), yous can go a little farther by creating multiple tailored dotfiles that assign slightly differing commands that achieve the same thing to the aforementioned alias. No more than remembering the minute differences that only come up every month or two—it's the aforementioned couple of characters wherever you are. If you're prone to misspelling commands (looking at you, gerp), you can alias those too.

At present permit'due south await at some other capability of dotfiles: customizing your prompt.

A constant source of truth on the control line

Your terminal prompt is one of the places you tin exist kindest to yourself, putting what you lot need in there so y'all don't take to blazon pwd all the fourth dimension or wonder exactly how long ago you typed that fateful command. At a minimum, I suggest calculation a timestamp with minutes to it; that way, if you need to backtrack through contempo work to necktie crusade to upshot, you can precisely ballast an action'due south fourth dimension with minimal work. Beyond that, I also suggest adding your working directory and current git branch. My go-to tool for setting this upwards inexpensively is EzPrompt, which lets you drag and drop your desired prompt elements and returns the Bash you demand to add to ~/.bash_profile. It'south a skilful, unproblematic showtime when y'all're first cultivating your dotfiles.

If you want to get a little more involved, you tin can try something like Powerline, which looks slick and offers more involved status information. And if you desire to curl your own, self-educate about how to work with colors in the concluding and the elements you can add to your prompt. There'due south a whole galaxy of options out at that place, and Terminals Are Sexy provides guidance to some of the constellations y'all tin explore. Hand-crafted customization is a great style to get used to Bash syntax. If you're looking to do something more circuitous with a lengthier control, Pipeline provides an interactive environs to assist you refine your output, showing you what your control produces as yous edit it.

Once you lot've gotten your file how you like it, do the extra footstep of creating a personal dotfiles repo. Proceed it sanitized (so no keys, tokens, or passwords), and yous'll take condom admission to your familiar prompt and whatever other settings you lot love at every new computer you piece of work on.

Y'all've made your prompt your friend. Adjacent, let'south look at making what comes afterward that into an ally too.

The just-enough arroyo to learning Bash

Bash tin can be a lot, even when y'all bargain with it every day (especially if some of the codebase comes from someone with an disfavor to comments). Non every dev must know Fustigate, but every dev volition benefit from knowing at least some. If nothing else, information technology helps you understand exactly what's happening when you utilise some long, pasted wget command to install a new program.

The good news is that, with a few strategies, you can navigate most of the Bash you're likely to encounter without having to become an skillful. One of my favorite tools is Explainshell. It tin can exist difficult to get a good, succinct, and completely relevant explanation for what a sample Bash control ways, particularly when you go four or 5 flags deep into information technology. Man pages are always a good identify to get-go, but Explainshell is an excellent complement. Paste in your command, and the site breaks down each piece and then that you actually know what that long string of commands and flags from that seven-yr-onetime Q&A does.

Sometimes, half the work of navigating the command line is figuring out what subcommands are available. If you're dealing with a circuitous tool (looking at you, AWS CLI) and find yourself referring to the docs more often than yous'd like, take a minute to search for an autocomplete characteristic for information technology. Sometimes autocomplete is bachelor equally a carve up simply still official parcel; other times, a third party has made their own complementary tool. That's one of the joys of the command line: you will rarely see a problem that's unique to y'all, and there'due south a good run a risk someone has been annoyed into activity and fixed it.

If you end upwards continuing to piece of work with the command line (and I promise you do), getting acquainted with pipes demystifies a lot of this work. A pipe in Linux is when you lot utilize the | symbol to chain together commands, piping output from one to another. In Unix and Linux, each tool was designed to do one matter well, and these private tools tin so exist chained together as needed to satisfy more complex needs. This is a strategy I utilize a lot, particularly when I need to create and sift through output in the final.

My most common pipe involves adding | grep -i $searchTerm afterward a command with long output I'd prefer not to choice through manually, if I'm only searching for i matter. (You can use -A and -B to add lines before and later on for context, with the number of lines you want every bit a parameter afterward each flag. Come across the grep man page to acquire more than.)

Also useful: piping the output to less, which is better if I practise desire to ringlet through the whole output, or at to the lowest degree navigate it and search within the open file, using /$searchTerm, n to see the side by side entry, and N to see the previous. You lot can also utilise cut or awk to manipulate the output, which is specially useful if you lot need to create a file of that output with a very specific format. And if you find yourself parsing JSON output much, getting acquainted with jq tin can save y'all some time.

Let's expect at some of the other conveniences the command line offers. sudo !! repeats your previous command with sudo pasted in front of it. (The !! is Unix/Linux shorthand for "the previous control" and tin be used in other situations too.) So if you lot ran something fairly involved simply forgot that it needed root-level permissions, just use sudo !!. Similarly useful: !$, which gives you the value of the beginning argument of the previous command, so ls ~/Desktop and cd !$ would evidence you the files in ~/Desktop so move y'all to that directory. And if you lot need to return to your previous directory and don't remember the whole path, just type cd - to back up 1 cd move.

Faster navigation in text

Here'due south a seemingly simple thing I learned a few years ago that regularly startles fifty-fifty long-tenured engineers. Did you know that you can click into the middle of a line in your terminal? Alt-click will motility your cursor to where you demand to go. It still requires moving your hands off the keyboard, so it'due south a fiddling clunky compared with some keyboard navigation. Merely it's a useful tool, and oddly impressive—I've stunned people past doing that in front of them and then got the joy of sharing it with them. Now you know it too.

The keyboard shortcut methods of moving your cursor can be equally impressive, though. You can get a lot of mileage out of concluding keyboard shortcuts (to say nothing about making your piece of work a little easier). Y'all can jump to the showtime or end of the line with ctrl-A or E, cut the line from your cursor to the showtime of the line with ctrl-U, or delete the previous give-and-take with ctrl-W. Here'southward Apple's long listing of keyboard shortcuts for the terminal, which by and large work on a Linux command line as well. I suggest picking a couple y'all want to adopt, writing them on a sticky annotation and putting it on your monitor, and making yourself do information technology the new way until information technology feels natural. And then move to the side by side commands yous want to commit to musculus retention, and soon enough, you too tin can be very efficient… if very confusing to watch for those who don't work this way. (But then you become to practise the kind matter of teaching them the thing y'all only learned, and the bicycle continues.)

Time travel, last mode

If you only need to refer to your last command, !! or but arrowing up and down are keen, straightforward options. Just what if you lot need to dig deeper into the past? To search your terminal history, type ctrl-R and then brainstorm typing. Desire to see the whole thing? Merely type history.

The Mac default is 500 history entries, which is not that much for a heavily used terminal. Yous can check your history length with echo $HISTFILESIZE. Desire to increase its retention? Time to edit ~/.bash_profile again. Just fix HISTSIZE and HISTFILESIZE to a very big number—10000000 is a good option. Add export HISTSIZE=10000000 and export HISTFILESIZE=10000000 to ~/.bash_profile (and don't forget to source ~/.bash_profile over again or open a new concluding window for it to take consequence). For more details on the difference between these two variables, bank check out the accustomed answer here.

At present that your history is (more than) infinite, it might exist good to know how to clean information technology upward. Information technology lives at ~/.bash_history, which ways you can delete information technology entirely with rm ~/.bash_history.

But let'due south wait at some of the other information accessible via the command line: environment variables.

Your terminal'southward subconscious values: revealed!

Environment variables can come up from many different places. Some are just function of your Bone; you tin see some common ones here. Others may exist put in place via ~/.bash_profile when you prepare them yourself in the terminal or via config or other files run on your arrangement. It'south quick and easy to blazon echo $varName in the final and see if a specific value is set up, just what if you don't know what variables have been set? That's where set, printenv, and env come in.

These 3 programs overlap some in output but aren't identical. Here'due south a quick rundown:

  • gear up is more complete and will include variables you've set in addition to the ones inherent to your environment.
  • printenv and env offering similar output of congenital-in environment variables, but env has more robust capabilities beyond printenv's elementary display purposes, including running a program in a modified environment. The accepted respond hither provides some deep history near the beingness of both commands and how and why they differ.

You'll likely get what yous need with set, though. The output is longer, which means you're more likely to need to pipe to grep or less, but it'south too more likely that y'all'll find what you're looking for.

Better living through ops skills

You lot've learned how to customize your command line and make it friendlier for troubleshooting. You've learned how to unearth surprise values hiding in your local surroundings variables. You've learned some of how to look like a wizard with aliases and keyboard shortcuts. And I bet you can start spreading the good discussion of ~/.bash_profile. In that location's more to Fustigate and terminal tricks than nosotros've laid out here, but it's yours to discover online—or just enquire your friendly local ops engineer out for coffee and ask them their favorite terminal customization. You'll probably learn more than you lot wait.

Tags: bash, bulletin, command line, devops, stackoverflow

elishaondur1975.blogspot.com

Source: https://stackoverflow.blog/2020/02/12/when-laziness-is-efficient-make-the-most-of-your-command-line/