Page cover
githubEdit

Bash

From Ahmed Farag

To write bash code start with #!/bin/bash → because system show this file as ASCII text

echo or printf we use it for printing

BASH → use interpreter bash (print correct line then print the error is is found)



implementation

to implement variable

#!/bin/bash
# no spaces before and after equal -> before space execute as a command 

name="irix"
echo $name  # to print the value for variable
printf $name

the difference between echo,printf :

  • printf → print text in the same line

  • echo → print text in new line (to print text in the same line we use option -n )

To save the value for execution command we use -> `var=`ls

mathematical operation

  • $(())

    with all operation except postfix and prefix ((x++))

  • let

  • expr



input

to take input from user we use

read → we have more option for it like :

  • -s —> make input non visible (like password in linux) read -s $name

  • -p —> print text (like input in python) read -p "what is your name: " $name

  • array

    we use set to implement array

    implement array , we use ${} to print array

  • connection

    no concatenation in bash

execution

to execute command on system $()



condition

  • if condition

    The -f checked if the file existed.

    The -w checked if the file was writable, without write permissions we wouldn't be able to output our text into the file.

    image.png
  • Test condition

    just check on two variable like ? in cpp



loop

echo {1..6} → regular expiration (out put from 1 to 6)

  • For loop

    • for $variable_name in 1 2 3 4

    • do

    • expiration

    • done

  • While loop

    • while [condition]

    • do

    • expiration

    • done

To Debug your code we use :



String

compare two strings

To count chars in word

Split → IFS

Substring ${var:start:end}



Function

function_name(){commands;}

or

function_name(){

commands

}

Notes

exit 0 → to exit from code

Last updated