Commands tagged bash (821)

  • use it to add a random boolean switch to your script Show Sample Output


    4
    echo $[RANDOM % 2]
    anapsix · 2013-05-25 19:15:57 9
  • This type of join is clearly documented in the bash manual. Only the first character of IFS is used for the delimiter. Show Sample Output


    4
    (IFS=,; echo "${array[*]}")
    aspiers · 2013-09-25 10:36:38 10

  • 4
    ps -p $$
    maverick · 2013-10-17 10:45:22 9

  • 4
    curl ipinfo.io/<ipaddress>
    coderholic · 2013-10-31 05:18:07 6
  • Simply sourcing .bashrc does not function correctly when you edit it and change an alias for a function or the other way round with the *same name*. I therefor use this function. Prior to re-sourcing .bashrc it unsets all aliases and functions.


    4
    bashrc-reload() { builtin unalias -a; builtin unset -f $(builtin declare -F | sed 's/^.*declare[[:blank:]]\+-f[[:blank:]]\+//'); . ~/.bashrc; }
    Xk2c · 2014-03-02 14:24:18 9
  • Shows "Bang!" in a chance of 1 out of 6, like in the original game with the gun (spin every round). Otherwise, echoes "Click...". If feeling brave you can also do: [ $[ $RANDOM % 6 ] == 0 ] && echo 'Bang!' && a really killer command || echo 'Click...' Show Sample Output


    4
    [ $[ $RANDOM % 6 ] == 0 ] && echo 'Bang!' || echo 'Click...'
    paulera · 2016-03-23 11:09:56 29
  • Unlike other methods that use pipes and exec software like tr or sed or subshells, this is an extremely fast way to print a line and will always be able to detect the terminal width or else defaults to 80. It uses bash builtins for printf and echo and works with printf that supports the non-POSIX `-v` option to store result to var instead of printing to stdout. Here it is in a function that lets you change the line character to use and the length with args, it also supports color escape sequences with the echo -e option. function L() { local l=; builtin printf -vl "%${2:-${COLUMNS:-`tput cols 2>&-||echo 80`}}s\n" && echo -e "${l// /${1:-=}}"; } With color: L "`tput setaf 3`=" 1. Use printf to store n space chars followed by a newline to an environment variable "l" where n is local environment variable from $COLUMNS if set, else it will use `tput cols` and if that fails it will default to 80. 2. If printf succeeds then echo `$l` that contains the chars, replacing all blank spaces with "-" (can be changed to anything you want). From: http://www.askapache.com/linux/bash_profile-functions-advanced-shell.html http://www.askapache.com/linux/bash-power-prompt.html Show Sample Output


    4
    printf -vl "%${COLUMNS:-`tput cols 2>&-||echo 80`}s\n" && echo ${l// /-};
    AskApache · 2016-09-25 10:37:20 15
  • I didn't come up with this myself, but I always add this to my .bash_aliases file. It's essentially the same idea as running "sudo !!" except it's much easier to type. (You can't just alias "sudo !!", it doesn't really work for reasons I don't understand.) "fc" is a shell built-in for editing and re-running previous commands. The -l flag tells it to display the line rather than edit it, and the -n command tells it to omit the line number. -1 tells it to print the previous line. For more detail: help fc


    4
    alias please='sudo $(fc -ln -1)'
    suspenderguy · 2018-06-13 20:20:19 241

  • 4
    diff <(tree /dir/one) <(tree /dir/two)
    redraw · 2019-09-19 01:33:08 116
  • Cleanly create tempfiles using mktemp and remove them using traps instead of removing them in the end of the script. This way, you make sure the tempfiles are removed properly even if the script is killed or interrupted. For a user script in KDE4, you can set TMPROOT using : TMPROOT=$(kde4-config --path tmp)


    3
    TMPROOT=/tmp; TMPDIR=$(mktemp -d $TMPROOT/somedir.XXXXXX); TMPFILE=$(mktemp $TMPROOT/somefile.XXXXXX); trap "rm -rf $TMPDIR $TMPFILE; exit" INT TERM EXIT; some treatment using $TMPDIR and $TMPFILE; exit 0
    raphink · 2009-02-24 09:35:22 5
  • Useful to e.g. keep an eye on several logfiles. Show Sample Output


    3
    tail -f file1 (file2 .. fileN)
    hberth · 2009-03-02 11:13:42 7

  • 3
    sort file1.txt | uniq > file2.txt
    rain · 2009-03-14 20:24:06 17
  • The output of "echo $PATH" is hard to read, this is much easier. The parentheses ensure that the change to the input field separator (IFS) only happens the the sub shell and not affecting the current shell. Show Sample Output


    3
    ( IFS=:; for p in $PATH; do echo $p; done )
    haivu · 2009-03-19 22:45:47 8
  • Reads a username from Show Sample Output


    3
    read -p 'Username: ' u;sudo -H -u $u xauth add $(xauth list|grep :$(echo ${DISPLAY: -4:2}));sudo su - $u
    vutcovici · 2009-04-02 13:24:53 8
  • If you're like me and want to keep all your music rated, and you use xmms2, you might like this command. I takes 10 random songs from your xmms2 library that don't have any rating, and adds them to your current playlist. You can then rate them in another xmms2 client that supports rating (I like kuechenstation). I'm pretty sure there's a better way to do the grep ... | sed ... part, probably with awk, but I don't know awk, so I'd welcome any suggestions. Show Sample Output


    3
    xmms2 mlib search NOT +rating | grep -r '^[0-9]' | sed -r 's/^([0-9]+).*/\1/' | sort -R | head | xargs -L 1 xmms2 addid
    goodevilgenius · 2009-04-16 20:27:30 6
  • The command is useful when, e.g., booting an existing system with a rescue or installation CD where you need to chroot into the hard-disk and be able to do stuff which accesses kernel info (e.g. when installing Ubuntu desktop with LVM2 you need to mount and chroot the hard disk from a shell window in order to install packages and run initramfs inside chroot). The command assumes that /mnt/xxx is where the chroot'ed environment's root file system on the hard disk is mounted.


    3
    for i in sys dev proc; do sudo mount --bind /$i /mnt/xxx/$i; done
    amosshapira · 2009-04-20 16:52:14 14
  • It can be hard to spot differences in reformatted files, because of all the diff noise created by word wrapped lines. This command removes all the noise and performs a word-by-word diff. To ignore empty lines, add -B to the diff command. Also, if this is something you do often, you might want to check out the wdiff(1) program.


    3
    diff -uw <(fmt -1 {file1, file2})
    sunny256 · 2009-05-23 03:11:08 4
  • Chronic Bash function: chronic 3600 time # Print the time in your shell every hour chronic 60 updatedb > /dev/null # update slocate every minute Note: use 'jobs' to list background tasks and fg/bg to take control of them.


    3
    chronic () { t=$1; shift; while true; do $@; sleep $t; done & }
    rhythmx · 2009-06-13 05:57:54 16
  • Useful if non-ascii characters in filenames have been improperly encoded. Replace "PROBLEM" with the incorrect characters (e.g. 'é'), and "FIX" with the correct ones (e.g. '?').


    3
    for i in *;do mv "$i" "$(echo $i | sed s/PROBLEM/FIX/g)";done
    AlecSchueler · 2009-06-28 01:50:25 18
  • print multiple increasing years using cal - calendar -. You can also try seq Start Increment End


    3
    for y in $(seq 2009 2011); do cal $y; done
    JesusSuperstar · 2009-07-10 10:07:46 26
  • I wanted all the 'hidden' .flv files from the http link in the command line; wget seemed appropriate, fed with output from lynx, grep the flv files and the normalised via sed (to remove the numeric bullet). Similar to the 'Grab mp3 files' fu. Replace link with your own, grep arg with something more interesting ;) See here for something along the same lines... http://www.commandlinefu.com/commands/view/1006/grab-mp3-files-from-your-favorite-netcasts-mp3blog-or-sites-that-often-have-good-mp3s Hope you find it useful! Improvements welcome, naturally.


    3
    wget `lynx -dump http://www.ebow.com/ebowtube.php | grep .flv$ | sed 's/[[:blank:]]\+[[:digit:]]\+\. //g'`
    spaceyjase · 2009-08-02 14:09:53 4

  • 3
    find $MAILDIR/ -type f -printf '%T@ %p\n' | sort --reverse | sed -e '{ 1,100d; s/[0-9]*\.[0-9]* \(.*\)/\1/g }' | xargs -i sh -c "cat {}&&rm -f {}" | gzip -c >>ARCHIVE.gz
    maergil · 2009-08-11 20:12:15 3
  • Based on the MrMerry one, just add some visuals to differentiate files and directories


    3
    du -a --max-depth=1 | sort -n | cut -d/ -f2 | sed '$d' | while read i; do if [ -f $i ]; then du -h "$i"; else echo "$(du -h --max-depth=0 "$i")/"; fi; done
    nickwe · 2009-09-03 20:43:43 3
  • This pipeline will find, sort and display all files based on mtime. This could be done with find | xargs, but the find | xargs pipeline will not produce correct results if the results of find are greater than xargs command line buffer. If the xargs buffer fills, xargs processes the find results in more than one batch which is not compatible with sorting. Note the "-print0" on find and "-0" switch for perl. This is the equivalent of using xargs. Don't you love perl? Note that this pipeline can be easily modified to any data produced by perl's stat operator. eg, you could sort on size, hard links, creation time, etc. Look at stat and just change the '9' to what you want. Changing the '9' to a '7' for example will sort by file size. A '3' sorts by number of links.... Use head and tail at the end of the pipeline to get oldest files or most recent. Use awk or perl -wnla for further processing. Since there is a tab between the two fields, it is very easy to process. Show Sample Output


    3
    find $HOME -type f -print0 | perl -0 -wn -e '@f=<>; foreach $file (@f){ (@el)=(stat($file)); push @el, $file; push @files,[ @el ];} @o=sort{$a->[9]<=>$b->[9]} @files; for $i (0..$#o){print scalar localtime($o[$i][9]), "\t$o[$i][-1]\n";}'|tail
    drewk · 2009-09-21 22:11:16 11
  • cd to the folder containing the wav files, then convert them all to flac. yeah baby! in ubuntu, to get the flac program just: sudo apt-get install flac flac file input formats are wav, aiff, raw, flac, oga and ogg Show Sample Output


    3
    flac --best *.wav
    nickleus · 2009-11-11 14:17:24 9
  • ‹ First  < 7 8 9 10 11 >  Last ›

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands


Check These Out

Using parcellite, indents the content of the clipboard manager
This command takes the content of a Parcellite-managed clipboard manager and add one level of indentation to it. It may be useful to indent a block of code which will enter inside another, already indented one but I use it mostly to indent code I will post in Stack Overflow questions and answers.

Multiple variable assignments from command output in BASH
No command substitution but subshell redirection

Sending a file over icmp with hping
you need to start a listening hping on the reciever: hping3 --listen 10.0.2.254 -I eth0 --sign MSGID1 then you can send your file: hping3 10.0.2.254 --icmp --sign MSGID1 -d 50 -c 1 --file a_file

Generate MD5 of string and output only the hash checksum in a readable format
Generates the md5 hash, without the trailing " -" and with the output "broken" into pairs of hexs.

Extract IPv4 addressess from file

lotto generator

Ease your directory exploration
Usage : tt [OCCURRENCE] tt will display a tree from your actual path tt .svn will display only line containing .svn

move contents of the current directory to the parent directory, then remove current directory.
I think this is less resource consuming than the previous examples

Both view and pipe the file without saving to disk
This is a cool trick to view the contents of the file on /dev/pts/0 (or whatever terminal you're using), and also send the contents of that file to another program by way of an unnamed pipe. All the while, you've not bothered saving any extra data to disk, like you might be tempted to do with sed or grep to filter output.

Produce 10 copies of the same string


Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: