Commands using echo (1,545)

  • Very useful in shell scripts because you can run a task nicely in the background using job-control and output progress until it completes. Here's an example of how I use it in backup scripts to run gpg in the background to encrypt an archive file (which I create in this same way). $! is the process ID of the last run command, which is saved here as the variable PI, then sleeper is called with the process id of the gpg task (PI), and sleeper is also specified to output : instead of the default . every 3 seconds instead of the default 1. So a shorter version would be sleeper $!; The wait is also used here, though it may not be needed on your system. echo ">>> ENCRYPTING SQL BACKUP" gpg --output archive.tgz.asc --encrypt archive.tgz 1>/dev/null & PI=$!; sleeper $PI ":" 3; wait $PI && rm archive.tgz &>/dev/null Previously to get around the $! not always being available, I would instead check for the existance of the process ID by checking if the directory /proc/$PID existed, but not everyone uses proc anymore. That version is currently the one at http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html but I plan on upgrading to this new version soon. Show Sample Output


    14
    sleeper(){ while `ps -p $1 &>/dev/null`; do echo -n "${2:-.}"; sleep ${3:-1}; done; }; export -f sleeper
    AskApache · 2009-09-21 07:36:25 8
  • Plot your most used commands with gnuplot.


    14
    history | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head > /tmp/cmds | gnuplot -persist <(echo 'plot "/tmp/cmds" using 1:xticlabels(2) with boxes')
    sthrs · 2010-06-13 23:35:13 7
  • usage: sitepass MaStErPaSsWoRd example.com description: An admittedly excessive amount of hashing, but this will give you a pretty secure password, It also eliminates repeated characters and deletes itself from your command history. tr '!-~' 'P-~!-O' # this bit is rot47, kinda like rot13 but more nerdy rev # this avoids the first few bytes of gzip payload, and the magic bytes. Show Sample Output


    13
    sitepass() { echo -n "$@" | md5sum | sha1sum | sha224sum | sha256sum | sha384sum | sha512sum | gzip - | strings -n 1 | tr -d "[:space:]" | tr -s '[:print:]' | tr '!-~' 'P-~!-O' | rev | cut -b 2-11; history -d $(($HISTCMD-1)); }
    grokskookum · 2009-10-01 20:14:57 12
  • This one liner takes the shell code that you can grab off of the web and disassemble it into readable assembly so you can validate the code does what it says, before using it. The shell code in the above example is from http://www.shell-storm.org/shellcode/files/shellcode-623.php You can replace "-s intel" with "-s att" to get AT&T format disassembly. Show Sample Output


    13
    echo -ne "<shellcode>" | x86dis -e 0 -s intel
    dsearle · 2010-06-12 08:08:13 9
  • Setting: You have a lot of jpg files in a directory. Maybe your public_html folder which is readable on the net because of Apache's mod_userdir. All those files from the current folder will be dropped into a file called gallery.html as image tags that can be viewed within a web browser locally or or over the Internet. Original: find . -iname "*.jpg" -exec echo "<img src=\"{}\">" >> gallery.html \;


    13
    find . -iname '*.jpg' -exec echo '<img src="{}">' \; > gallery.html
    Schneckentreiber · 2010-07-03 16:36:15 7
  • Dialog's gauge widget accepts progress updates on stdin. This version runs dialog once and updates it every second. There's no need to use timeout which causes screen flicker since it restarts dialog for each update.


    13
    for i in {0..600}; do echo $i; sleep 1; done | dialog --gauge "Install..." 6 40
    dennisw · 2010-10-05 02:29:23 4
  • Commandlinefu.com is great but has a few bugs when people are submitting new commands: . 1. There is no preview button. This was a minor inconvenience before, but now is a major problem since new commands won't show up to be edited until they have been moderated. . 2. White space in the description field and in the comments is almost completely lost. People resort to using periods in between paragraphs to force a line break. Indentation of code is ridiculous. . 3. Many characters get munged. . 3a. For example, a less than character in the description gets read as an HTML tag and discarded. In order to type a less than, I've had to type "&lt;" (I hope that comes out right). Unfortunately, when re-editing a command, the HTML entity is turned into a literal less than character, which I have to change back by hand before saving. 3b. Some unicode characters work in the description field, but turn into ugly literal HTML strings when put in the sample output or in an additional command using the $ prefix. . For example, here is a unicode character: ❥ Here is the same character after a dollar sign: &#10085; . 3c. Some unicode characters don't work anywhere. Bizarrely, it appears to be the most commonly needed ones, such as Latin-1 accented characters. Here are some examples, . Bullet: ?, Center dot: ?, Umlaut u: ?. . 4. Here is an example of the greater than, >, and less than, . 5. Commandlinefu used to abbreviate long descriptions on the front page and had a "more..." button so that people could read the rest if they wanted. That's a good feature as it encourages people to explain their commands more fully. Either, the feature has gone missing, or, perhaps, I was just hallucinating it existed in the first place. If the former, please bring it back, If the latter, please implement this great new feature I just thought up. . 6. Tags cannot include Unicode characters. If you try to type one in, the cursor will just spin and spin as it attempt to look up if that tag exists already. For example, try typing Ctrl+Shift+u 2 7 6 5 SPC as a tag name. Show Sample Output


    13
    echo "?????, these are the umlauted vowels I sing to you. Oh, and sometimes ?, but I don't sing that one cause it doesn't rhyme."
    hackerb9 · 2011-01-05 05:56:20 9
  • Invoked from within a shell script, this will print the directory in which the script resides. Doesn't depend on external tools, /proc/self/*, etc.. (`echo` is a shell builtin.) To see the *current working* directory of a script, use `pwd`.


    13
    echo "${0%/*}"
    mhs · 2011-04-17 12:09:56 12
  • Put it in your ~/.bashrc usage: google word1 word2 word3... google '"this search gets quoted"' Show Sample Output


    13
    function google { Q="$@"; GOOG_URL='https://www.google.de/search?tbs=li:1&q='; AGENT="Mozilla/4.0"; stream=$(curl -A "$AGENT" -skLm 10 "${GOOG_URL}${Q//\ /+}" | grep -oP '\/url\?q=.+?&amp' | sed 's|/url?q=||; s|&amp||'); echo -e "${stream//\%/\x}"; }
    michelsberg · 2013-04-05 08:04:15 9
  • ;)


    12
    echo SSBMb3ZlIFlvdQo= | base64 -d
    grissiom · 2009-02-07 11:58:39 30
  • Define a function vert () { echo $1 | grep -o '.'; } Use it to print some column headers paste <(vert several) <(vert parallel) <(vert vertical) <(vert "lines of") <(vert "text can") <(vert "be used") <(vert "for labels") <(vert "for columns") <(vert "of numbers") Show Sample Output


    12
    echo "vertical text" | grep -o '.'
    dennisw · 2009-09-11 03:45:04 10
  • The above code is just an example of printing on the same line, hit Ctrl + C to stop When using echo -ne "something\r", echo will: - print "something" - dont print a new line (-n) - interpret \r as carriage return, going back to the start of the line (-e) Remember to print some white spaces after the output if your command will print lines of different sizes, mainly if one line will be smaller than the previous Edit from reading comments: You can achieve the same effect using printf (more standardized than echo): while true; do printf "%-80s\r" "$(date)"; sleep 1; done


    12
    while true; do echo -ne "$(date)\r"; sleep 1; done
    polaco · 2009-11-17 22:45:37 12
  • Simple countdown clock that should be quite portable across any Bourne-compatible shell. I used to teach for a living, and I would run this code when it was time for a break. Usually, I would set "MIN" to 15 for a 15-minute break. The computer would be connected to a projector, so this would be projected on screen, front and center, for all to see. Show Sample Output


    12
    MIN=1 && for i in $(seq $(($MIN*60)) -1 1); do echo -n "$i, "; sleep 1; done; echo -e "\n\nBOOOM! Time to start."
    atoponce · 2010-06-20 15:19:12 198

  • 12
    echo $(openssl rand 4 | od -DAn)
    putnamhill · 2010-11-09 14:55:39 10
  • substrings a variable starting at position. If no offset given prints rest of the line Show Sample Output


    12
    var='123456789'; echo ${var:<start_pos>:<offset>}
    totti · 2011-09-14 20:05:17 5
  • When expanding, bash output the command, so don't be affraid if you type the command. Here is the details: First examples: echo foo bar foobar barfoo First argument: echo !$ echo barfoo barfoo (Note that typing echo foo bar foobar barfoo && echo !$, bash substitute !$ with $:1) Last argument: echo foo bar foobar barfoo && echo !^ echo foo bar foobar barfoo && echo barfoo foo bar foobar barfoo barfoo All the arguments: echo !* echo foo bar foobar barfoo foo bar foobar barfoo The third argument: echo foo bar foobar barfoo && echo !:3 echo foo bar foobar barfoo && echo foobar foo bar foobar barfoo foobar You may want to add {} for large numbers: echo !:{11} for example Now with path: echo /usr/bin/foobar /usr/bin/foobar For the head: echo !$:h echo /usr/bin /usr/bin And the tail: echo !$:t echo foobar foobar You also may want to try !:h and !:t or !!3-4 for the third and the fourth (so !!:* == !!:1-$)


    11
    echo foo bar foobar barfoo && echo !$ !^ !:3 !* && echo /usr/bin/foobar&& echo !$:h !$:t
    lhb · 2009-02-17 09:10:17 11
  • From screen's manpage: "Attach here and now. In detail this means: If a session is running, then reattach. If necessary detach and logout remotely first. If it was not running create it and notify the user. This is the author's favorite." Toss this in your ~/.bash_profile so that you never have that "oh crap" moment where you wanted to run something in screen and didn't.


    11
    echo "screen -DR" >> ~/.bash_profile
    sud0er · 2009-04-28 20:45:37 5
  • The variable ? contain the last exit status of a command, it can be printed for troubleshooting purpose. Show Sample Output


    11
    echo $?
    servermanaged · 2009-05-09 17:32:23 15
  • This works in some situations where 'reset' and the other alternatives don't.


    11
    echo <ctrl-v><esc>c<enter>
    kcm · 2009-08-05 18:32:28 9
  • This command uses mutt to send the mail. You must pipe in a body, otherwise mutt will prompt you for some stuff. If you don't have mutt, it should be dead easy to install.


    11
    echo "Body goes here" | mutt -s "A subject" -a /path/to/file.tar.gz recipient@example.com
    ketil · 2009-08-05 23:06:25 10
  • Sqlite database keeps collecting cruft as time passes, which can be cleaned by the 'vacuum;' command. This command cleans up the cruft in all sqlite files relating to the user you have logged in as. This command has to be run when firefox is not running, or it will exit displaying the pid of the firefox running.


    11
    pgrep -u `id -u` firefox-bin || find ~/.mozilla/firefox -name '*.sqlite'|(while read -e f; do echo 'vacuum;'|sqlite3 "$f" ; done)
    kamathln · 2009-08-22 10:36:05 10
  • Displays a scrolling banner which loops until you hit Ctrl-C to terminate it. Make sure you finish your banner message with a space so it will loop nicely.


    11
    while [ 1 ]; do banner 'ze missiles, zey are coming! ' | while IFS="\n" read l; do echo "$l"; sleep 0.01; done; done
    craigds · 2009-12-14 07:40:07 10
  • if you're using wildcards * or ? in your command, and if you're deleting, moving multiple files, it's always safe to see how those wildcards will expand. if you put "echo" in front of your command, the expanded form of your command will be printed. It's better safe than sorry. Show Sample Output


    11
    echo rm *.txt
    alperyilmaz · 2010-10-27 07:26:26 6
  • Countdown clock - Counts down from $MIN minutes to zero. I let the date command do the maths. This version doesn't use seq. Show Sample Output


    11
    MIN=10;for ((i=MIN*60;i>=0;i--));do echo -ne "\r$(date -d"0+$i sec" +%H:%M:%S)";sleep 1;done
    flatcap · 2011-02-20 11:56:28 25
  • Command makes use of the Malware Hash Registry (http://www.team-cymru.org/Services/MHR/). It parses the current directory and subdirectories and calculates the md5 hash of the files, then prints the name and sends the hash to the MHR for a lookup in their database. The 3rd value in the result is the detection percentage across a mix of AV packages. Show Sample Output


    11
    IFS=$'\n' && for f in `find . -type f -exec md5sum "{}" \;`; do echo $f | sed -r 's/^[^ ]+/Checking:/'; echo $f | cut -f1 -d' ' | netcat hash.cymru.com 43 ; done
    Neo23x0 · 2011-10-15 03:38:47 6
  •  < 1 2 3 4 5 >  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

power off system in X hours form the current time, here X=2

generate a unique and secure password for every website that you login to
usage: sitepass MaStErPaSsWoRd example.com description: An admittedly excessive amount of hashing, but this will give you a pretty secure password, It also eliminates repeated characters and deletes itself from your command history. tr '!-~' 'P-~!-O' # this bit is rot47, kinda like rot13 but more nerdy rev # this avoids the first few bytes of gzip payload, and the magic bytes.

Route outbound SMTP connections through a addtional IP address rather than your primary

Quick and dirty RSS
runs an rss feed through sed replacing the closing tags with newlines and the opening tags with white space making it readable.

Extract the MBR ID of a device
Useful when you want to know the mbrid of a device - for the purpose of making it bootable. Certain hybridiso distros, for eg the OpenSUSE live ISO uses the mbrid to find the live media. Use this command to find out the mbrid of your USB drive and then edit the /grub/mbrid file to match it.

Convert CSV to JSON
Replace 'csv_file.csv' with your filename.

Find files that were modified by a given command
Traces the system calls of a program. See http://linuxhelp.blogspot.com/2006/05/strace-very-powerful-troubleshooting.html for more information.

Check wireless link quality with dialog box
The variable WIRELESSINTERFACE indicates your wireless interface

Show current network interface in use

Perform a branching conditional
This will perform one of two blocks of code, depending on the condition of the first. Essentially is a bash terniary operator. To tell if a machine is up: $ ping -c1 machine { echo succes;} || { echo failed; } Because of the bash { } block operators, you can have multiple commands $ ping -c1 machine && { echo success;log-timestamp.sh }|| { echo failed; email-admin.sh; } Tips: Remember, the { } operators are treated by bash as a reserved word: as such, they need a space on either side. If you have a command that can fail at the end of the true block, consider ending said block with 'false' to prevent accidental execution


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: