Remove file extensions:
bash$ echo $filename | cut -d'.' -f1
This will give you everything up until the first period. For the second period, use -f2 as an option, etc.
Renaming the file extension from .asp to .html in the entire directory:
bash$ for f in *.asp; do mv $f `basename $f .asp`.html; done;
Renaming the file extension from .asp to .html inside all the files within the director:
bash$ for f in *.html; do sed -f replace.sed -i $f; done;
where replace.sed contains:
1,$s:\.asp:.html:g
Tar a directory into .tar.gz file:
bash$ tar -czvf filename.tar.gz dirname
Untar .tar.gz file:
bash$ tar -xzvf filename.tar.gz -C dir_destination
Exit status:
echo hello
echo $? # Exit status 0 returned because command executed successfully.
lskdf # Unrecognized command.
echo $? # Non-zero exit status returned because command failed to execute.
echo exit 113 # Will return 113 to shell.
# To verify this, type "echo $?" after script terminates.
Split a string with delimiter:
#!/bin/bash
line=’this “is” a command;this “is” a pattern’
COMMAND=${line%;*}
PATTERN=${line#*;}
echo $COMMAND
echo $PATTERN
The output would be:
this “is” a command
this “is” a pattern
Find zero length file:
bash$ find <DIR> -type f -size 0 -print
Running remote command using SSH:
bash$ ssh USERNAME@HOSTNAME 'COMMAND'
For example, check system status remotely on hostname www.example.com:
bash$ ssh root@www.example.com 'top -b -n 1 | head -n 8'
Date and Time format:
bash$ DATE=$(date +"%m-%d-%Y")
bash$ TIME=$(date +"%H:%M:%S")
bash$ echo ${DATE}_${TIME}
11-17-2010_12:15:37
Create large file size for testing:
This command will create a 10GB file called testfile.out
bash$ dd if=/dev/zero of=testfile.out bs=1MB count=10000
Find zombie process:
bash$ ps -A -ostat,ppid,pid,cmd | grep -e '^[Zz]'
Kill zombie process:
bash$ kill -HUP `ps -A -ostat,ppid,pid,cmd | grep -e '^[Zz]' | awk '{print $2}'`
Prompt user for input:
echo -ne "\nWould you like to continue (y/n): "
read CONT
if [ "${CONT}" == "n" ] ; then
exit 0;
fi
Read command line arguments:
bash$ commandline.sh arg1 arg2 arg3
$1 = argument 1
$2 = argument 2
$@ = all arguments
$# = number of arguments
MORE TO COME......