- Echo statements always require double quotes in bash script.
- use ${variable} to reference the variable.
Sample script 1:
#!/bin/bash echo "hi there" echo "my current directory is " pwd echo "contents of the directory is" ls
#!/bin/bash a=3 b=4 c= $a + $b echo "$c"
output:
3+4
#!/bin/bash word="fun" echo "linux is $word" echo "bash is $word" echo "Test cricket is $word"
Output:
linux is fun
bash is fun
Test cricket is fun
#!/bin/bash echo "file contents are $(ls)" echo "present directory is $(pwd)}" now=$(date) echo "system date and time is $now" name=$(whoami) # or use $(USER) echo "my name is $name and using this machine on $now"
-
multiplication is calculated by
expr 100 /* 4, addition is calculated byexpr 2 + 3, division is calculated byexpr 2 / 3.
#!/bin/bash var=33 total= expr $var + 4 echo "total is $total"
Here are some ways to add two numbers and store the result in a variable in Bash:
Using the let command.
Code
num1=10 num2=20 let sum=$num1+$num2 echo "The sum is $sum"
This will print the following output:
Code
The sum is 30
num1=10 num2=20 sum=$(expr $num1 + $num2) echo "The sum is $sum"
This will also print the following output:
Code
The sum is 30
num1=10 num2=20 sum=$(echo $num1 + $num2 | bc) echo "The sum is $sum"
This will also print the following output:
The sum is 30