DEV Community

Konstantinos Blatsoukas
Konstantinos Blatsoukas

Posted on

bash coursera: intro shell bash scripting

writting a simple script

#~/bin/bash
cd /etc
cat ./passwd
Enter fullscreen mode Exit fullscreen mode

give execution permissions

chmod +x test_script.sh
Enter fullscreen mode Exit fullscreen mode

pass data

#~/bin/bash
echo good morning $1 I hope you haveiong a great day
Enter fullscreen mode Exit fullscreen mode

Environmental variable

# craete an environmental variable
export USERNAME=kostas

#~/bin/bash
echo good morning $USERNAME I hope you haveiong a great day
Enter fullscreen mode Exit fullscreen mode

zip a file and move it to a new directory

#!/bin/bash

source=$1
dest=$2

tar -cvf backup.tar $source
gzip backup.tar
mv backup.tar.gz $dest
Enter fullscreen mode Exit fullscreen mode
mkdir audiofiles
cd audiofiles/
touch f1 f2 f3
cd ..
Enter fullscreen mode Exit fullscreen mode

READ and TEST commands, if conditionals

#!/bin/bash

# read user input
read -p "enter your desired username " username
echo you have chosen $username as your username
Enter fullscreen mode Exit fullscreen mode
$?
# 0 success, 1 and above error


#!/bin/bash
if [ 5 -gt 3 ]; then
    echo yes it is greater than 5
else
    echo no it is not
fi
Enter fullscreen mode Exit fullscreen mode

loops

#!/bin/bash

for name in natthew mark luke
do
    echo good morning $name
done
Enter fullscreen mode Exit fullscreen mode

loops using a bash command

#!/bin/bash
count=1
for file in `ls *.log`
do
    echo "log file number $count: $file"
    count=$((count+1))
done
Enter fullscreen mode Exit fullscreen mode

loops, the while case

#!/bin/bash
while true
do
    touch file-`date +%s`.txt
    sleep 3
done
Enter fullscreen mode Exit fullscreen mode

loops, the until case

#!/bin/bash
until `ssh 192.168.1.100`
do
    echo "still attemting..."
done
Enter fullscreen mode Exit fullscreen mode

functions in Bash

mkdir newdir
cd newdir
touch file1 file2 file3 file4
Enter fullscreen mode Exit fullscreen mode
#!/bin/bash

source=$1
dest=$2

function fileExists() {
    # check file existence
    if [ -f  $dest/backup3.tar.gz ]; then
        echo this file already exists
        exit
    fi
}


function compressDir() {
tar -cvf backup3.tar $source
gzip backup3.tar
mv backup3.tar.gz $dest
}

fileExists
compressDir
Enter fullscreen mode Exit fullscreen mode

Top comments (0)