OSCP
Search…
Bash Scripting
https://sushant747.gitbooks.io/total-oscp-guide/basics_of_linux.html

Iterate over a file

This script will iterate over a file and echo out every single line:
1
#!/bin/bash
2
3
for line in $(cat file.txt);do
4
echo $line
5
done
Copied!
Another way of writing is this:
1
#!/bin/bash
2
3
while read p; do
4
echo $p
5
done <file.txt
Copied!

For-loops

1
#!/bin/bash
2
3
for ((i = 0; i < 10; i++)); do
4
echo $i
5
done
Copied!
Another way to write this is by using the program seq. Seq is pretty much like range() in python. So it can be used like this:
1
#!/bin/bash
2
3
for x in `seq 1 100`; do
4
echo $x
5
done
Copied!

If statement

$1 here represent the first argument.
1
2
if [ "$1" == "" ]; then
3
echo "This happens"
4
fi
Copied!

If/Else

1
#!/bin/bash
2
3
if [ "$1" == "" ]; then
4
echo "This happens"
5
else
6
echo "Something else happens"
7
fi
Copied!

Command line arguments

Command line arguments are represented like this
1
#!/bin/bash
2
3
$1
Copied!
This is the first command line argument.

Daemonize an execution

If you do a ping-sweep with host the command will take about a second to complete. And if you run that against 255 hosts I will take a long time to complete. To avoid this we can just deamonize every execution to make it faster. We use the & to daemonize it.
1
#!/bin/bash
2
3
for ip in $(cat ips.txt); do
4
ping -c 1 $ip &
5
done
Copied!

Use the output of command

It has happened to me several times that I want to input the output of a command into a new command, for example:
I search for a file, find three, and take the last line, which is a path. Now I want to cat that path:
1
#!/bin/bash
2
3
locate 646.c | tail -n 1
Copied!
This can be done like this:
1
#!/bin/bash
2
3
cat $(locate 646.c | tail -n 1)
Copied!
Last modified 1yr ago