16 ms·
Mastering Bash and Terminal
- alphast0rm 10y agoFor changing directories, you can also use something like z (https://github.com/rupa/z https://github.com/rupa/z) to jump around: Tracks your most used directories, based on 'frecency'. After a short learning phase, z will take you to the most 'frecent' directory that matches ALL of the regexes given on the command line, in order. For example, z foo bar would match /foo/bar but not /bar/foo.
- kbd 10y agoAlso fasd, which has a z-compatible interface and does a little more: https://github.com/clvv/fasd https://github.com/clvv/fasd
- eriknstr 10y agoI've been thinking about wanting something akin to this, I just had no idea it existed, so what I've been doing instead is I've defined short aliases for some of my most frequent directories. I use such an alias which I have named "no" which does "cd /var/www/no.nordstroem.www/pub/htdocs" on my Raspberry Pi where I host my website. For most directories on my laptop and desktop rather than using an alias even though I might have defined one is I first try a reverse search for it in the shell history, for example ^Rklon to get to ~/src/github.com/eriknstr/klondike/. However reverse search will fail whenever I haven't worked with a directory for a while or if I've been doing a lot of things in one directory since I have chosen to leave the length of the shell history at its default. I would have liked to maybe start using the command you linked but unfortunately it is using the WTFPL so I will have to pass on it. But from the short description you quoted maybe I'll implement a similar tool myself some day. Then again maybe I will just keep doing things the way I'm doing them now because usually most of what I do is I go to a specific directory and do a lot of work there without moving much, typically said directory will be the root of the repository I have for what I'm working on. If I'm working in several project root directories at the same time I'll usually have multiple terminals open.
- Normal_gaussian 10y agoRather than temporarily suspend vim to use the terminal you can get vim to suspend and resume itself with the exclamation mark command. This has the benefit of not wreaking havoc on your vim session and allowing you to read data into vim by prefixing with r. For example :!ls will execute ls and show you the result (press enter to return) :r!ls will read the result of ls in for you More usefully :r!sed -n5,10p that/other/file will read lines 5-10 from that other file. However you will most often want to :!make :!up build :!git status :!git commit -am "Fixed #23"
- TAForObvReasons 10y agoYou can also give a range before the ! and it remove the lines in the specified range and pass it to the command. For example, when reading xml I use xmllint to clean it up: :%!xmllint --format -
- makecheck 10y agoYou can also install a plug-in like ConqueTerm to devote an entire in-vim buffer to something like a shell session.
- skierscott 10y agoOr you can use tmux (which can be have vim bindings) to run vim in one pane.
- blockloop 10y agoTmux is great. I have another writing in progress on my tmux workflow.
- Sir_Cmpwn 10y agoFYI :make also works
- justinmk 10y agoYou can also use the ":terminal" command (":te" for short) in Neovim.
- teddyh 10y ago> 8. alt-w - delete the word behind of the cursor He means “ctrl-w”. But since that only works in bash, not in Emacs or other tools with Emacs key bindings, it makes more sense to use (in his terminology) “alt-backspace”. This does the same thing, and works both in the shell and in Emacs-like environments.
- blockloop 10y agoAh yes. Thank you for the correction.
- u801e 10y agoThe default key bindings in bash are listed in the readline section of the bash man page (they mostly match the emacs key bindings).
- syrrim 10y agoAnother advantage to using alt-backspace over ctrl-w is that the former has the same semantics as alt-b. ctrl-w considers a word to be anything surrounded by spaces, whereas alt-b and alt-backspace consider a word to be any consecutive string of word characters.
- Lio 10y agoIt may be worth noting that C-w also works in Vim insert mode. So, for me, it works in both shell and editor.
- oblio 10y agoThe article is nice but a small part of it rubs me the wrong way: > I know there are some cool newcomers out there like zsh and fish, but after trying others out I always found that some of my utilities were missing or ill-replaced. First of all bash was first released in 1989 and zsh arrived just 1 year later so zsh is in no way a newcomer. Secondly zsh is almost strictly a bash superset so I don't know what he was missing (or what he found "ill-replaced").
- blockloop 10y agoI wasn't so much commenting on the release date when I said "newcomers." Mostly commenting on my personal experience. I've been using bash for a long time and only recently have I seen zsh get so popular. It's entirely possible that only the people I know have only recently taken an interest in it. I would have to run zsh again to remember the pieces that I didn't like. I might have been able to configure my way around it, but I do remember things not working as I expected them to.
- oblio 10y agozsh was quite popular when I first went spelunking in *NIX-land (2005). oh-my-zsh, which was a decent boost to zsh popularity, seems to have been around since 2009 (http://ohmyz.sh/ http://ohmyz.sh/). zsh has always been held back by the "default browser"-syndrome: Linux and Mac OS both come with "good enough" default shells, so few people actually want to go through the effort of switching. Especially since there is a bit of a learning curve to becoming more productive with zsh than you already are with bash.
- blockloop 10y agoYou're probably right about oh-my-zsh. I really only hear people refer to zsh as "oh my zsh" which makes me smile.
- dotancohen 10y agoThe problem with installing zch on my desktop is that I won't have it on the servers I SSH into. I need to know the proper spells and incantations that will work on a wide variety of distros and versions, many of which I don't personally maintain. Therefore, bash.
- lisivka 10y agoI recommend to install mc (Midnigth Commander) and bash-completion (if bash is your shell of choice) as first terminal tools. mc allows to explore system efficiently while not standing in my way, because I can always press ctrl-O and get my shell back. bash-completion saves time on typing of commands. Other tools I install often are htop (better ps) and strace.
- mdekkers 10y agoall of these are my go-to tools. I also edit inputrc to make pgup and pgdn history search - something I picked up from SuSE version 15 years ago, and stuck.
- amirbehzad 10y agowould you mind to share and elaborate a bit. tq.
- teddyh 10y agoRegarding macOS and bash, it is slightly remiss of the article to not at least mention that the version of bash in macOS is 1. Ancient. 2. Will most likely never be updated by Apple (Most GNU- and Linux-based systems, and also Windows, on the other hand, continue to use the latest versions.)
- blockloop 10y agoI don't use the version that ships with MacOS. You can install the latest version with `brew install bash`. I'm currently using 4.4.5. Nevertheless, I updated the post to add bash 4 to the assumptions.
- KKKKkkkk1 10y agoWhy are you saying that Apple will not update bash? Wouldn't that be in the best interest of its users?
- oblio 10y agoGPLv3.
- teddyh 10y agoIt would indeed be in the best interest of its users, but Apple has apparently decided that it would not be in its own best interest: http://meta.ath0.com/2012/02/05/apples-great-gpl-purge/ http://meta.ath0.com/2012/02/05/apples-great-gpl-purge/ […] Anyway, the message is pretty obvious: Apple won’t ship anything that’s licensed under GPL v3 on OS X. Now, why is that? There are two big changes in GPL v3. The first is that it explicitly prohibits patent lawsuits against people for actually using the GPL-licensed software you ship. The second is that it carefully prevents TiVoization, locking down hardware so that people can’t actually run the software they want. So, which of those things are they planning for OS X, eh? I’m also intrigued to see how far they are prepared to go with this. They already annoyed and inconvenienced a lot of people with the Samba and GCC removal. Having wooed so many developers to the Mac in the last decade, are they really prepared to throw away all that goodwill by shipping obsolete tools and making it a pain in the ass to upgrade them?
- wodenokoto 10y agoPersonally I found "Learn Enough Command Line to Be Dangerous" to be really helpful to get started with actually using the command line at all. https://www.learnenough.com/command-line-tutorial https://www.learnenough.com/command-line-tutorial
- whack 10y agoPersonally, I found the following to be extremely easy and powerful. A no-brainer that should be a bash default really. if [ -t 1 ] then # search for commands that start off with the same characters already typed bind '"\e[A":history-search-backward' bind '"\e[B":history-search-forward' fi One of my friends also recommended version-controlling your config files and storing them on gitlab, which I'm only sad I didn't do sooner. It's been such a help in keeping my aliases and configs in sync, as I make changes across numerous different machines.
- blockloop 10y agoYou can also put those in your ~/.inputrc
- 3131s 10y agoYes! This is the first thing I do in a new Linux OS. Also, the author does not mention hitting tab for autocomplete (or displaying the remaining options that match what has been typed so far).
- lottin 10y agoThat these, probably the most useful Readline functions by far, are not bound to any keys by default is crazy. To me it makes more sense to bind them to M-p and M-n though.
- joatmon-snoo 10y agoHaving a .dotfiles/ repo makes life so much easier. Seriously.
- mjlangiii 10y agoI'm sorry, can you explain how to use this?
- whack 10y agoJust stick that snippet in your .bashrc file
- 10y ago
- santaclaus 10y agoI'm curious about the popularity of Bash vis a vis, say, Csh. Is Bash more popular due to superior features, or is simply because it is the default on quite a few *nix distros (and macOS)?
- pmoriarty 10y agoI used to use zsh way back in the day because it was clearly superior to bash, then decades ago switched to bash because it was everywhere by default and my job involved using lots of computers that only had bash on them, then about 4 or 5 years ago I switched back to zsh because I realized that it really didn't matter that I used zsh on my own machine and bash on others, and zsh was still better than bash. These days bash seems to have a lot closer feature parity to zsh, and I'd be curious to read an up-to-date comparison of both shells to determine if either is clearly better than the other.
- RJIb8RBYxzAMX9u 10y agoshell is a bit like JavaScript: both languages have a lot of warts, but if you interact with UNIX-like systems / browsers at intermediate or above levels, you must be comfortable with them. Unlike browsers, you have a few choices for shells, and IMHO [t]csh lost because a) Linux "won" over *BSDs, b) POSIX basically standardized on sh, c) [t]csh is a worse scripting language. Back in uni I used to use tcsh interactively, script in [ba]sh, and program in a "real language" like C, Java, etc., but I wasn't doing anything very complicated with any of them. Once I started working and begin using these tools seriously, I simply couldn't learn and retain all of them. Something had to go, and tcsh was it.
- gogolb 10y agoOn macOS, instead of ip addr show en0 | grep -inet\ | awk '{ print $3 }' | awk -F/ '{print $1}' | pbcopy you can use: ipconfig getifaddr en0 If you wanna stick with ip addr, a more compact command is: ip addr show en0 | awk '/inet/{split($2,a,"/"); print a[1]}'
- krzyk 10y agoIt would be good to mention that this article is MacOS centric.
- blockloop 10y agoI use most of it on both GNU Linux and Mac. I have installed coreutils (GNU bins) and bash v4.4.5 via homebrew on Mac. It's probably safer to say these are more specific to Linux.
- xolb 10y agoOne that I learned from Mr. Robot: put a space before the command to avoid being registered in the history.
- jlgaddis 10y agoThat only works if $HISTCONTROL includes "ignorespace" or "ignoreboth".
- gigatexal 10y agoInstead of ctrl-z and bg why not just do # <cmd> & to push it to the background.
- number-sequence 10y agoI don't know if you can bring a process back to the foreground using the
- gigatexal 10y agoit does work. I just tried it. #> watch -n 1 dmesg & #> fg -- brought it back
- SFJulie 10y agoSeriously you can get on fi(r)st page of HN with 5% of man bash?
- llasram 10y agoWorth it just for finding out about `stty -ixon`. I never would have guessed from the `stty` man page description that this option would give me back C-s and C-q to bind to something actually useful.
- uuoc 10y agoIt is described perfectly, but it does presume the reader knows the meaning of "XON/XOFF flow control". Whether the reader knows that meaning immediately is a rather good proxy for just how long they have been working and/or playing with computers. Long ago, in a world of RS-232 connected display terminals and/or analog telephone modems, one became very familiar with "XON/XOFF flow control".
- h2hn 10y agoI actually resolved most of that common issues with just bash: :) Substring history search, so you can use just a substring to look for a argument,command. Binded to ctr+r/s by default. ;) https://github.com/liloman/asyncBash#use https://github.com/liloman/asyncBash#use Changing directories: Last n directories, transparent popd/pushd. https://github.com/liloman/dirStack https://github.com/liloman/dirStack Movements: vim-surround for your cli, so you can do ysiw" o whatever... ;) https://github.com/liloman/bash-surround https://github.com/liloman/bash-surround Control-n right: So just type the start and control+n to search for the arguments/commands starting with whatever. And the classical up/down to look up for a complete history line: https://github.com/liloman/dotfiles/blob/master/bash/.inputrc#L234 https://github.com/liloman/dotfiles/blob/master/bash/.inputr... https://github.com/liloman/dotfiles/blob/master/bash/.inputrc#L170 https://github.com/liloman/dotfiles/blob/master/bash/.inputr... There're a ton of hidden functionality and customization behind the classical bash instalation. :)
- tambourine_man 10y agoThat is amazing, thanks for sharing. I'm gonna steal some ideas from asyncBash
- h2hn 10y agoI'm glad you liked it. :) I don't understand why the default bash/readline doesn't get something related for substring search or way better autocompletions, it's really not that hard definitely (actually quite easy) and even when that's the reason for a lot of people to choose zsh over bash.
- hiq 10y agoAbout bindings, it would have been better to redirect to: LESS=+/"DEFAULT KEY BINDINGS" man readline assuming it exists on mac. About suspend, what's the benefit of suspending vim using C-z? Shouldn't you use a terminal multiplexer instead, or even terminal tabs if you don't want to learn how to use tmux or screen (which I find weird if you already spent time to learn how to use vim but alright)? I only ever suspend a program when I want it to stop, for instance because it slows other programs and I realize I would rather resume it when I'm not in front of my computer. Even in that case, I often just renice the program instead. Stopping a program just because you want to run some bash commands looks like an anti-pattern to me, but maybe there are better motives I'm not aware of.
- blockloop 10y agoI use tmux. The benefit of using suspend is not having to move around multiple windows/tabs. I try to keep those to a minimum (usually one or two). With suspend I can stick with the same tmux window for editing and cli within the same context. It's a personal preference over managing multiple windows.
- hiq 10y agoTo stay on the same window I would personally use a split-window depending on the size of the display. I didn't think about the context though, good point!
- pmoriarty 10y agobash (and shells in general) are so hacky (in a bad way) that I wouldn't want to waste my time mastering them. Whenever a shell script grows beyond 10 or 20 lines, I try to rewrite it in a "real" programming language. Fancy shell tricks are a code smell to me, and clarity and simplicity are of far greater importance. For me, as far as shells go it's usually enough to know the basics and be able to look stuff up when debugging other people's shell scripts.
- marvy 10y agoThat might be a good reason to not write programs in shell, but it sounds like mastering the interactive features might still be worth the time.
- Karrot_Kream 10y agoWhile I understand this sentiment, I think it's a point that needs a bit more thought; it's not a black and white issue. On my personal machines, I often find places where I want to either clean up my desktop experience or automate some workflow, where I break some shell out. Most of the time, the overhead to drop into an actual programming language is quite heavy, and even though I try to comment my scripts and write them in a maintainable fashion, I only end up editing them maybe a few times a year. I feel like discouraging shell scripts is part of what's driving us to seek increasingly heavyweight solutions like systemd in our architecture. Sometimes a lightweight environment where we trust the programmer is needed.
- pmoriarty 10y agoI'm about as anti-systemd as you can get, but I also cringe whenever I look at some of those massive, convoluted shell scripts in SysVinit. There is a middle path, with runit[1], which mostly uses short, simple shell scripts for its process initialization and supervision. Brevity and simplicity are really the keys when it comes to shell scripts. I really don't have a problem with them if they're short and don't try to be too clever. Whenever I've let my shell scripts get long or complicated, I've always regretted it, and always wound up rewriting them in a "real" programming language anyway, and then realizing that I would have been better off rewriting them much earlier, as soon as they'd outgrown the short, simple stage. There's no shortage of relatively light-weight "real" programming languages like Perl, Python, Ruby, Lua, and Go -- for even moderately sophisticated tasks, all of them would be better choices than shell scripting. [1] - http://smarden.org/runit/ http://smarden.org/runit/
- wyclif 10y agoI also assume you're using bash. I know there are some cool newcomers out there like zsh and fish While there is much useful in this post, I always find comments like this one odd. bash was released back in 1989, zsh was released one year later, in 1990. One year difference in age almost thirty years ago means that you can't really call zsh a newcomer. Maybe he's talking about adoption, though.
- dozzie 10y agoI've had a similar thing recently. Somebody asked me about learning "old technologies", like Perl and CFEngine. Perl 5.x was published in 1991, four years after initial version, Python was published in the same year, and Ruby merely 4 years later. CFEngine 3.x, a complete rewrite that carries over very little and only very high level ideas from earlier versions, was released in 2008, three years after Puppet, and only one year before Chef. Some people just lack the perspective.
- blockloop 10y agoI was definitely talking about adoption ;-). See my comment https://news.ycombinator.com/item?id=13400707 https://news.ycombinator.com/item?id=13400707
- barrkel 10y agobash is an extended clone of Bourne shell, though, and sh dates to 1977.
- why-el 10y agoIn the spirit of sharing: one of my favorite lines in my bashrc is the alias of `rm` to `rm -i`. This prompts for a confirmation. You might not need it but I deleted some important, not-yet-checked-in-git files in the past by accident. If you want to delete everything and don't want to keep typing yes just do `yes | rm bla`.
- RJIb8RBYxzAMX9u 10y agoNo need to do that: just pass -f. The last flag "wins": $ rm -fi blah remove blah? $ rm -if blah $ # confirmation suppressed
- Symbiote 10y agoWith GNU rm, you can put the -f at the end, which I do for safety. rm -i x y z -f
- danielrm26 10y agoRather than trying to remember all those commands for moving around in your command, I recommend turning on vim mode for the command line, and remapping ESC to "jk". bindkey -v bindkey -M viins 'jk' vi-cmd-mode Then you can edit your command line the same way you would edit a line in vim.
- kpil 10y agoBut come on, the default mode is "emacs" for a reason.
- lxe 10y agoThe one tool that saved me quite possibly a few months of typing paths over my lifetime is autojump: https://github.com/wting/autojump https://github.com/wting/autojump. I can't imaging a terminal workflow without it.
- stinos 10y agoThis should be shouted out regulary to anyone using any type of command line until everybody uses it. I cringe everytime I see someone spelling out cd /mega/long/path/to/a/place/i/visit/multiple/times/every/single/day. Ok some of them already know about tab completion, but it just hurts to see that knowing all that's really needed is j d or z d or so.
- ndesaulniers 10y agoWhen going past something with ctrl+r, use backspace rather than ctrl+s. less has movements similar to vim. In less, hit v to open the file in your editor.
- philonoist 10y agoKindly help me out on how to learn this tool in Windows10 without using VM?
- RJIb8RBYxzAMX9u 10y agoRegarding history, another simple trick is to increase $HISTSIZE and $HISTFILESIZE, for the defaults are woefully tiny for 2017. I set mine to a million. You could have 100 terminals open and they would still consume less RAM than <insert "native" Electron app(s) of your choice>.
- mr_donk 10y ago> Now that we know we don't need the up and down arrow keys, what about the left and right? Unfortunately, these keys are still needed for single character movements Don't ctrl-f and ctrl-b work?
- TheAceOfHearts 10y agoI've tried bash, zsh, and fish. After trying all three, I'm staying with fish. bash and zsh don't have sensible defaults, and configuring them is tedious. fish works great out of the box, and it's really fast. When I picked up zsh I used oh-my-zsh and later prezto, but it was slow and figuring out what everything all the framework did was complicated. With fish I have a setup.fish script that defines all my universal exports, for when I setup a new computer. This is for private tokens, like HOMEBREW_GITHUB_API_TOKEN. For aliases and utilities, I wrote a fisherman [0] plugin. It has a functions folder and a fishfile for the few other plugins I use. [0] https://github.com/fisherman/fisherman https://github.com/fisherman/fisherman
- eknkc 10y agoI use fish too but I'm thinking about switching back to zsh. Mostly due to incompatible software here and there (like nvm) and lack of completions for a lot of cli tools.
- TheAceOfHearts 10y agoasdf [0] is a great alternative to nvm. The best part is that it supports multiple languages and it's fast. I use the plugins for elixir, erlang, nodejs, and ruby. Many CLI tools are missing completions, but I think it's slowly getting better over time. The pros outweigh the cons for me. [0] https://github.com/asdf-vm/asdf https://github.com/asdf-vm/asdf [1] https://github.com/fisherman/fisherman https://github.com/fisherman/fisherman
- FreeFull 10y agoI leave my $SHELL set to bash, but have tmux launch fish. That way, any software that tries to start a shell of its own gets the POSIX sh-compatible shell it expects.
- ufo 10y agoThe Bass wrapper script can help with some of the incompatibilities: https://github.com/edc/bass https://github.com/edc/bass
- 10y ago
- nurb 10y agoAnother trick is to use "!!" which is the last command launched, especially useful if you forgot a "sudo" in front of your command, just write sudo !! In the same way, "!*" is all the arguments of your previous command, and "!$" only the last one.
- jcutrell 10y agoCame here to mention the sudo-bang-bang trick, which really has the best name of all the commands I know.
- alkonaut 10y ago> "tool that every developer uses regardless of language, platform, or framework it's the terminal" I'm not sure I agree with that. If you work in a decent IDE and your vcs is not git then you can do pretty well without a terminal. Especially on Windows.
- deleted 10y ago[deleted]
- greenspot 10y agotl:dr ctrl-r search in history, ctrl-r again to skip- ctrl-p previous command (instead of arrow up) ctri-n
- deleted 10y ago[deleted]
- blunte 10y agoThose Emacs commands you mention for moving around on the line also work in a lot of other text fields, in a lot of other programs. Notably they don't work in MS Office, but they work in web browsers and practically every other app I have on my Mac.
- ubernostrum 10y agoThey work in so many things because they're the default keybindings for the movement commands in readline. So anything using readline gets them for free.
- cel1ne 10y agoTipp for OSX-Terminal: Option + Cursor-Left/Cursor-Right to jump words
- johnchristopher 10y agoI love `set -o vi`. It gives you vim motion in the terminal.
- greenspot 10y agoGreat post & thread, a tl;dr: Ctrl-r search history - then Ctrl-r again to show next match - then Tab to show all options Ctrl-p previous command or arrow up Ctrl-n next command or arrow down export HISTCONTROL=ignoreboth:erasedups Add to .bashrc to avoid duplicate entries Ctrl-a to beginning of line Ctrl-e to end of line Alt-b one word back Alt-f one word forward Ctrl-k delete to end of line Ctrl-u delete to beginning of line Alt-d delete to end of word Ctrl-w delete to beginning of word Alt-Backspc same cd - change to last dir pushd <dir> mark current dir and go to <dir> popd go to marked dir z fuzzy cd, install from https://github.com/rupa/z j fuzzy cd and more, install via autojump Ctrl-z to background & suspend bg recent background app continue running fg bring recent background app to front disown -h remove recent background app from current tty fg %n bring nth app to front, e.g.: fg %2 for second less better than cat, doesn't flood screen, same keys find find files, e.g. find / -name <filename> ag install via the_silver_searcher, faster grep tree shows dir like a GUI app, install !! last command, e.g. sudo !! fish bash alternative with more sensible defaults man bash read more about bash
- bigbugbag 10y agoHere are some notes I took about ZSH that may be helpful to someone * zsh bang previous commands: !! Previous command !-1 Previous command !-2 Second previous command Getting individual arguments: !$ Last arg !* All args !$:h Last argument, strip one level !!:1 First arg Modifying commandlines !ls:$:h Head !ls:$:t Tail !ls:$:r Rm Suffix !ls:$:s/user/dude/ Substitute user by dude * Filename Modifiers :h head (dirname) :t tail (basename) :e extension :r remove extension :l lowercase conversion :u uppercase conversion :p print command but do not execute :q quote substituted words * zsh globbing **/* Picks out all files and directories, recursively. ***/* Ditto, following symlinks * Any string, including the null string. ? Any character. [...] Any of the enclosed characters. Ranges of characters can be specified by separating two characters by a -. [^...] Inverse [!...] Inverse <x-y> Any number in the range x to y, inclusive. Either can be omitted. ^x Anything except the pattern x. x|y Either x or y. x# Zero or more occurrences of the pattern x. x## One or more occurrences of the pattern x. globbing qualifiers * file type (.) Regular files (/) Directories (@) Symlinks (=) Sockets (p) Named pipes (%) Device (%b) Block devices (%c) Character devices * permissions (r) Readable by owner (w) Writable by owner (x) Executables by owner (R) Readable by world (W) Writable by world (X) Executable by world (A) Readable by group (I) Writable by group (E) Executable bu group alternatively a chmod style syntax is supported: ls **/*(.:g-w:) * Ownership (U) Your own user (G) Your own group (u:userid:) User with userid (g:userid:) group with groupid example: list files belonging to user www-data with ls -l /(u:www-data:) Modification and access time (m) Modification time (a) Access time (-) Before (+) After (M) Months (w) Weeks (h) Hours (m) Minutes (s) Seconds example: list files accessed last month with ls /(.aM-1) file size (L) File size (defaults to bytes) (k) use kilobytes (m) use megabytes (p) use 512-byte blocks example: list all files larger than 10 megabytes with ls /(.Lm+10) dos2unix /~.(gif|png|jpg)(.) # ~ excludes dos2unix (#i)/~.(gif|png|jpg)(.) # case-insensitive ls =bob # Lists file anywhere in $PATH ls /some_file # Lists file under current directory zargs -- /(.) -- ls -l # Ditto * zsh Iteration for i (/home/**/q*) rm $i for i in /**/b*(u:miklophone:); do rm $i ; done for f in http://zsh.sunsite.dk/Guide/zshguide{,{01..08}}.html; do... zargs -- /**/b*(u:miklophone:) -- rm * Renaming files with Zsh Numerical prefix: $ i=1; for j in *; do mv $j $i.$j; ((i++)); done $ i=1; for f in *; do mv $f $(echo $i| awk '{ printf("%03d", $0)}').$f; ((i++)); done $ integer i=0; for f in *; do mv $f $[i+=1].$f; done Rename all files from name.mp3 to Name.mp3: $ zmv `([a-z])(*).mp3` `${(C)1}$2.mp3` Capitalize file $ zmv '([a-z])(*).pdf' '${(C)1}$2.pdf' Replaces spaces with underlines $ zmv '* *' '$f:gs/ /_' FOO to foo $ for i in *(.); mv $i ${i:l} Rename pic1.jpg to pic0001.jpg ... $ zmv 'pic(*).jpg' 'pic${(1:4::0:)1}.jpg' $ zmv '(**/)pic(*).jpg' '$1/pic1:4::0:)2}.jpg' # recursive Remove spaces from filenames $ for a in ./**/*\ *(Dod); do mv $a ${a:h}/${a:t:gs/ /_}; done Substitute r for l s/l/r[/] Unless preceded immediately by a g, with no colon between, the substitution is done only for the first string that matches l. For arrays and filename expansion, this applies to each word of the expanded text. The left-hand side of substitutions are not regular expressions, but character strings. Any character can be used as the delimiter in place of '/'. A backslash quotes the delimiter character. The character '&', in the right-hand-side r, is replaced by the text from the left-hand-side l. The '&' can be quoted with a backslash. * zsh if # see also -z below if [[ $foo = '' ]]; then print The parameter foo is empty fi # quote the term to avoid pattern matching (not regexp, btw) if [[ biriyana = b* ]]; then print Word begins with a b fi # Numbers if [[ $number -gt 3 ]]; then if [[ $number -lt 3 ]]; then if (( $number > 3 )); then if (( 3 )); then # Files if [[ file1 -nt file2 ]]; then # newer than if [[ file1 -ot file2 ]]; then # older than if [[ file1 -ef file2 ]]; then # same file # Variables if [[ -z "$var is blah; test fails" ]]; then # zero length? if [[ -n "$var is blah; test passes" ]]; then # non-zero length?
- coldtea 10y ago>If there is one tool that every developer uses regardless of language, platform, or framework it's the terminal. Sounds like the author never heard of Windows development.
- ivanhoe 10y agoIt's missing my favourite: CTRL + _ for Undo. Also there's a big difference between Alt + Backspc and Ctrl + w. The first will delete a word consisting of only alphanumerics, while Ctrl + w also deletes the word, but word can be made of any characters other than space.
- Scea91 10y agoOne thing I am struggling with is that when I use several terminal windows then the history is not recorded immediately and history from one window is not available in other windows. Some time ago I was looking up how to solve this but didn't find a solution that would work for me.
- MarcScott 10y agoThis bugs me as well. I use a tiling windows manager, so terminal windows are completely disposable to me, and I'll open and close them at will, often having double digit terminals open across 10 desktops. My bash history does not reflect my use of multiple terminals.
- thiagof 10y agoA very usefull command is Alt-m. This command repeat the last digited string in the current line. It only works in ZSH.
- annetee 10y agoAlso: Alt-l converts next word to lowercase Alt-u converts next work to uppercase
- rofrol 10y agoI would suggest https://github.com/BurntSushi/ripgrep https://github.com/BurntSushi/ripgrep over ag
- Graziano_M 10y ago> Now that we know we don't need the up and down arrow keys, what about the left and right? Unfortunately, these keys are still needed for single character movements... What? No. Use Ctrl-f and Ctrl-b. I use this probably more than any other readline shortcut. Ctrl-h for backspace, Ctrl-d for delete. Half my keyboards don't even have arrow keys and I don't miss them.
- rerx 10y agoI never knew of `cd -` before -- very useful!