M y B l o g

Some notes when using Bash Script.

This article is designed to keep track of some of the most commonly used commands at work.

◉ Arguments:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Example: ./test.sh arg1 arg2 arg3
# Print number of arguments, return a number
# Output: 3
echo $#

# Print 1st argument
# Output: arg1
echo $1

# Print all arguments
# Output: arg1 arg2 arg3
echo $@

◉ Input and file:

1
2
3
4
5
6
7
8
# Read input
read -p "Enter input:" var
echo $var

# Read file
while IFS= read -r line; do
    echo "Text read from file: $line"
done < my_filename.txt

◉ Increment (or decrement) a numeric:

1
2
3
4
5
6
7
8
# Increment a numeric
var=$((var+1))
((var=var+1))
((var+=1))
((var++))
let "var=var+1"
let "var+=1"
let "var++"

◉ Array:

1
2
3
4
5
6
7
8
9
10
# Create an array
myArray=("A" "B" "C" "D")
var=0

# Loop through array elements
for element in "${myArray[@]}"
do
    # Print each element
    echo "${myArray[var]}"
    echo $element
done

◉ Print something:

1
2
3
4
5
6
# Print literal \n
echo -e "Hello,\nWorld!"
printf "Hello,\nWorld!"

read -n 1 -s -r -p "Press any key to continue..."
read -p "Press Enter to continue..."

◉ "if" condition:

Syntax:

1
2
3
4
5
6
7
8
9
if [[ condition ]];
then
    # Commands;
else if [[ other condition ]];
then
    # Commands;
else
    # Commands;
fi

Compare Numbers:

Syntax Explanation
num1 -eq num2 check if 1st number is equal to 2nd number
num1 -ge num2 checks if 1st number is greater than or equal to 2nd number
num1 -gt num2 checks if 1st number is greater than 2nd number
num1 -le num2 checks if 1st number is less than or equal to 2nd number
num1 -lt num2 checks if 1st number is less than 2nd number
num1 -ne num2 checks if 1st number is not equal to 2nd number

Compare Strings:

Syntax Explanation
str1 = str2 checks if str1 is the same as string str2
str1 != str2 checks if str1 is not the same as str2
str1 < str2 checks if str1 is less than str2
str1 > str2 checks if str1 is greater than str2
-n str1 checks if str1 has a length greater than zero
-z str1 checks if str1 has a length of zero