|intro to BASH scripting



BASH (Bourne again shell)

→ A Bash script is a plain text file which contains a series of commands. These commands are a mixture of commands we would normally type ourselves on the command line (such as ls or cp for example) and commands we could type on the command line but generally wouldn't.



Commands

- to get to know what SHELL you’re using type:


let’s automate things

first create a .SH file:


the nano text editor should be opened up.

then let’s automate an echo:

to save the file: ctrl + x then askes you if you wanna save it so ender y and then askes you about the file name, click enter .

in order to run the BASH script you just wrote:


create delay between codes

open up the BASH script you just wrote and let’s make a conversation:

- to edit the file:

to save it →

  1. ctrl + x

  2. y

  3. enter

#!/bin/bash → this means we want to use the BASH SHELL, so always declare it on the top



change permission to run

if you type ls -l you’ll see the files with their permissions which in this case our BASH script doesn’t have an execute permission, so if you try to run it using this command ./automate1.sh, it doesn’t allow you.

for changing or giving a new permission use this command → (x = execute)

to remove the permission →


setting variables & inputs

to set a variable →

to get an input →


another way to set variables is using positional parameter →


we used $1 because $name is the first parameter, we can also add more


let’s run it but give it a parameter →


put command outputs into variables

let’s put the output of “whoami” into a variable and return it →


Create your own variable into system

→ now we can use our variable into our bash script, however, in order to make it permanent you need to modify the .bashrc file and put export UNIX=”the ….” in the bottom of the file.


Do math

to get a random number between 0-9 →


Conditionals

case →


loops

let’s ping some websites automatically →

-q = make it quite

-c 2 = 2 pings

-w 1 = wait 1 second

> dev/null = don’t want the responses


check an address until it’s up →



  • Source: ryanstutorials | Networkchuck
  • Wrote: November 30, 2022 | Azar 9, 1401
  • Updated:
  • Posted: December 16, 2022 | Azar 25, 1401