October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories

October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Bash Shortcuts and Tips

Bash Shortcuts and Tips

Repeating an argument
You can repeat the last argument of the previous command in multiple ways. Have a look at this example:

$ mkdir /path/to/dir
$ cd !$

The second command might look a little strange, but it will just cd to /path/to/dir.

Some keyboard shortcuts for editing

There are some pretty useful keyboard shortcuts for editing in bash. They might appear familiar to Emacs users:

• Ctrl + a => Return to the start of the command you’re typing
• Ctrl + e => Go to the end of the command you’re typing
• Ctrl + u => Cut everything before the cursor to a special clipboard
• Ctrl + k => Cut everything after the cursor to a special clipboard
• Ctrl + y => Paste from the special clipboard that Ctrl + u and Ctrl + k save their data to
• Ctrl + t => Swap the two characters before the cursor (you can actually use this to transport a character from the left to the right, try it!)
• Ctrl + w => Delete the word / argument left of the cursor
• Ctrl + l => Clear the screen

Redirecting both Standard Output and Standard Error:

# ls -ltR 2>&1 > /tmp/temp.txt

Specify this in .bashrc

Make Bash append rather than overwrite the history on disk:

# shopt -s histappend

Whenever displaying the prompt, write the previous line to disk:

# export PROMPT_COMMAND=’history -a’

To erase duplicate entries in History.

# export HISTCONTROL=erasedups
(or)
# export HISTCONTROL=ignoreboth

To see the history with timestamps

# export HISTTIMEFORMAT=”%d/%m/%Y-%H:%M:%S ”

To set the Size of the historyHISTSIZE: The number of commands to remember in the command history. The default value is 500.

# export HISTSIZE=500

Searching the Past

  • Ctrl+R searches previous lines

This will put bash in history mode, allowing you to type a part of the command you’re looking for. In the meanwhile, it will show the most recent occasion where the string you’re typing was used. If it is showing you a too recent command, you can go further back in history by pressing Ctrl + r again and again. Once you found the command you were looking for, press enter to run it.

  • !tcp will execute the previous command which starts with “tcp”

Creating large empty files in Linux / UNIX

Creating large empty files in Linux / UNIX

To create large empty files in Linux or UNIX:

# dd if=/dev/zero of=filename bs=1024 count=desired

Example to create a 1GB file:

dd if=/dev/zero of=file_1GB bs=1024 count=1000
/or/
dd if=/dev/zero of=file_1GB bs=4096 count=250
/or/
dd if=/dev/zero of=file_1GB bs=2048 count=500

Example to create a 2GB file:

dd if=/dev/zero of=file_2GB bs=2048 count=1000
/or/
dd if=/dev/zero of=file_2GB bs=1024 count=2000

Example to create a 512MB file:

dd if=/dev/zero of=file_512MB bs=1024 count=500
/or/
dd if=/dev/zero of=file_1GB bs=512 count=1000

either use

# mkfile size myfile

where can be in KB, MB or GB using k, m or g as suffix. To create a 10 GB file, use

# mkfile 10240m myfile

If you run # mkfile -n 10240m myfile the file will be created, but the disk blocks will not get allocated, only when writing data into the file.

 

 

Posted by Satish LN at 8:46 PM

rsync

rsync examples from command line.

 

To copy all the files in /home/lokams/* of remote host to local directory /backup/home/lokams/
# rsync -e ssh -avz –delete –exclude dir/* –delete-excluded –stats user@remotehost:/home/lokams/ /backup/home/lokams/

To copy the directory /home/lokams of remote host to local directory /backup/home. Directory “lokams” will get created in /backup/home.
# rsync -e ssh -avz –delete –exclude-from=~/.rsync/excludeFile –delete-excluded –stats user@remotehost:/home/lokams /backup/home/

To ignore the permissions errors while copying to remote windows/mac systems, use “-rlt” option.
# rsync -e ssh -avz –delete –exclude dir/* –delete-excluded –stats -rlt user@remotehost:/home/lokams/ /backup/home/lokams/

rsync behaves differently if the source directory has a trailing slash. Study and learn the difference between the following two commands before moving on. Use the -n option to rsync when testing to preview what would happen.

$ rsync -n -av /tmp .
$ rsync -n -av /tmp/ .

More rsync examples:
————————–

# rsync -crogpvltz -e ssh –exclude “bin” –exclude “ifany” –delete –delete-after –bwlimit 20 root@10.144.17.1:/apps/uae/ /apps/uae > /apps/uae/logs/sync.log

# rsync -avz -e ssh root@remotehost:/backup/reptest /backtmp/reptest/

# rsync -avz -e ssh /logstage/archive/DXBSEC/NODE0000/ db2inst1@10.20.202.236:/db2/archivelog/security/logstage/retrieve/DXBSEC/NODE0000/

# rsync -e ssh -avz –timeout=999 –delete –exclude dir-or-file-to-exclude –delete-excluded –stats -rlt user@remotehost:/home/lokams/

rsync useful options:
————————-

-a, –archive archive mode, equivalent to -rlptgoD
-n, –dry-run show what would have been transferred ( Preview mode )

-c – always checksum
-r – recursive into directories
-o – preserve owner
-g – preserve group
-p – preserve permissions
-t – preserve times
-v – verbose
-l – copy symlinks as symlinks
-z – compress file data
-P – show progress during transfer
-q – quite (decrease verbosity)
-e – specify the remote shell
-b – make backup
-R – Use relative path names
-u – skip files that are newer on the receiver

–stats give some file-transfer stats
–timeout=TIME set I/O timeout in seconds

–backup-dir – make backups into this directory
–bwlimit=KBPS – limit I/O bandwidth, KBytes per second
–delete – delete files that don’t exist on the sending side
–delete-after – receiver deletes after transferring, not before
–daemon run as an rsync daemon
–address=ADDRESS bind to the specified address
–exclude=PATTERN exclude files matching PATTERN
–exclude-from=FILE exclude patterns listed in FILE
–include=PATTERN don’t exclude files matching PATTERN
–include-from=FILE don’t exclude patterns listed in FILE
–min-size=SIZE don’t transfer any file smaller than SIZE
–max-size=SIZE don’t transfer any file larger than SIZE

# –numeric-ids:
Tells rsync to not map user and group id numbers local user and group names
# –delete:
Makes server copy an exact copy of the source by removing any files that have been removed on the remote machine

My Loveable Linux Commands

My Loveable Linux Commands
Command    Description

apropos whatis    Show commands pertinent to string See also threadsafe
man -t ascii | ps2pdf – > asciipdf    make a pdf of a manual page
which command    Show full path name of command
time command    See how long a command takes
time cat    Start stopwatch Ctrl-d to stop See also sw

Dir navigation

cd –    Go to previous directory
cd    Go to $HOME directory
(cd dir && command)    Go to dir, execute command and return to current dir
pushd     Put current dir on stack so you can popd back to it

File searching

alias l=’ls -l –color=auto’    quick dir listing
ls -lrt    List files by date See also newest and find_mm_yyyy
ls /usr/bin | pr -T9 -W$COLUMNS    Print in 9 columns to width of terminal
find -name ‘*[ch]’ | xargs grep -E ‘expr’    Search ‘expr’ in this dir and below See also findrepo
find -type f -print0 | xargs -r0 grep -F ‘example’    Search all regular files for ‘example’ in this dir and below
find -maxdepth 1 -type f | xargs grep -F ‘example’    Search all regular files for ‘example’ in this dir
find -maxdepth 1 -type d | while read dir; do echo $dir; echo cmd2; done    Process each item with multiple commands (in while loop)
find -type f ! -perm -444    Find files not readable by all (useful for web site)
find -type d ! -perm -111    Find dirs not accessible by all (useful for web site)
locate -r ‘file[^/]*\txt’    Search cached index for names This re is like glob *file*txt
look reference    Quickly search (sorted) dictionary for prefix
grep –color reference /usr/share/dict/words    Highlight occurances of regular expression in dictionary

Archives and compression

gpg -c file    Encrypt file
gpg filegpg    Decrypt file
tar -c dir/ | bzip2 > dirtarbz2    Make compressed archive of dir/
bzip2 -dc dirtarbz2 | tar -x    Extract archive (use gzip instead of bzip2 for targz files)
tar -c dir/ | gzip | gpg -c | ssh user@remote ‘dd of=dirtargzgpg’    Make encrypted archive of dir/ on remote machine
find dir/ -name ‘*txt’ | tar -c –files-from=- | bzip2 > dir_txttarbz2    Make archive of subset of dir/ and below
find dir/ -name ‘*txt’ | xargs cp -a –target-directory=dir_txt/ –parents    Make copy of subset of dir/ and below
( tar -c /dir/to/copy ) | ( cd /where/to/ && tar -x -p )    Copy (with permissions) copy/ dir to /where/to/ dir
( cd /dir/to/copy && tar -c  ) | ( cd /where/to/ && tar -x -p )    Copy (with permissions) contents of copy/ dir to /where/to/
( tar -c /dir/to/copy ) | ssh -C user@remote ‘cd /where/to/ && tar -x -p’    Copy (with permissions) copy/ dir to remote:/where/to/ dir
dd bs=1M if=/dev/sda | gzip | ssh user@remote ‘dd of=sdagz’    Backup harddisk to remote machine

rsync (Network efficient file copier: Use the –dry-run option for testing)

rsync -P rsync://rsyncservercom/path/to/file file    Only get diffs Do multiple times for troublesome downloads
rsync –bwlimit=1000 fromfile tofile    Locally copy with rate limit It’s like nice for I/O
rsync -az -e ssh –delete ~/public_html/ remotecom:’~/public_html’    Mirror web site (using compression and encryption)
rsync -auz -e ssh remote:/dir/  && rsync -auz -e ssh  remote:/dir/    Synchronize current directory with remote one

ssh (Secure SHell)

ssh $USER@$HOST command    Run command on $HOST as $USER (default command=shell)
ssh -f -Y $USER@$HOSTNAME xeyes    Run GUI command on $HOSTNAME as $USER
scp -p -r $USER@$HOST: file dir/    Copy with permissions to $USER’s home directory on $HOST
scp -c arcfour $USER@$LANHOST: bigfile    Use faster crypto for local LAN This might saturate GigE
ssh -g -L 8080:localhost:80 root@$HOST    Forward connections to $HOSTNAME:8080 out to $HOST:80
ssh -R 1434:imap:143 root@$HOST    Forward connections from $HOST:1434 in to imap:143
ssh-copy-id $USER@$HOST    Install public key for $USER@$HOST for password-less log in

wget (multi purpose download tool)

(cd dir/ && wget -nd -pHEKk http://wwwpixelbeatorg/cmdlinehtml)    Store local browsable version of a page to the current dir
wget -c http://wwwexamplecom/largefile    Continue downloading a partially downloaded file
wget -r -nd -np -l1 -A ‘*jpg’ http://wwwexamplecom/dir/    Download a set of files to the current directory
wget [url]ftp://remote/file[/url][1-9]iso/    FTP supports globbing directly
wget -q -O- http://wwwpixelbeatorg/timelinehtml | grep ‘a href’ | head    Process output directly
echo ‘wget url’ | at 01:00    Download url at 1AM to current dir
wget –limit-rate=20k url    Do a low priority download (limit to 20KB/s in this case)
wget -nv –spider –force-html -i bookmarkshtml    Check links in a file
wget –mirror http://wwwexamplecom/    Efficiently update a local copy of a site (handy from cron)

Networking (Note ifconfig, route, mii-tool, nslookup commands are obsolete)

ethtool eth0    Show status of ethernet interface eth0
ethtool –change eth0 autoneg off speed 100 duplex full    Manually set ethernet interface speed
iwconfig eth1    Show status of wireless interface eth1
iwconfig eth1 rate 1Mb/s fixed    Manually set wireless interface speed
iwlist scan    List wireless networks in range
ip link show    List network interfaces
ip link set dev eth0 name wan    Rename interface eth0 to wan
ip link set dev eth0 up    Bring interface eth0 up (or down)
ip addr show    List addresses for interfaces
ip addr add 1234/24 brd + dev eth0    Add (or del) ip and mask (2552552550)
ip route show    List routing table
ip route add default via 123254    Set default gateway to 123254
host pixelbeatorg    Lookup DNS ip address for name or vice versa
hostname -i    Lookup local ip address (equivalent to host `hostname`)
whois pixelbeatorg    Lookup whois info for hostname or ip address
netstat -tupl    List internet services on a system
netstat -tup    List active connections to/from system

windows networking (Note samba is the package that provides all this windows specific networking support)

smbtree    Find windows machines See also findsmb
nmblookup -A 1234    Find the windows (netbios) name associated with ip address
smbclient -L windows_box    List shares on windows machine or samba server
mount -t smbfs -o fmask=666,guest //windows_box/share /mnt/share    Mount a windows share
echo ‘message’ | smbclient -M windows_box    Send popup to windows machine (off by default in XP sp2)

Text manipulation (Note sed uses stdin and stdout Newer versions support inplace editing with the -i option)

sed ‘s/string1/string2/g’    Replace string1 with string2
sed ‘s/\(*\)1/\12/g’    Modify anystring1 to anystring2
sed ‘/ *#/d; /^ *$/d’    Remove comments and blank lines
sed ‘:a; /\\$/N; s/\\\n//; ta’    Concatenate lines with trailing \
sed ‘s/[ \t]*$//’    Remove trailing spaces from lines
sed ‘s/\([`”$\]\)/\\\1/g’    Escape shell metacharacters active within double quotes
seq 10 | sed “s/^/      /; s/ *\(\{7,\}\)/\1/”    Right align numbers
sed -n ‘1000{p;q}’    Print 1000th line
sed -n ‘10,20p;20q’    Print lines 10 to 20
sed -n ‘s/*<title>\(*\)<\/title>*/\1/ip;T;q’    Extract title from HTML web page
sed -i 42d ~/ssh/known_hosts    Delete a particular line
sort -t -k1,1n -k2,2n -k3,3n -k4,4n    Sort IPV4 ip addresses
echo ‘Test’ | tr ‘[:lower:]’ ‘[:upper:]’    Case conversion
tr -dc ‘[:print:]’ < /dev/urandom    Filter non printable characters
tr -s ‘[:blank:]’ ‘\t’ </proc/diskstats | cut -f4    cut fields separated by blanks
history | wc -l    Count lines

set operations (Note you can export LANG=C for speed Also these assume no duplicate lines within a file)
sort file1 file2 | uniq    Union of unsorted files
sort file1 file2 | uniq -d    Intersection of unsorted files
sort file1 file1 file2 | uniq -u    Difference of unsorted files
sort file1 file2 | uniq -u    Symmetric Difference of unsorted files
join -t’\0′ -a1 -a2 file1 file2    Union of sorted files
join -t’\0′ file1 file2    Intersection of sorted files
join -t’\0′ -v2 file1 file2    Difference of sorted files
join -t’\0′ -v1 -v2 file1 file2    Symmetric Difference of sorted files

math
echo ‘(1 + sqrt(5))/2’ | bc -l    Quick math (Calculate ?) See also bc
seq -f ‘4/%g’ 1 2 99999 | paste -sd-+ | bc -l    Calculate ? the unix way
echo ‘pad=20; min=64; (100*10^6)/((pad+min)*8)’ | bc    More complex (int) eg This shows max FastE packet rate
echo ‘pad=20; min=64; print (100E6)/((pad+min)*8)’ | python    Python handles scientific notation
echo ‘pad=20; plot [64:1518] (100*10**6)/((pad+x)*8)’ | gnuplot -persist    Plot FastE packet rate vs packet size
echo ‘obase=16; ibase=10; 64206’ | bc    Base conversion (decimal to hexadecimal)
echo $((0x2dec))    Base conversion (hex to dec) ((shell arithmetic expansion))
units -t ‘100m/958s’ ‘miles/hour’    Unit conversion (metric to imperial)
units -t ‘500GB’ ‘GiB’    Unit conversion (SI to IEC prefixes)
units -t ‘1 googol’    Definition lookup
seq 100 | (tr ‘\n’ +; echo 0) | bc    Add a column of numbers See also add and funcpy

calendar
cal -3    Display a calendar
cal 9 1752    Display a calendar for a particular month year
date -d fri    What date is it this friday See also day
[ $(date -d ’12:00 +1 day’ +%d) = ’01’ ] || exit    exit a script unless it’s the last day of the month
date –date=’25 Dec’ +%A    What day does xmas fall on, this year
date –date=’@2147483647′    Convert seconds since the epoch (1970-01-01 UTC) to date
TZ=’America/Los_Angeles’ date    What time is it on west coast of US (use tzselect to find TZ)
date –date=’TZ=”America/Los_Angeles” 09:00 next Fri’    What’s the local time for 9AM next Friday on west coast US

locales

printf “%’d\n” 1234    Print number with thousands grouping appropriate to locale
BLOCK_SIZE=\’1 ls -l    Use locale thousands grouping in ls See also l
echo “I live in `locale territory`”    Extract info from locale database
LANG=en_IEutf8 locale int_prefix    Lookup locale info for specific country See also ccodes
locale -kc $(locale | sed -n ‘s/\(LC_\{4,\}\)=*/\1/p’) | less    List fields available in locale database

recode (Obsoletes iconv, dos2unix, unix2dos)

recode -l | less    Show available conversions (aliases on each line)
recode windows-1252 file_to_changetxt    Windows “ansi” to local charset (auto does CRLF conversion)
recode utf-8/CRLF file_to_changetxt    Windows utf8 to local charset
recode iso-8859-15utf8 file_to_changetxt    Latin9 (western europe) to utf8
recode /b64 < filetxt > fileb64    Base64 encode
recode /qp < fileqp > filetxt    Quoted printable decode
recode HTML < filetxt > filehtml    Text to HTML
recode -lf windows-1252 | grep euro    Lookup table of characters
echo -n 0x80 | recode latin-9/x1dump    Show what a code represents in latin-9 charmap
echo -n 0x20AC | recode ucs-2/x2latin-9/x    Show latin-9 encoding
echo -n 0x20AC | recode ucs-2/x2utf-8/x    Show utf-8 encoding
CDs
gzip < /dev/cdrom > cdromisogz    Save copy of data cdrom
mkisofs -V LABEL -r dir | gzip > cdromisogz    Create cdrom image from contents of dir
mount -o loop cdromiso /mnt/dir    Mount the cdrom image at /mnt/dir (read only)
cdrecord -v dev=/dev/cdrom blank=fast    Clear a CDRW
gzip -dc cdromisogz | cdrecord -v dev=/dev/cdrom –    Burn cdrom image (use dev=ATAPI -scanbus to confirm dev)
cdparanoia -B    Rip audio tracks from CD to wav files in current dir
cdrecord -v dev=/dev/cdrom -audio -pad *wav    Make audio CD from all wavs in current dir (see also cdrdao)
oggenc –tracknum=’track’ trackcddawav -o ‘trackogg’    Make ogg file from wav file

disk space (See also FSlint)

ls -lSr    Show files by size, biggest last
du -s * | sort -k1,1rn | head    Show top disk users in current dir See also dutop
du -hs /home/* | sort -k1,1h    Sort paths by easy to interpret disk usage
df -h    Show free space on mounted filesystems
df -i    Show free inodes on mounted filesystems
fdisk -l    Show disks partitions sizes and types (run as root)
rpm -q -a –qf ‘%10{SIZE}\t%{NAME}\n’ | sort -k1,1n    List all packages by installed size (Bytes) on rpm distros
dpkg-query -W -f=’${Installed-Size;10}\t${Package}\n’ | sort -k1,1n    List all packages by installed size (KBytes) on deb distros
dd bs=1 seek=2TB if=/dev/null of=ext3test    Create a large test file (taking no space) See also truncate
> file    truncate data of file or create an empty file

monitoring/debugging

tail -f /var/log/messages    Monitor messages in a log file
strace -c ls >/dev/null    Summarise/profile system calls made by command
strace -f -e open ls >/dev/null    List system calls made by command
strace -f -e trace=write -e write=1,2 ls >/dev/null    Monitor what’s written to stdout and stderr
ltrace -f -e getenv ls >/dev/null    List library calls made by command
lsof -p $$    List paths that process id has open
lsof ~    List processes that have specified path open
tcpdump not port 22    Show network traffic except ssh See also tcpdump_not_me

ps -e -o pid,args –forest    List processes in a hierarchy
ps -e -o pcpu,cpu,nice,state,cputime,args –sort pcpu | sed ‘/^ 00 /d’    List processes by % cpu usage
ps -e -orss=,args= | sort -b -k1,1n | pr -TW$COLUMNS    List processes by mem (KB) usage See also ps_mempy
ps -C firefox-bin -L -o pid,tid,pcpu,state    List all threads for a particular process
ps -p 1,$$ -o etime=    List elapsed wall time for particular process IDs

last reboot    Show system reboot history

free -m    Show amount of (remaining) RAM (-m displays in MB)
watch -n1 ‘cat /proc/interrupts’    Watch changeable data continuously
udevadm monitor    Monitor udev events to help configure rules

System information (see also sysinfo) (‘#’ means root access is required)

uname -a    Show kernel version and system architecture
head -n1 /etc/issue    Show name and version of distribution
cat /proc/partitions    Show all partitions registered on the system
grep MemTotal /proc/meminfo    Show RAM total seen by the system
grep “model name” /proc/cpuinfo    Show CPU(s) info
lspci -tv    Show PCI info
lsusb -tv    Show USB info
mount | column -t    List mounted filesystems on the system (and align output)
grep -F capacity: /proc/acpi/battery/BAT0/info    Show state of cells in laptop battery

#    dmidecode -q | less    Display SMBIOS/DMI information
#    smartctl -A /dev/sda | grep Power_On_Hours    How long has this disk (system) been powered on in total
#    hdparm -i /dev/sda    Show info about disk sda
#    hdparm -tT /dev/sda    Do a read speed test on disk sda
#    badblocks -s /dev/sda    Test for unreadable blocks on disk sda

Interactive (see also linux keyboard shortcuts)

readline    Line editor used by bash, python, bc, gnuplot,
screen    Virtual terminals with detach capability,
mc    Powerful file manager that can browse rpm, tar, ftp, ssh,
gnuplot    Interactive/scriptable graphing
links    Web browser
xdg-open     open a file or url with the registered desktop application

Find Command

Find Command

Some examples:

Find all files with 777 permissions:
find . -type f -perm 777 -print

Find all files that are older than 14 days and ls:
find . -type f -mtime +14 -exec ls -l {} \;

Find all your writable files and list them:
find . -perm -0777 -type f -ls

Find files and change their permission to writeable:
find . -name “NAME*” -exec chmod 666 {} \;

Find files created in the past 7 days:
find . -mtime -7 -type f

Find files modified in the past 7 days:
find . -mtime -7 -type f

Find files owned by a particular user:
find . -user esofthub

Find files that were modified more than 7 days ago and tar them into an archive (with a date in the name):
find . -type f -mtime +7 | xargs tar -cvf `date ‘+%d%m%Y’_archive.tar`

Find files that were modified less than 7 days ago and tar them into an archive (with a date in the name):
find . -type f -mtime -7 | xargs tar -cvf `date ‘+%d%m%Y’_archive.tar`

Find how many files are in a path:
find . -type f -exec basename {} \; | wc -l

Find the top 50 Biggest Files:
find / -type f -not -path “/proc/*” -not -path “/dev/*” -not -path “/sys/*” -not -path “/home/rack/*” -printf “%s %h/%f\n” | sort -rn -k1 | head -n 50 | awk ‘{print $1/1048576 “MB” ” ” $2}’

 

xargs and find to selected copy

$ 4.2.29 8 508---> find  . -name "*gimp*"  -print0   | xargs -0 -I {}  cp  {} ../6raphics/
$ 4.2.29 9 509---> find  . -name "*gimp*"  -print0   | xargs -0 -I {}  cp  {} ../6raphics/
$ 4.2.29 10 510---> find  . -name "*blender*"  -print0   | xargs -0 -I {}  cp  {} ../6raphics/
$ 4.2.29 11 511---> find  . -name "*inkscape*"  -print0   | xargs -0 -I {}  cp  {} ../6raphics/
$ 4.2.29 12 512---> find  . -name "*Grap*"  -print0   | xargs -0 -I {}  cp  {} ../6raphics/
$ 4.2.29 13 513---> find  . -name "*grap*"  -print0   | xargs -0 -I {}  cp  {} ../6raphics/
$ 4.2.29 14 514---> 

find + grep 

find /schedapps/test/log -type f -name "*abc*log"

find /schedapps/test/log -type f -name "*log" | grep abc

find /schedapps/test/log -type f ! -name "*abc*log"

find /schedapps/test/log -type f -name "*log" | grep -v abc | grep -v def

find /schedapps/test/log -type f -name "*log" -mtime +7 | xargs rm -f

find /schedapps/etmd -type f -perm -o+w -exec ls -l {} \; | more

find /SqLogs –type f –name accesslog | xargs grep "TCP_DENIED"

find  path-name type -f -name "aliencoders*" | xargs -r ls -lRt | awk '{ print \$9 }'

Find occurrences of strings in files AND report file names

find  -name '*xml' -print | xargs grep 'hostName' /dev/null

Find files over a certain size eg 10K

find / -xdev -size +1024 -exec ls -al {} \; | sort -r -k 5

Find and tar files on the fly

find /opt/IBM/WebSphere/PortalServer/log -name 'System*log'| xargs tar -rvf System_logstar

Output wsadmin to console AND file

/opt/IBM/WebSphere/wp_profile/bin/wsadminsh -lang jython | tee wsadminlog

Find files touched in, say, the past 20 minutes

find * -mmin -20

Run a command on a loop

watch -d=10 -n 1 "netstat -a"

$ find . -name *.gif -exec ls {} \;

The -exec parameter holds the real power. When a file is found that matches the search criteria, the -exec parameter defines what to do with the file. This example tells the computer to:

 1. Search from the current directory on down, using the dot (.) just after find.
 2. Locate all files that have a name ending in .gif (graphic files).
 3. List all found files, using the ls command.

The -exec parameter requires further scrutiny. When a filename is found that matches the search criteria, the find command executes the ls {} string, substituting the filename and path for the {} text. If saturn.gif was found in the search, find would execute this command:

$ ls ./gif_files/space/solar_system/saturn.gif

An important alternative to the -exec parameter is -ok; it behaves the same as -exec, but it prompts you to see if you want to run the command on that file. Suppose you want to remove most of the .txt files in your home directory, but you wish to do it on a file-by-file basis. Delete operations like the UNIX rm command are dangerous, because it's possible to inadvertently delete files that are important when they're found by an automated process like find; you might want to scrutinize all the files the system finds before removing them.

The following command lists all the .txt files in your home directory. To delete the files, you must enter Y or y when the find command prompts you for action by listing the filename:

$ find $HOME/. -name *.txt -ok rm {} \;

Each file found is listed, and the system pauses for you to enter Y or y. If you press the Enter key, the system won't delete the file.

If too many files are involved for you to spend time with the -ok parameter, a good rule of thumb is to run the find command with -exec to list the files that would be deleted; then, after examining the list to be sure no important files will be deleted, run the command again, replacing ls with rm.

Both -exec and -ok are useful, and you must decide which works best for you in your current situation. Remember, safety first!

Examples:

  • To remove all temp, swap and core files in the current directory.
$ find . \( -name '*.tmp* -o -name '*.swp' -o -name 'core' \) -exec rm {} \;

  • To copy the entire contents of a directory while preserving the permissions, times, and ownership of every file and subdirectory
$ cd /path/to/source/dir
$ find . | cpio -vdump /path/to/destination/dir

  • To list the first line in every text file in your home directory
$ find $HOME/. -name *.txt -exec head -n 1 -v {} \; > report.txt
$ less <>

  • To maintain LOG and TMP file storage space for applications that generate a lot of these files, you can put the following commands into a cron job that runs daily:
  • The first command runs all the directories (-type d) found in the $LOGDIR directory wherein a file’s data has been modified within the last 24 hours (-mtime +0) and compresses them (compress -r {}) to save disk space. The second command deletes them (rm -f {}) if they are more than a work-week old (-mtime +5), to increase the free space on the disk. In this way, the cron job automatically keeps the directories for a window of time that you specify.
$ find $LOGDIR -type d -mtime +0 -exec compress -r {} \;
$ find $LOGDIR -type d -mtime +5 -exec rm -f {} \;

  • To find links that point to nothing
$ find / -type l -print | perl -nle '-e || print';

  • To list zero-length files
$ find . -empty -exec ls {} \;

  • To delete all *.tmp files in the home directory
$ find ~/. -name "*.tmp" | xargs rm
(or)
$ find ~/. -name "*.tmp" -exec rm {} \;

  • To see what hidden files in your home directory changed in the last 5 days:
$ find ~ -mtime -5 -name \.\*

  • If you know something has changed much more recently than that, say in the last 14 minutes, and want to know what it was there’s the mmin argument:
$ find ~ -mmin 14 -name \.\*

  • To locate files that have been modified since some arbitrary date use this little trick:
$ touch -d "13 may 2001 17:54:19" date_marker
$ find . -newer date_marker 

  • To find files created before that date, use the cnewer and negation conditions:
$ find . \! -cnewer date_marker

  • To find files containing between 600 to 700 characters, inclusive.
$ find . -size +599c -and -size -701c 

Thus we can use find to list files of a certain size:

$ find /usr/bin -size 48k

  • To find empty files
$ find . -size 0c

  • Using the -empty argument is more efficient. To delete empty files in the current directory:
$ find . -empty -maxdepth 1 -exec rm {} \;

  • To locate files belonging to a certain user:
# find /etc -type f \! -user root -exec ls -l {} \;

  • To search for files by the numerical group ID use the -gid argument:
$ find -gid 100

  • To find directories with ‘_of_’ in their name we’d use:
$ find . -type d -name '*_of_*'

  • To redirect the error messages to /dev/null
$ find / -name foo 2>/dev/null

  • To remove all files named core from your system.
# find / -name core | xargs /bin/rm -f
# find / -name core -exec /bin/rm -f '{}' \; # same thing
# find / -name core -delete # same if using Gnu find

  • To find files modified less than 10 minutes ago. I use this right after using some system administration tool, to learn which files got changed by that tool:
# find / -mmin -10

  • When specifying time with find options such as -mmin (minutes) or -mtime (24 hour periods, starting from now), you can specify a number n to mean exactly n, -n to mean less than n, and +n to mean more than n. 2 For example:
# find . -mtime 0 # find files modified within the past 24 hours
# find . -mtime -1 # find files modified within the past 24 hours
# find . -mtime 1 # find files modified between 24 and 48 hours ago
# find . -mtime +1 # find files modified more than 48 hours ago
# find . -mmin +5 -mmin -10 # find files modifed between 6 and 9 minutes ago

  • To find all files containing “house” in the name that are newer than two days and are larger than 10K, try this:
# find . -name “*house*” -size +10240 -mtime -2

  • The -xdev prevents the file “scan” from going to another disk volume (refusing to cross mount points, for example). Thus, you can look for all regular directories on the current disk from a starting point like this:
# find /var/tmp -xdev -type d -print

  • To find world writables in your system:
# find / -perm 777 | xargs ls -ld | grep -v ^l | grep -v ^s
# find / -perm 666 | xargs ls -ld | grep -v ^l | grep -v ^s

# find . -perm +o=w -exec ls -ld {} \; | grep -v ^l | grep -v ^s | grep -v ^c
or
# find . -perm +o=w | xargs ls -ld | grep -v ^l | grep -v ^s | grep -v ^c

  • To find the orphan files and directories in your system:
# find / -nouser -nogroup | xargs ls -ld

  • To find the files changed in last 5 mins and move them to a different folder.
# find /tmp -mmin -5 -type f -exec mv {} /home/lokams \;
(or)
# mv `find . -mmin -5 -type f` /tmp/
(or)
# find . -mmin -10 -type f | xargs -t -i {} mv {} /tmp/

  • To search on multiple directories
$ find /var /etc /usr -type f -user root -perm 644 -name '*ssh*'

  • To find and list all regular files set SUID to root (or anyone else with UID 0 😉
# find / -type f -user 0 -perm -4000

  • To find all regular files that are world-writable and removes world-writability:
# find / -type f -perm -2 -exec chmod o-w {} \;

  • To find all files owned by no one in particular and give them to root:
# find / -nouser -exec chown root {} \;

  • To find all files without group ownership and give them to the system group:
# find / -nogroup -exec chgrp system {} \;

  • To find and gzip regular files in current directory that do not end in .gz
$ gzip `find . -type f \! -name '*.gz' -print`

  • To find all empty files in my home directory and delete after being prompted:
$ find $HOME -size 0 -ok rm -f {} \;

  • To find all files or symlinks in /usr not named fred:
$ find /usr \( -type f -o -type l \) \! -name fred

  • If you have a file with spaces, control characters, leading hyphens or other nastiness and you want to delete it, here’s how find can help. Forget the filename, use the inumber instead. Say we have a file named “-rf .”, spaces and all. We wouldn’t dare attempt removing it the normal way for fear of issuing ‘rm -rf /’ at the command line.
$ echo jhjhg > "-rf /"
$ ls -la
total 4
-rw-r----- 1 mongoose staff 6 Nov 07 15:57 -rf /
drwxr-x--- 2 mongoose staff 512 Nov 07 15:57 .
drwxr-xr-x 3 mongoose bin 1024 Nov 07 15:53 ..

Find the I-number of the file using the -i flag in ls:

$ ls -lai .
total 4
18731 -rw-r----- 1 mongoose staff 6 Nov 07 15:57 -rf .
18730 drwxr-x--- 2 mongoose staff 512 Nov 07 15:57 .
1135 drwxr-xr-x 3 mongoose bin 1024 Nov 07 15:53 ..
^^^^^
There it is: I-node 18731. Now plug it into find and make find delete it:

$ find . -inum 18731 -ok rm {} \;
rm ./-rf . (?) y
$ ls -la
total 3
drwxr-x--- 2 mongoose staff 512 Nov 07 16:03 .
drwxr-xr-x 3 mongoose bin 1024 Nov 07 15:53

 

Limiting large requests in apache

Limiting large requests in apache

Apache has several directives that allow you to limit the size of a request, this can also be useful for mitigating the effects of a denial of service attack.A good place to start is the LimitRequestBody directive. This directive is set to unlimited by default. If you are allowing file uploads of no larger than 1MB, you could set this setting to something like:

LimitRequestBody 1048576

If you’re not allowing file uploads you can set it even smaller.

Some other directives to look at are LimitRequestFields, LimitRequestFieldSize and LimitRequestLine. These directives are set to a reasonable defaults for most servers, but you may want to tweak them to best fit your needs. See the documentation for more info.

Delay in SSH Login Prompt

Delay in SSH Login Prompt

You may came across this situation. At the time of logging in the shell prompt using SSH, 

               – Connection will be taking a fraction of second
               – After/While entering the Password its taking more time to provide the shell prompt.
             
To fix this issue:

This is related to DNS. We have to change dns related entries in ssh config file to reduce this delay.

Note :
     Be careful when doing this on production servers. 
     This activity may disconnect all the users from the system who are logged in to that machine using SSH. 

By default UseDNS option in this file is disable. We have to uncomment this option and then edit this entry to no. As below.. 

# vi /etc/ssh/sshd_config 

Just search for UseDNS.. 

                     #UseDNS yes  

Change that to, (Simply Uncomment it)

                      UseDNS no 

save and exit the file and then just reload ssh service to take effect what ever changes we did.. 

# service sshd reload
  
Now try to login and observe, delay will be reduced.

 

Linux Booting Process Sequence

Linux Booting Process Sequence

  1. When the computer is switched on, it automatically invokes BIOS [a ROM chip embedded in the motherboard].
  2. The BIOS will start the processor and perform a POST [power on self test] to check whether the connected device are ready to use and are working properly.
  3. Once the POST is completes BIOS will jump to a specified location in the RAM and check for the booting device. The boot sector is always the first sector of the hard disk and BIOS will load the MBR into the memory.
  4. Here the boot loader takes the control of the booting process.
  5. LILO or GRUB is the boot loaders commonly available. It will help the user to select various boot options.
  6. Depending on the boot option selected the kernel is loaded.
  7. After kernel is loaded the kernel will take the control of the booting process
  8. initrd will be loaded which contains drivers to detect hardware (Initialization of RAM Disk)
  9. Then it will initialize all the hardware including I/O processors etc.
  10. Kernel then mounts the root partition as read-only
  11. INIT is loaded.
  12. INIT will mount the root partition and other partitions as read/write and checks for file system errors.
  13. Sets the System Clock, hostname etc..
  14. Based on the Runlevel, it will load the services and runs the startup scripts (Network, cups, nfs, etc.)
  15. Finally it runs the rc.local script.
  16. Now the login prompt will appear.

Recover Bad Superblock in Linux Filesystem

Recover Bad Superblock in Linux Filesystem

If  you get a ¨Damaged Superblock¨ error message at filesystem (fsck) check in Linux Server, Usually fsck will not be able to repair the file system due to bad super block. In these situations, we can recover the damaged super block from the backup.

Solution:

There are backups of the Superblock located on several positions and we can restore them with a simple command in a Linux server

By default in Linux, the file system creates the backup of  super block in the following locations:

8193, 32768, 98304, 163840, 229376 and 294912.



Note: 8193 is only on older systems  in many cases. 32768 is the most current position for the first backup

When you get this “damaged superblock or bad superblock error” and if  you get a root-prompt in a recovery console, then issue the following command:

# e2fsck -b 32768 /dev/hda5


Now the System will check the filesystem with the information stored in that backup superblock and if the check was successful it will restore the backup to position 0.

If this is not successful, then try using the other copy of Superblock backup (Refer the backup location of superblock above)

Stop or Pause Process in Linux Server

Stop or Pause Process in Linux Server

ome times we may need to pause a particular process or service in Linux Servers.

We may need to stop a particular process without killing it for certain period of time and resume it again.

This can be done with KILL Command.

Most of us familiar with KILL comman. But this is the another feature of KILL command, which helps to achieve this:

To Stop a Process or Job:

#kill -STOP 21368 ( where 21368 is process id )

To Resume a Process or Job:

#kill -CONT 21368 ( where 21368 is process id )

Thats all.. Hope this is useful