bash script

Some often used bash scripts techniques. Also an example script I wrote for my network homework which does some auto download testing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# !/bin/bash

### to assign variable: (notice no space in between)
vname1='str'
vname2=1

### use assigned variable:
echo $vname1

### simple loop
while(( $int<=100))
do
echo $int
# do something here
let "int++"
done

Suppose we name out script as myscript.sh, to run it, fisrt we givie it permission:

1
2
$ chmod 755 myscript.sh
$ ./myscript.sh

Some some techniques (more will be added):

1
2
3
4
5
6
7
8
9
### string quotes
NAME="John"
echo "Hi $NAME" #=> Hi John
echo 'Hi $NAME' #=> Hi $NAME

### Conditional execution:
git commit; git push
git commit && git push
git commit || echo "Commit failed"

Now an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# !/bin/bash
echo start creating files

### create 25 4kb files
int=1
while(( $int<=25 ))
do
echo $int
dd if=/dev/urandom of=test/t$int bs=1000 count=4
let "int++"
done

### create 25 60kb files
int=1
while(( $int<=25 ))
do
echo $int
dd if=/dev/urandom of=test/tt$int bs=1000 count=60
let "int++"
done

echo done creating files

At the end, a very good reference link: https://devhints.io/bash