35 ms·
My Favorite One Liners
- petepete 5y agoA couple of useful ones in here. However, instead of: git log --format='%aN' | sort -u I'd recommend using git shortlog, as it'll provide you with counts. git shortlog -sn
- fooblat 5y agoNice list! > If you want to cat bunch of files at once you can this command You can use cat itself for this (and save typing a few characters): cat *
- karatinversion 5y agoThat one gave me a giggle too - perhaps the author got told off for useless uses of cat too many times?
- enriquto 5y agoThat meme "useless use of cat" is a major pet peeve of mine... It makes no sense. Starting your pipe with cat is alright. I make a point of always starting all my pipes with cat, even in the cases where it is a bit unnatural.
- tzot 5y agoIt's one more process to run, so `cat single_file | ` can be easily substituted with `<single_file `.
- justin_oaks 5y agoI was going to point this out too. For those who may not know, you can put the I/O redirection anywhere in the command, not just at the end. So you can write < input_file.txt grep some_pattern | grep another Which has the same effect as grep some_pattern < input_file.txt | grep another but puts the input redirection at the beginning so you can easily follow the data flow from left to right. I use "redirection first" in other cases such as 1>&2 echo "Error: missing file" To make it clear up-front that I'm writing to stderr.
- tzot 5y agoOr plain `>&2` since the `1` is implied for '>'
- enriquto 5y agoYep. Writing "<file " is just as good as "cat file |". Still I'm more used to writing cat. The only (marginal) advantage of cat over explicit redirection at the beginning is maybe that you can split the lines more cleanly with cat: cat file |\ program1 |\ program2 |\ ... If you use a redirection, since the command does not start with a pipe the symmetry is broken. Redirections at the start of the line are fun. I have an alias alias null='>/dev/null 2>/dev/null' this allows to run GUI programs without cluttering the terminal with useless GTK/QT warnings: null evince file.pdf
- fooblat 5y agoPro tip, if a line ends in a | you don't need a trailing backslash. The same is true if a line ends in || or && as those all imply continuation. Edit: cat file | program1 | program2 | ...
- enriquto 5y agowow, that's great. Now what I miss is to be able to put comments after each such line.
- fooblat 5y agoI just tested it and, in bash at least, it actually works fine. echo foo | # echoing foo tr 'a-z' 'A-Z' FOO
- enriquto 5y agothis is incredible, I had already given up on this, and the solution was in front of my eyes the whole time! You have just greatly enhanced the elegance of several scripts in my lab.
- probably_wrong 5y agoThere's a natural workflow that tends to get ignored in these discussions: when you're not sure of all the details of the pipeline yet and your file is big enough to slow you down. I typically start with (say) `head file | grep '2020'`. Once it does what I want I move to the next step, and so on until it's done. At that point, and having chained 5-6 commands, replacing `head` with `cat` is faster and less likely to break due to me putting the '<' in the wrong place. The simplicity and extra peace of mind is well worth an extra process IMHO.
- aflag 5y agoWhy always start with cat? Not using cat when you don’t need to means less typing, more efficient and mor robust code. Why use it if you don’t need to?
- petepete 5y agoIt's easier to change the start of a chain that starts with cat than if you're passing a filename into your first program. Even though it's _technically_ misuse, cat can improve composability.
- alpaca128 5y agoIn many situations it's quicker to just rely on muscle memory than coming up with the most efficient way to read a few 50kB files. It's a good thing to be aware of the differences when needed, but often the execution speed is not the reason for writing a bash script.
- aflag 5y agoI don’t think efficiency matters much in this case, but more robust and concise code is better. Most commands either take a file as a unnamed argument or you can just do something like <filename. But I agree, there may be commands where passing the file name is awkward (eg. jq)
- deleted 5y ago[deleted]
- scrooched_moose 5y agoI often prefer it in scripts for easier parsing later. cat file.txt | somemonstrousoneliner immediately tells me it's reading file.txt and doing something with the contents. Burying the filename deeper in the string makes it harder to figure that out.
- aflag 5y agoIf it was grey -R . * it’d make more sense. Maybe they just missed the -R?
- tzot 5y ago`grep . *` has different output than `cat` if `*` expands to more than one filename: every line is prefixed by the filename it exists in.
- gbrown_ 5y agoThe use of grep the author proposes will have each line of output prefixed with the name of the file it came from followed by a colon. That is if the glob expands to more than one file though, if it only expands to a single file then it is equivalent to cat. Use of the -h option should be passed to grep if the difference in format is something the author wishes to guarantee.
- naniwaduni 5y agoEven when it expands to a single file, it has different output when the file contains empty lines.
- justin_oaks 5y agoI think grep ^ * would fix that and is just as short.
- m4r35n357 5y ago$ ps aux | convert label:@- process.png convert-im6.q16: attempt to perform an operation not allowed by the security policy `@-' @ error/property.c/InterpretImageProperties/3666. convert-im6.q16: no images defined `process.png' @ error/convert.c/ConvertImageCommand/3258.
- whalesalad 5y agoOn macOS you can use “pbcopy” and “pbpaste” to manipulate or read from the clipboard. For instance, format the JSON in your clipboard: pbpaste | jq .
- tyingq 5y agoxclip and xsel for X11: xclip -o | jq
- dijit 5y agoOr wl-copy / wl-paste on wayland.
- easton 5y agoIf you’re on Windows, Set-Clipboard in PowerShell does this too and is super handy.
- camel_Snake 5y agojq is lovely. python3 has a json formatter built in as well pbpaste | python3 -m json.tool
- laacz 5y agoclip.exe when on WSL (alias to pbcopy, if Mac way is the way).
- lqet 5y agoNice list, but the descriptions are written like they describe the next command, not the previous one. I would not recommend doing this to cat a bunch of files ;): > If you want to cat bunch of files at once you can this command. > rm -f !(test.txt).
- jonplackett 5y agoTotally got the same confusion. I hope whoever follows this blindly doesn’t lose too many files they wanted to cat.
- happimess 5y agoI added `margin-top: 3em` to `ul, ol, dl` and it is much more readable.
- geocrasher 5y agoI'd strongly recommend horizontal rules or something else that will more definitely demarcate each item.
- boojing 5y agoI thought these would be jokes!
- FirstLvR 5y agothere is a couple jokes in there
- criticas 5y agoThe first joke oneliner I learned, circa 1980: 1: gotta light? No match. Quickly followed by: 2: Could you beat up superman? No match. Oh, the days when csh was cool and not retro.
- KMnO4 5y agoI remember someone showed this to me on a vintage Mac: $ bill gates Did you mean “kill gates”?
- throwaway744678 5y ago$ %blow No such job We had fun times.
- lqet 5y agoMy favorite one liner for a pretty and compact graph-like git log: git log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n'' %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all Add a global alias: git config --global alias.lg "log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n'' %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all" Usage: git lg
- fidesomnes 5y agoYou are my new favorite person today.
- MauranKilom 5y agoYep, definitely among my top git aliases. Google/DDG search for "git lg2" should also reliably take you to this SO answer to copy the alias from: https://stackoverflow.com/a/9074343 https://stackoverflow.com/a/9074343
- cliff_badger 5y agoUsage: git branches Code for your ~/.gitconfig branches = branch -a --sort=-committerdate --format='\ %(HEAD) \ %(if)%(HEAD)%(then)\ %(color:"#329664")%(objectname:short)%(color:reset) \ %(color:"#222222")[%(committerdate:short)]%(color:reset) \ %(color:green)%(refname:short)%(color:reset) \ %(else)\ %(if)%(upstream)%(then)\ %(color:"#999999")%(objectname:short)%(color:reset) \ %(color:"#222222")[%(committerdate:short)]%(color:reset) \ %(refname:short) \ %(color:"#ffc662")%(upstream:track)%(color:reset) \ %(else)\ %(color:"#963232")%(objectname:short)%(color:reset) \ %(color:"#222222")[%(committerdate:short)]%(color:reset) \ %(color:red)%(refname:lstrip=1)%(color:reset)\ %(color:"#ffc662")%(upstream:track)%(color:reset) \ %(end)\ %(end)\ ' Meaning HASH Commit_date Branch_Name A white branch_name means it is local. Red means it is remote. Yellow branch_name is the current branch. It will also tell you if your checked out branch is ahead or behind the remote branch.
- 5y ago
- FriedrichN 5y agoI use this as a one liner script in my PATH to review code before I commit it. svn diff "$@" | colordiff | less -R -x4
- dwhitney 5y agosvn? Blast from the past! Why are you using it?
- throwaway823882 5y agoIn general, for a very large old project that has no major problems with SVN, it's easiest to just leave it. Lots of open source projects are still on SVN (some even on CVS...)
- imoverclocked 5y agoAny sccs users out there?
- FriedrichN 5y agoI knew this one was coming. I've been using it for a very long time and it hasn't let me down. I have considered using git but found no compelling reason to migrate.
- russh 5y agoSame here, I still use svn on my 20 year old projects and haven't felt the need change. I use git for my newer projects but occasionally run into issues that cause me to have to search for a solution.
- scrooched_moose 5y agoAs far as I'm aware, rm -f !(text.txt) isn't enabled by default, at least in bash. You have to enable extended globbing by running 'shopt -s extglob' first (or add it to your profile). Great feature though, it adds a ton of extra pattern matching. Not (!) is definitely my most used though. https://www.linuxjournal.com/content/bash-extended-globbing https://www.linuxjournal.com/content/bash-extended-globbing
- prussian 5y agoEven funner quirk with stuff like that: $ bash -c 'shopt -s extglob; rm -- !(x)' bash: -c: line 1: syntax error near unexpected token `(' bash: -c: line 1: `shopt -s extglob; rm -- !(x)' Because of the strangeness of the bash parser, the glob has to come on the preceding line: $ bash -c $'shopt -s extglob\nrm -- !(x)'
- dwhitney 5y agoWe should have a "My Favorite One Liners" thread every month like we do "Who's Hiring". Some of this is going straight into some aliases!
- throwaway823882 5y agoLess-common one-liners that I use for work: # Use jq to craft json documents jq -en --rawfile key some_id_rsa \ '{ "ssh_private_key": $key, "hosts": [ { "type": "EC2", "name": "backenddev", "id": "i-0123456789", "address": "1.2.3.4", "region": "us-west-1" } ] }' > metadata.json # Use jq to import Terraform resources from a state file jq -er '.modules[].resources | to_entries | .[] | [ "terraform", "import", .key, .value.primary.id ] | @sh' \ generated/aws/route53/terraform.tfstate \ | xargs -L1 env # Use Bash to check for a TCP connection (like 'nc -z') timeout 1 bash -c 'cat < /dev/null > /dev/tcp/127.0.0.1/3306'
- deleted 5y ago[deleted]
- nicbou 5y agoGreat post idea! "python3 -m http.server" is really useful when building simple JavaScript pages, or when you need a simple static file server for testing. "ss -p" is great, but if you just want to see what's hogging your bandwidth, iftop and nethogs are much better. My favourite one-liner is "open .", to open the current directory in Finder. The open command can also open URLs and other files. I also have an alias for "osascript -e 'display notification "'"$1"'"'", which will display the text you choose in a MacOS notification. It's useful when you need to be notified at the end of a long-running task. "printf '\a'" is also useful if you need the terminal to "ding".
- banana_giraffe 5y agoFor those that don't know "start ." is the Windows version of "open .", opening Explorer in the current folder. Speaking of Windows, "pushd \\servername\sharename" is a simple way to mount a share in Windows, if you have the login creds cached, and set the new drive letter as your active drive. Useful if you need to bounce around a bunch of shares.
- samstave 5y agoAlso, "notepad FILENAME" will open the file in notepad... etc.
- manjana 5y agoAlso, "vim FILENAME", where Vim is an alias set in $PROFILE that point to the vim executeable.
- RealStickman_ 5y agoNote that you don't have to specify an alias for it, if the vim executable is located in your $PATH.
- dgfitz 5y agoOh, I always used: explorer.exe . I didn't know open was aliased to that.
- gbrown_ 5y agoSending typescript to a FIFO seems odd. Sure you can see live input rather than following a line at a time with tail -f but you also lose persistence. To share something live I'd just use tmux or screen, granted if you want to ensure the observer has read only access there may be a couple more steps than using a FIFO.
- geocrasher 5y agoI use autohotkey to script some of my favorite things, which is another great way to get good use out of the command line on various systems where I don't necessarily need/want to set up a .bashrc. hotkey: "du-m" Use: Sort directories by usage: du -m --max-depth=1 | sort -n hotkey: "wpinfo" Use: gets basic WordPress site info: code for AHK ::wpinfo:: ( echo Home URL $(wp option get home) ; echo Site URL $(wp option get siteurl);echo "### Plugins ###"; wp plugin list;echo "### Themes ###"; wp theme list;echo "### Users ###"; wp user list; echo "### Roles ###"; wp role list; wp core verify-checksums ) hotkey: awk(1-5) use: saves me typing something I fat finger every. single. time. awk '{ print $1 }' awk '{ print $2 }' awk '{ print $3 }' etc AHK: ::awk1::awk '{{} print $1 {}}' There are others but these are the ones that come to mind. The main thing isn't the scripts but the automation. And AHK can save a ton of error-prone typing or copy/pasting in these scenarios.
- xorcist 5y agoOf all the things awk can do, I will never understand the popularity of echoing an argument. The same thing in bash would be: $ arg1 () { echo $1; } $ arg1 one two three one Splitting fields is easy with cut: $ echo one two three | cut -f 1 -d " " one Normally you just want to stuff it into a variable in which case read is much easier: $ read arg1 arg2 arg3 < <(echo one two three) $ echo arg1 one Symbolic names are normally much easier to read than numeric positions. That last example looks a bit weird with <() instead of a pipe, but that's just because the right hand side of a pipe is a separate shell so setting variables in it is a bit useless. It's nothing specific to read.
- criticas 5y agoUsing "wc -l" or "sort | uniq -c | sort" to count and classify things. Count processes and threads by user on Linux: # ps -Teo euser=,comm= | sort | uniq -c | sort -nr
- FriedrichN 5y agoAnother application of this is counting unique IPs in Apache access logs. zgrep -Po '^[0-9.]+' /var/log/apache2/test.access.log | sort | uniq -c | sort -n
- Crazyontap 5y agoI sometimes wish there was a linux command that when piped into turned anything into json readable format, so `ps | json-pipe` would output something like [{pid: 133, name, etc}, ...] or `ls | json-pipe` would turn into [{name, size, etc}]. It would handle most known commands and maybe had plugin support for the rest. Just a thought I had. Don't really know if it's possible or feasible. But it would make working with command line much more predictable and easier especially if it also supported jmespath! What do you guys think?
- daniellarusso 5y agoI saw this mentioned a few weeks ago: https://stedolan.github.io/jq https://stedolan.github.io/jq “Like sed for JSON data”
- drjasonharrison 5y agojq is a great tool for working with json data, but the author asked for a "command output in table format to json converter." The output would then be appropriate for jq.
- bronson 5y agoNushell comprehensively addresses this: https://www.nushell.sh https://www.nushell.sh (I don't have an opinion yet. Been meaning to try it for a year now but a shell is a difficult thing to switch)
- zaat 5y agoNot a linux command, but PowerShell (on linux) have a ConvertTo-Json cmdlet, it can parse dotnet object, so 'Get-ChildItem | ConvertTo-Json' will give you the output you want, but it is less successful with text so 'ls -alh | ConvertTo-Json' will give you an array and not distinct objects.
- cryptofistMonk 5y agoFor this to work on the command line, the json-pipe command would need some heuristic for parsing arbitrary input, could be tricky. Interestingly enough, the Arista CLI actually implements something like this, but it's not a real pipe or a separate command - each command implements it's own `<command> | json` handler.
- tyingq 5y agoOne I used to use when website performance seemed bad. Prints out hits in the current log with a count for each unique client ip: awk '{print $1}' < apache.log | sort -n | uniq -c | sort -rn |less Produces output like: 4482 66.249.73.135 3264 46.105.14.53 3157 130.237.218.86 2073 75.97.9.59 1013 50.16.19.13 ... And fairly easy to throw in a "grep" for specific fetched urls, slices of time, etc.
- gmuslera 5y agoI use cut instead of awk, at least for logs like apache or ones with fixed amount of spaces between fields, because it means less parsing/work, specially for summarizing long log files. Also use cat of the log as input, because is the same pattern for zcat/grep/zgrep if the input is compressed or I did some selection of records before. Some of the records you may have to search could have the port attached (i.e. output of netstat, haproxy logs or others) so for stripping them I add rev | cut -d ":" -f 2- | rev on the list of IPs to not get messed up with IPv6 records.
- someguy101010 5y ago> This commmand allows you to convert your shell output into an image as this makes it much easier than taking a screenshot of your shell if you want to share your output with someone. Why is this becoming a more common practice? There is nothing more annoying than a picture of a block of text that I can't copy, quote, or modify and send back to someone.
- makeworld 5y agoIt's better for places where you can't control text wrapping or text is limited. Twitter is the main one.
- someguy101010 5y agoThe only reason to post an image instead of a pastebin is for engagement. I understand the engagement practices we are subject to on attention marketplaces like twitter, but is it that hard to provide a supplemental pastebin link?
- PenguinCoder 5y agoSome locations and people have sites like pastebin blocked, but image hosting allowed. Also in case of say technical blog posts, a combination of certain text characters might trigger a false positive for malware on your site. You don't get that problem with images.
- darkwater 5y agoIt's not engagement. It's usability. Way better having the image in context than having an external link to a text written with fixed width font. Obviously you should ALSO provide the link to the text in the tweet so one can easily copypaste (if interested in the code/text after seeing the image preview)
- daniellarusso 5y agoPassive aggressiveness.
- loulouxiv 5y agoimport png:-|xclip -selection clipboard -t image/png -i Copy a selected rectangle of the screen into clipboard
- smusamashah 5y agoWhat is import? Does it read text from image?
- mercora 5y agoimport is part of ImageMagick and "saves any visible window on an X server and outputs it as an image file. You can capture a single window, the entire screen, or any rectangular portion of the screen."
- _def 5y agonice! I extended it to a little shell script so it gets written to a file, too.
- banana_giraffe 5y agoThe comment about sharing a terminal using mkfifo reminds me: Screen has a multi-display mode you can use with "screen -x" that lets multiple clients connect to the same session. Useful if you want to walk someone through a process.
- z5h 5y agoSpeaking of one liners... is there a way to get w3m or lynx to print a PRETTY formatted output to the console and exit? Seems all the dump commands are for plain text. Hoping someone here knows as this arcane knowledge doesn’t seem to exist elsewhere.
- tyingq 5y agoI get decent output by using headless chrome to dump to a pdf, then pdftotext (from poppler-utils) to format that as text. google-chrome --headless --disable-gpu --print-to-pdf=out.pdf https://www.cnn.com pdftotext -layout -nopgbrk out.pdf - | less
- jeswin 5y agoShameless plug for bashojs (bashojs.org), for the JavaScripters: A one liner to update all your npm deps to latest. I use this quite a lot. basho --import './package.json' pack -j pack -j 'Object.keys(x.dependencies)' -m x -e 'npm install ${x}@latest' Explanation of how this works: 1) Import package.json, call it 'pack'. 2) Put pack in the pipeline. 3) map pack to pack.dependencies. 4) flatMap (-m x) to remove nesting. Because pipeline is an array, and it contains pack.dependencies - another array. 5) Exec command with '-e'
- nickjj 5y agoHere's a few functions / aliases I have set up that I use on a pretty regular basis: # Generate a random password and copy it to the clipboard. pw () { pwgen -sync "${1:-48}" -1 | xclip } # Get the current weather. weather () { curl https://wttr.in/"${1}" } # Get the numeric value of a file / directory's permissions. alias octal="stat -c '%a %n'" All of my aliases are listed in my dotfiles at: https://github.com/nickjj/dotfiles/blob/master/.aliases https://github.com/nickjj/dotfiles/blob/master/.aliases
- gav 5y agoMy version of `pw', might be useful to those without `pwgen': function genpasswd() { openssl rand 150 | LC_CTYPE=C tr -dc '[[:alnum:]!@#$%^&]' | tr -d iIlLOo0 | cut -c 1-${1:-12}; }
- nickjj 5y agoOh yeah I forgot to mention in the alias comment that it depends on pwgen. Thanks for the reminder, I just updated it. I made a whole video on generating random password from the command line and compared a few options (including using openssl) at: https://nickjanetakis.com/blog/generate-a-random-secure-password-on-the-command-line-with-pwgen https://nickjanetakis.com/blog/generate-a-random-secure-pass... The TL;DR for not using openssl is that you're not going to get the same amount of characters every time. For example if you run yours with 48 characters instead of 12 it won't generate 48 characters every time you run it. With pwgen (something you can apt or brew install) you know what you're getting every time.
- gav 5y agoIf you change `openssl rand 150` to a bigger number, say 1000 or so, you can generate longer passwords.
- nickjj 5y agoAh, I see. Did you test your solution on macOS btw? I know macOS uses an ancient version of Bash and has different binaries that act differently vs Linux (such as sed). I don't have a Mac here but I do try to make my dotfiles compatible with it. If your solution works on macOS it would be nice to drop the pwgen dependency.
- secondcoming 5y agogit checkout -f develop
- defulmere 5y agoMy favorite is piping stuff into awk to make bar graphs. Here's system load from atopsar for the current day: atopsar -p | tail -n +7 | grep '\S' | awk '{printf("\n%s %6.2f ",$1, $5); for (i = 0; i<$5; i++) {printf("")}}'; echo sample: https://gist.github.com/defulmere/bec1aef40ca4cddb5c421ffa5f9b9e1f/edit https://gist.github.com/defulmere/bec1aef40ca4cddb5c421ffa5f...
- rhn_mk1 5y agoFixed link: https://gist.github.com/defulmere/bec1aef40ca4cddb5c421ffa5f9b9e1f https://gist.github.com/defulmere/bec1aef40ca4cddb5c421ffa5f...
- defulmere 5y agogracias
- defulmere 5y agoDangit, there should have been an ASCII block character in that second printf. Here's a version with an asterisk instead: atopsar -p | grep ":[0-9]\{2\}\s\+[0-9]" | awk '{printf("\n%s %6.2f ",$1, $5); for (i = 0; i<$5; i++) {printf("*")}}'; echo
- CalChris 5y agofvi - find vi - recursively grep for a pattern and pass the successful files into the editor. I use this to find examples in a codebase. Sure, it would be nice to set editor's pattern and have it jump to the first occurrence but that has been a bridge too far. Maybe I'll try again with VSC. (Yeah, VSC doesn't seem to have a way of setting the search pattern.) function fvi { grep -rl $1 . | xargs zsh -c 'code "$@" <$0' /dev/tty }
- m-hilgendorf 5y agoOn MacOS ./very-long-task.sh && say 'success' || say 'fail' I use it when I need to context switch and leave something running. `espeak` is an alternative for `say` on Linuxes.
- banana_giraffe 5y agoI like this idea a lot, I just dumped a tiny shell script named 'tellme' on my mac: #!/bin/bash $@ && say 'The command finished.' || say 'Danger! Something blew up!' To give me a quick way to run commands and hopefully enough words to catch my attention.
- the_pwner224 5y agoAs an audio-free alternative to `say 'success'`, you could use `tput bel`. Konsole, and many other terminals, can flash the screen or show a normal OS notification when a terminal bell is triggered in a non-active terminal window. This doesn't do the success/fail thing though.
- j1elo 5y agoNote ShellCheck's SC2015, especially if you do stuff with permanent consequences in the place of "say": "A && B || C is not if-then-else. C may run when A is true": https://github.com/koalaman/shellcheck/wiki/SC2015 https://github.com/koalaman/shellcheck/wiki/SC2015
- yesenadam 5y agoInteresting! Good to know, thanks. I never mix && and || in the same line, but didn't know exactly why that is! The problem is that "In this case, if A is true but B is false, C will run." I guess with B as "say", B will never be false, but generally it's really not the same as if-then-else.
- renox 5y agoI do something similar for long job on the remote server: an alias to send me an email + a rule in Outlook which opens a popup when an email with this subject is received (I haven't managed to get sound from VNC)
- revscat 5y agoRails dev. This runs the most recently modified test in your spec/ directory: bin/rspec $(find spec -type f -exec stat -f '%a %N' {} \; | sort -r | head -1 | awk '{print $NF}') So if you are working on a spec & save it, running this will execute that spec & only that spec. I have it hooked up to a mapping in neovim, so hitting `<leader>rt` runs the test. Needs some tweaking, and I'm aware that guard exists. This is simpler. Quick & does the job.
- kaladin_1 5y agoffmpeg -i <sth.mp4> <sth.mp3> ## converting videos to mp3
- susam 5y agoI have something similar but a little more elaborate (not a one-liner) at my ~/bin to ensure that there isn't a severe loss of quality during the conversion: https://github.com/susam/dotfiles/blob/e434b7c/bin/xmp3 https://github.com/susam/dotfiles/blob/e434b7c/bin/xmp3
- susam 5y ago> grep . * I believe this command is present to prefix each line of output with the filename. But this ignores all the blank lines. That can of course be fixed easily with: grep ^ * Here is what I normally use myself if I want to show the content of files with their filenames: tail -n +1 * This shows the name of the file once at the beginning of each file and no more. Here is an example: $ tail -n +1 * ==> bar.txt <== bar 1 bar 2 bar 3 ==> baz.txt <== baz 1 baz 2 baz 3 ==> foo.txt <== foo 1 foo 2 foo 3
- ansible 5y agoThough you get error messages if there are any directories. This will filter those out: tail -n +1 `find * -maxdepth 0 -type f` Getting long enough to make an alias...
- jolmg 5y ago> mkfifo hello; script -f hello > This command will allow you to share your terminal session in real time. Using `script` for this seems nice for when you don't want them to be able to control the same computer. Like person foo on their computer would nc -l 9000 then you could script -f >(nc foo 9000) to show them your session. One could also add some encryption to the pipe. If both controlling the same computer is not a problem or is even desired, then it's probably simplest to just share a tmux session. One runs `tmux` and the other `tmux a`.
- ansible 5y agoNeat trick with the named pipe and the script command. Note that visual editors (and anything else like ls that are aware of the terminal size) will not work well unless all terminal windows are the exact same size. And type, obviously.
- jolmg 5y agoAnd even then there might be issues. emacs' line numbers don't update correctly for one. At least for vim and htop, having a larger terminal window doesn't seem to be a problem as far as I can see.
- spurgu 5y ago> One runs `tmux` and the other `tmux a`. Here's how to do this with screen instead of tmux. Terminal 1: screen -mS hello # create screen named "hello" Terminal 2: screen -x hello # attach to shared screen
- jolmg 5y agoJust Terminal 1: screen Terminal 2: screen -x seems to be enough, too.
- spurgu 5y agoYes, but it gets confusing if you already have previous screens running (-x opens the right one if you only have one) so I provided a more "foolproof" version. I always use named screens since it's quicker and more organized than typing `screen -ls` before every time and then making a decision on whether or not to name the new one (I still think it's better to name the first one in any case in the vast majority of (my) cases).
- sandreas 5y agoMaybe some of these could be shared at http://www.bashoneliners.com http://www.bashoneliners.com :-)
- chromejs10 5y agoWas really hoping for a list of jokes when I clicked that link. A bit disappointed.
- geocrasher 5y agoA politician, a cleric, and a homeless guy walk into a bar, and the bartender says "What is this, some kind of joke?" You're welcome.
- tornato7 5y agoI thought this was going to be about jokes :(
- zfxfr 5y ago-> grep * : "If you want to cat bunch of files at once you can (use) this command." Yes but I don't understand the advantage of that instead of simply using : cat *.* or if you want to display the filenames : tail * works fine too. Maybe someone can explain.
- rahimiali 5y agoSome of these are useful. Some of these have better alternatives: > grep . * you can "cat *" > ps aux | convert label:@- process.png copy-pastable text is a better way to exchange text. > mkfifo hello; script -f hello you forget to mention that the other side needs to cat this file. but also, tmux might be better for this.
- matvore 5y ago> > grep . * > you can "cat *" The advantage of `grep . *` is that it omits empty lines and includes the source file on each matching line by default.
- dvh 5y agoI pulled history and my favorite seems to be: pmount sdb1
- TheAceOfHearts 5y agoOn macOS you can read and write to the clipboard with pbcopy and pbpaste: $ ls | pbcopy $ pbpaste > out.txt You can also put this in a function in order to get the path of the frontmost Finder window: osascript 2>/dev/null -e ' tell application "Finder" return POSIX path of (target of window 1 as alias) end tell' Get the current Finder selection: osascript 2>/dev/null -e ' set output to "" tell application "Finder" to set the_selection to selection set item_count to count the_selection repeat with item_index from 1 to count the_selection if item_index is less than item_count then set the_delimiter to "\n" if item_index is item_count then set the_delimiter to "" set output to output & ((item item_index of the_selection as alias)\'s POSIX path) & the_delimiter end repeat'
- jgwil2 5y agoAlso, for quick formatting a blob of JSON you've copied: pbpaste | json_pp | pbcopy
- michaelmcmillan 5y agoOn MacOS you can also drag-and-drop a file from Finder onto your terminal and it will type out the full path for you.
- TheAceOfHearts 5y agoYou can also select one or more files and use the hotkey Command + Option + C to "Copy N items as Pathname", which copies the full pathname of each item to your clipboard.
- Tsiklon 5y agoWonderful! I didn't know that it was possible to copy the file path of an arbitrary selection, thanks!
- laacz 5y agoOn Windows I use alias: 'alias pbcopy="clip.exe"' for consistency as I use Mac and Windows daily. ps auxw | pbcopy # After alias works on WSL too.
- kown7 5y agoOne can always dig their own IP address dig TXT -4 +short o-o.myaddr.l.google.com @ns1.google.com
- imoverclocked 5y agoThat's neat! I can also find my upstream DNS servers recursive resolver IP by leaving the @ns.google.com off. Looks like my upstream resolvers are using IPv6 :) Also, I can find the resolver IP for popular public resolvers this way too. This is probably the coolest thing I will learn about today.
- kmstout 5y agoAmong my favorites is this little zinger (awk): !seen[$0]++ which gives the union of the lines of all the input files, with none of that 'sort | uniq' business. It's not a one-liner, but here's intersection: ! buf[$0]++ { acc[$0]++ } ENDFILE { delete buf; files++ } END { for (k in acc) if (acc[k] == files) print k } and here's set difference: ! filenum { acc[$0] = 1 } filenum { delete acc[$0] } ENDFILE { filenum++ } END { for (k in acc) print k } I keep these in my ~/bin with evocative names (e.g., 'union' and 'set-diff'). Once I did that, lots of other things became one liners.