Showing posts with label Bash. Show all posts
Showing posts with label Bash. Show all posts

Thursday, May 13, 2010

know the return value of a native (c) program in linux

Hi folks
use this command:
echo $?
to know the return value of a native program in Linux.
try it yourself:

scenario 1:
more 
echo $? #(watch the result, it will be 1, which means unsuccess)


scenario 2:
echo "hello world" > file
more file
echo $? #(watch the result, it will be 0, means success)

Saturday, April 17, 2010

Bash Script to run a sql file (Draft) - Part 1

#!/usr/bin/bash

# This script calls the Ad_1.sql script and spools the output with date stamp to a log file
# Update: You MUST add your environment variables one way or another, e.g. look below


export ORACLE_BASE=/oracle
export ORACLE_HOME=/oracle/OraHome_1
PATH=${PATH}:${ORACLE_HOME}/bin; export PATH
export LIBPATH=${LIBPATH}:${ORACLE_HOME}/lib32:${ORACLE_HOME}/lib


if [ ! -f lock ]; then

sqlplus -s user/password@sid << EOF
column dcol new_value mydate noprint
select sysdate dcol from dual;
spool log_ad_1_&mydate..log
@Ad_1.sql;
spool off
EOF

fi

where:

if [ ! -f lock ]: very useful statement, it checks whether a file named "lock" exists or not, if it doesn't exist, it will not execute the code block within.

sqlplus -s usr/passwod@sid: to run sqlplus commands as if I'm entering the commands manually, the -s flag lets sqlplus accept the standardin input until it finds the word "EOF"


Part 2 will be about adding the above script in crontab and executing it daily.

Wednesday, April 7, 2010

$@ is not "$@"

when you want to pass multiple parameters through you shell script, you use $@
ex:

#! /bin/sh
echo $@


and then execute this file:
./script1 hello world

the script will prints "Hello world"

But be ware, $@ is not "$@" !!

The story is, I wrote some Java file that accepts 1 argument from the command line, such like this:

public class SayHello{
public static void main(String[] args){
if (args.length != 1){
System.out.println("Usage: SayHello ");
System.exit(-1);
}
// do other staff here
}
}


I have wrapped this program in a shell file "sayHello.sh":
#! /bin/sh
java SayHello $@


But the result was unexpected, as when I run with this command:
./sayHello.sh "Mohammed Hewedy"

I got
Usage: SayHello

I found the problem in the shell file, that I should use "$@" instead of $@
So, the script should be:
#! /bin/sh
java SayHello "$@"

Thursday, March 18, 2010

pass entire parameters in shell scripts

example bash file:

save the following in a file called print.sh
#!/bin/bash
echo "$@"
and then :
chmod +x print.sh
./print.sh hello world
Note that, all the parameters you pass to print.sh will be passed to echo, this because of "$@"

Monday, March 8, 2010

Bash Switch statement

If you have some server that need some script that control it (such as scripts found in /etc/init.d), here's that script:

open a text file and put the following in :

#! /bin/sh
case "$1" in
start)
echo "START";
## command to start your server
;;
stop)
echo "STOP";
## command to stop your server
;;
*)
echo "Usage : $0 {start|stop}"
exit -1;
esac


Then of course
chomd +x <file_name>


And you're done.

Thursday, February 4, 2010

How to change your current username on Ubuntu Linux

Beware, this action is VERY dangerous and might ruin some of your running applications, I tried it first on a virtual machine and then my actual machine and it messed up 2 or 3 apps only, I was lucky as these were easy to fix, here we go (Read the instructions below carefully):

usermod -l newname -m -d /home/newname oldname

Please note that you MUST:
  1. be logged out from the user that you will change the "username" for 
  2. and make sure all that user's applications are closed.
Thanks go to prshah for his post here

Tuesday, February 2, 2010

Bash script to monitor background processes

while [ 1 ]; do ps -ef | grep bzip2; echo "============================================="; sleep 5; done;

where:

bzip2: is the process name or part of the process name

Press Ctrl+c at any time to cancel the process

Sunday, January 31, 2010

How to split a text file in Ubuntu

Simple! Just use the "split" command, if no arguments are specified, it will split the text file to files each containing 1,000 lines of text.

Monday, December 28, 2009

A complete invisibility - anonymity - solution for Ubuntu

Based on some online articles and my previous posts, I created the following script which does the following:
  1. Generates and assigns a random MAC address to my wired card (eth0) and wireless card (wlan0) using the macchanger software described here
  2. Generates and assigns a new hostname to my OS
  3. Applies the new changes in my "/etc/hosts" file
  4. Runs on every startup
IMPORTANT: You MUST have your "127.0.0.1" and "127.0.1.1" entries as the last two lines if you need to run this script EXACTLY as it is. If you don't want this, you can simply change the "sed" part.

Here is the script:

!/bin/bash

#random_computer_name & random MAC address for both eth0 and wlan0

sudo macchanger -A eth0 #random mac for eth0
sudo macchanger -A wlan0 #random mac for wlan0

sed -i 1,10d /etc/hostname

function randnum
{
number=$[ ( $RANDOM % 15 ) + 8 ]
}

randnum

function randpass
{
newhostname=`
}

randpass

(echo '0a'; echo $newhostname; echo '.'; echo 'wq') | ed -s /etc/hostname

/bin/hostname $newhostname

sed -i '$d' /etc/hosts # deletes the last two lines in /etc/hosts
sed -i '$d' /etc/hosts

echo -e "127.0.0.1    $newhostname localhost\n127.0.1.1    $newhostname" >>/etc/hosts


You can add the above file to your startup following the steps in this link

Appreciate any feedback. Note: I'm already working with this script on my laptop and it's working fine till now, I just had about 10 seconds idle at the startup screen.

Update: That delay happened only after the first startup and then disappeared

Delete the last line in a text file using sed

sed -i '$d' hobba

-i: to change the file itself, not copy contents to another file or something
$d: delete the last line
hobba: the file name

Insert a "new line" character in a text file using Bash

"echo -e "192.168.100.100\n192.168" >> hobba"

 The '-e' option does the magic, as it allows escape characters to be printed

Source

How to delete certain lines of text from a file in Bash using sed

"sed -i 1,+2d file_name"

deletes starting from line '1' and the next '2' lines, i.e. deletes the first 3 lines

Monday, December 14, 2009

How To Find and Delete Files Not Matching MULTIPLE criteria using bash in AIX

"find . ! -name "*.bz2" ! -name "ESPRD*" | xargs rm"

 The above command finds all files in the "current" directory excluding those with "*.bz2" extension and those which start with "ESPRD*" and then deletes them all.

Wednesday, December 2, 2009

Bash Script To Find and Delete All Files Except Some When the filesystem reaches a specific size

#!/bin/sh

# This script checks if the /siebel filesystem reaches the warning limit of free space
# And then delete the old logs except those of last 12 hours

warninglimit=1572864    # This number is in KB, it's equal to 1.5 GB,
                        # KB is used to avoid floating point numbers

filesystem="/siebel"   # The filesystem to be monitored

size=`df -k $filesystem|grep $filesystem|awk '{ print $3; }'`   # Extract size of /siebel Filesystem in KB

if [ $size -le $warninglimit ]  # If fs size is less than warning lim.
    then
              find /siebel/siebsrvr/enterprises/ESPRD/$HOSTNAME/log -cmin +720 \( ! -name "ESPRD*" \) | xargs rm  # Delete log files that are more than 12 hours old from now (except those starting with "ESPRD")
fi

Credit goes to Osama Magdy for the above script.

"Find All EXCEPT" using bash script

find . \( ! -name "hobba*" \)

The above command invokes the "find" command asking it to search in the current directory (".") and return all files except those starting with the string "hobba". Note: Take care of the spaces as one more or less space character can ruin the whole script.

The above script is taken from a bash script written by Osama Magdy that deletes all files in a certain directory except one.

Thursday, August 27, 2009

Searching for a string inside multiple files and output the name of the files containing that string

find . -name "*" | grep -i ecomm | xargs ls -las | grep "Aug 27" | awk '{print $10}' | xargs grep -i string_to_search_for | grep -i "\.log" | awk '{print $1}'

where:

"ecomm" is part of the name of the file in which we should search for the string
"Aug 27" is the date the files were last modified
"$10" is the last column resulting from the "ls -las" command, this is the column containing the filename (the string is not searched for yet)
"string_to_search_for" the name is obvious :)
"\.log" all the files end with ".log"
"$1" is the filename containing the string

There are still two problems left (I don't have time right now to solve them):
  1. All the filenames end with the ":" character, it needs to be omitted
  2. Filenames are redundant, i.e. each file is repeated many times
Update: Problem number 2 solved using the "sort" and "uniq" commands which sort the results and then omit the repeated results, here is an example:

find . -name "*" | grep -i ecomm | xargs ls -las | grep "Aug 31" | awk '{print $10}' | xargs grep -i mbassiouny | grep -i "\.log" | awk '{print $1}' | sort | uniq

Monday, August 24, 2009

Count number of lines in a text file

wc -l file_name

Extract Lines From a Text File

"sed -n 2,4p file_name"

extracts lines from 2 to 4 from that file

Tuesday, August 18, 2009

How To Write Infinite Loop in Bash

This is how you create an infinite loop in bash to run a piece of code infinitely at defined intervals.


#!/bin/bash
while [ 1 ]
do
# Your code goes here

# Modify sleep time (in seconds) as needed below
sleep 2
done

I needed such code to monitor the size of a file every 2 seconds.

Source: http://blog.taragana.com/index.php/archive/how-to-write-infinite-loop-in-bash/