Commands using echo (1,545)

  • only for sudo-style systems. Use this construct instead of I/O re-directors ``>'' or ``>>'' because sudo only elevates the commands and *not* the re-directors. ***warning: remember that the `tee` command will clobber file contents unless it is given the ``-a'' argument Also, for extra security, the "left" command is still run unprivileged. Show Sample Output


    4
    echo "Whatever you need" | sudo tee [-a] /etc/system-file.cfg
    asmoore82 · 2009-03-09 01:33:31 7
  • Yes, it's useless.


    4
    a=`printf "%*s" 16`;b=${a//?/{0..1\}}; echo `eval "echo $b"`
    rhythmx · 2009-06-13 06:32:35 5
  • Display the amount of memory used by all the httpd processes. Great in case you are being Slashdoted!


    4
    ps -o rss -C httpd | tail -n +2 | (sed 's/^/x+=/'; echo x) | bc
    ricardoarguello · 2009-07-31 15:15:08 9
  • Only tested on Linux Ubunty Hardy. Works when file names have spaces. The "-maxdepth 2" limits the find search to the current directory and the next one deeper in this example. This was faster on my system because find was searching every directory before the current directory without the -maxdepth option. Almost as fast as locate when used as above. Must use double quotes around pattern to handle spaces in file names. -print0 is used in combination with xargs -0. Those are zeros not "O"s. For xargs, -I is used to replace the following "{}" with the incoming file-list items from find. Echo just prints to the command line what is happening with mv. mv needs "{}" again so it knows what you are moving from. Then end with the move destination. Some other versions may only require one "{}" in the move command and not after the -I, however this is what worked for me on Ubuntu 8.04. Some like to use -type f in the find command to limit the type. Show Sample Output


    4
    find . -maxdepth 2 -name "*somepattern" -print0 | xargs -0 -I "{}" echo mv "{}" /destination/path
    jonasrullo · 2009-08-01 01:55:47 7
  • #Usage: watch timeinsecond "command" Show Sample Output


    4
    watch() { while test :; do clear; date=$(date); echo -e "Every "$1"s: $2 \t\t\t\t $date"; $2; sleep $1; done }
    peshay · 2009-08-19 15:29:00 3
  • This never gets old Show Sample Output


    4
    echo {1..3}" o'clock" ROCK
    JackiesJungle · 2009-09-14 15:39:07 5
  • I usually have 5 or more ssh connections to various servers, and putting this command in my .bash_profile file makes my putty window or x terminal window title change to this easily recognizable and descriptive text. Includes the username, group, server hostname, where I am connecting from (for SSH tunneling), which device pts, current server load, and how many processes are running. You can also use this for your PROMPT_COMMAND variable, which updates the window title to the current values each time you exec a command. I prefix running this in my .bash_profile with [[ ! -z "$SSH_TTY" ]] && which makes sure it only does this when connecting via SSH with a TTY. Here's some rougher examples from http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html # If set, the value is executed as a command prior to issuing each primary prompt. #H=$((hostname || uname -n) 2>/dev/null | sed 1q);W=$(whoami) #export PROMPT_COMMAND='echo -ne "\033]0;${W}@${H}:${PWD/#$HOME/~} ${SSH_TTY/\/dev\//} [`uptime|sed -e "s/.*: \([^,]*\).*/\1/" -e "s/ //g"`]\007"' #PROMPT_COMMAND='echo -ne "\033]0;`id -un`:`id -gn`@`hostname||uname -n 2>/dev/null|sed 1q` `command who -m|sed -e "s%^.* \(pts/[0-9]*\).*(\(.*\))%[\1] (\2)%g"` [`uptime|sed -e "s/.*: \([^,]*\).*/\1/" -e "s/ //g"` / `command ps aux|wc -l`]\007"' #[[ -z "$SSH_TTY" ]] || export PROMPT_COMMAND #[[ -z "$SSH_TTY" ]] && [[ -f /dev/stdout ]] && SSH_TTY=/dev/stdout And here's a simple function example for setting the title: function set_window_title(){ echo -e "\033]0; ${1:-$USER@$HOST - $SHLVL} \007"; } Show Sample Output


    4
    echo -ne "\033]0;`id -un`:`id -gn`@`hostname||uname -n|sed 1q` `who -m|sed -e "s%^.* \(pts/[0-9]*\).*(\(.*\))%[\1] (\2)%g"` [`uptime|sed -e "s/.*: \([^,]*\).*/\1/" -e "s/ //g"` / `ps aux|wc -l`]\007"
    AskApache · 2009-09-19 06:57:53 4
  • With this form you dont need to cut out target directory using grep/sed/etc.


    4
    (ls; mkdir subdir; echo subdir) | xargs mv
    mechmind · 2009-11-08 11:40:55 13
  • Convert some decimal numbers to binary numbers. You could also build a general base-converter: function convBase { echo "ibase=$1; obase=$2; $3" | bc; } then you could write function decToBun { convBase 10 2 $1; } Show Sample Output


    4
    function decToBin { echo "ibase=10; obase=2; $1" | bc; }
    woxidu · 2009-11-24 22:57:58 3

  • 4
    echo "There are $(($(date +%j -d"Dec 31, $(date +%Y)")-$(date +%j))) left in year $(date +%Y)."
    unixhome · 2010-02-06 00:15:40 13
  • Set up X forwarding in PuTTY, with X display location set to :0.0 Launch PuTTY ssh session. Launch Xming. Make sure that display is set to :0.0 (this is default). echo "I'm going to paste this into WINDERS XP" | xsel -i will insert the string into the windows cut and paste buffer. Thanks to Dennis Williamson at stackoverflow.com for sharing...


    4
    echo "I'm going to paste this into WINDERS XP" | xsel -i
    bartonski · 2010-02-08 00:23:43 9
  • Check if you have 64bit by looking for "lm" in cpuinfo. lm stands for "long mem". This can also be used without being root.


    4
    if cat /proc/cpuinfo | grep " lm " &> /dev/null; then echo "Got 64bit" ; fi
    xeor · 2010-04-10 15:31:58 6
  • To do hex to binary: echo 'ibase=16; obase=2; 16*16' | bc # prints: 111100100 To do 16*16 from decimal to hex: echo 'ibase=10; obase=16; 16*16' | bc # prints: 100 You get the idea... Alternatively, run bc in interactive mode (see man page) Show Sample Output


    4
    echo 'obase=16; C+F' | bc
    rkulla · 2010-04-14 20:35:31 7
  • just a bit simpler


    4
    echo $ascii | perl -ne 'printf "%x", ord for split //'
    linuxrawkstar · 2010-04-19 11:57:08 4
  • Very handy way to perform a host scan if you don't have nmap,ncat,nc ...or other tools installed locally. When executing a command on a /dev/tcp/$host/$port pseudo-device file, Bash opens a TCP connection to the associated socket and UDP connection when using /dev/udp/$host/$port.A simlpe way to get servers banner is to run this command "cat < /dev/tcp/localhost/25" , here you will get mail server's banner. NOTE: Bash, as packaged for Debian, does not support using the /dev/tcp and /dev/udp pseudo-device it's not enabled by default Because bash in Debian is compiled with ?disable-net-redirections. Show Sample Output


    4
    for p in {1..1023}; do(echo >/dev/tcp/localhost/$p) >/dev/null 2>&1 && echo "$p open"; done
    benyounes · 2010-04-26 18:09:22 41
  • Searches for web radio by submitted keyword and returns the station name and the link for listing . May be enhanced to read user's selection and submit it to mplayer. Show Sample Output


    4
    echo "Keyword?";read keyword;query="http://www.shoutcast.com/sbin/newxml.phtml?search="$keyword"";curl -s $query |awk -F '"' 'NR <= 4 {next}NR>15{exit}{sub(/SHOUTcast.com/,"http://yp.shoutcast.com/sbin/tunein-station.pls?id="$6)}{print i++" )"$2}'
    benyounes · 2010-05-03 00:44:10 8
  • Checks if a web page has changed. Put it into cron to check periodically. Change http://www.page.de/test.html and mail@mail.de for your needs.


    4
    HTMLTEXT=$( curl -s http://www.page.de/test.html > /tmp/new.html ; diff /tmp/new.html /tmp/old.html ); if [ "x$HTMLTEXT" != x ] ; then echo $HTMLTEXT | mail -s "Page has changed." mail@mail.de ; fi ; mv /tmp/new.html /tmp/old.html
    Emzy · 2010-07-04 21:45:37 5
  • [ 2000 -ge "$(free -m | awk '/buffers.cache:/ {print $4}')" ] returns true if less than 2000 MB of RAM are available, so adjust this number to your needs. [ $(echo "$(uptime | awk '{print $10}' | sed -e 's/,$//' -e 's/,/./') >= $(grep -c ^processor /proc/cpuinfo)" | bc) -eq 1 ] returns true if the current machine load is at least equal to the number of CPUs. If either of the tests returns true we wait 10 seconds and check again. If both tests return false, i.e. 2GB are available and machine load falls below number of CPUs, we start our command and save it's output in a text file. The ( ( ... ) & ) construct lets the command run in background even if we log out. See http://www.commandlinefu.com/commands/view/3115/ .


    4
    ( ( while [ 2000 -ge "$(free -m | awk '/buffers.cache:/ {print $4}')" ] || [ $(echo "$(uptime | awk '{print $10}' | sed -e 's/,$//' -e 's/,/./') >= $(grep -c ^processor /proc/cpuinfo)" | bc) -eq 1 ]; do sleep 10; done; my-command > output.txt ) & )
    michelsberg · 2010-07-13 09:12:11 3
  • The simplest way to do it. Works for me, at least. (Why are the variables being set?)


    4
    echo notify-send test | at now+1minute
    polar · 2010-08-08 03:11:11 7
  • you could save the code between if and fi to a shell script named smiley.sh with the first argument as and then do a smiley.sh to see if the command succeeded. a bit needless but who cares ;) Show Sample Output


    4
    <commmand>; if [[ "$?" = 0 ]]; then echo ':)'; else echo ':('; fi
    potatoface · 2010-08-23 20:35:31 13

  • 4
    echo "savedefault --default=2 --once" | grub --batch; sudo reboot
    binfalse · 2010-08-31 22:40:19 4
  • Like 7171, but fixed typo, uses fewer variables, and even more cryptic! Show Sample Output


    4
    read -a A<<<".*.**..*....*** 8 9 5 10 6 0 2 11 7 4";for C in `date +"%H%M"|fold -w1`;do echo "${A:${A[C+1]}:4}";done
    __ · 2010-12-02 22:04:49 4
  • Run as root. Path may vary depending on laptop model and video card (this was tested on an Acer laptop with ATI HD3200 video). cat /proc/acpi/video/VGA/LCD/brightness to discover the possible values for your display.


    4
    echo <percentage> > /proc/acpi/video/VGA/LCD/brightness
    renan2112 · 2010-12-29 13:51:45 10
  • Configures screen to always display the clock in the last line (has to be configured only once). After that you not only have got the possibility to detach sessions and run them in background, but also have got a nice clock permanently on your screen.


    4
    echo 'hardstatus alwayslastline " %d-%m-%y %c:%s | %w"' >> $HOME/.screenrc; screen
    olorin · 2011-02-16 08:04:56 4
  • I created this so I could send myself an email alert when a long-running job was finished, e.g., my_long_job.exe ; quickemail my_long_job.exe has finished


    4
    quickemail() { echo "$*" | mail -s "$*" email@email.com; }
    dbh · 2011-02-22 20:33:18 3
  • ‹ First  < 8 9 10 11 12 >  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

Add page numbers to a PDF
Put this code in a bash script. The script expects the PDF file as its only parameter. It will add a header to the PDF containing the page numbers and output it to a file with the suffix "-header.pdf" Requires enscript, ps2pdf and pdftk.

Your name backwards

test for ksh/bash
Dave Korn gave me this one. It works because ksh allows variable names ( w/o the $name syntax ) used by sh and bash. I wrote it to permit "single source" shell libraries; the current objective: every shell library may be sourced by either shell. see http://github.com/applemcg/backash

Which processes are listening on a specific port (e.g. port 80)
swap out "80" for your port of interest. Can use port number or named ports e.g. "http"

Find the package that installed a command

extract element of xml
poor man's xml parser :)

Convert seconds to [DD:][HH:]MM:SS
Converts any number of seconds into days, hours, minutes and seconds. sec2dhms() { declare -i SS="$1" D=$(( SS / 86400 )) H=$(( SS % 86400 / 3600 )) M=$(( SS % 3600 / 60 )) S=$(( SS % 60 )) [ "$D" -gt 0 ] && echo -n "${D}:" [ "$H" -gt 0 ] && printf "%02g:" "$H" printf "%02g:%02g\n" "$M" "$S" }

convert a .wmv to a .avi

Displays user-defined ps output and pidstat output about the top CPU or MEMory users.
It grabs the PID's top resource users with $(ps -eo pid,pmem,pcpu| sort -k 3 -r|grep -v PID|head -10) The sort -k is sorting by the third field which would be CPU. Change this to 2 and it will sort accordingly. The rest of the command is just using diff to display the output of 2 commands side-by-side (-y flag) I chose some good ones for ps. pidstat comes with the sysstat package(sar, mpstat, iostat, pidstat) so if you don't have it, you should. I might should take off the timestamp... :|

Create Encrypted WordPress MySQL Backup without any DB details, just the wp-config.php
The coolest way I've found to backup a wordpress mysql database using encryption, and using local variables created directly from the wp-config.php file so that you don't have to type them- which would allow someone sniffing your terminal or viewing your shell history to see your info. I use a variation of this for my servers that have hundreds of wordpress installs and databases by using a find command for the wp-config.php file and passing that through xargs to my function.


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: