Note: *Check out these useful books! As an Amazon Associate I earn from qualifying purchases.
Bash (Bourne Again Shell) is a command-line interpreter and scripting language commonly used on Unix/Linux systems. It provides a user interface for running commands and automating tasks through shell scripts.
In Bash, variables are declared without spaces around the equals sign. For example:name=JohnTo access the variable, use $name.
name=John
$name
You can use the read command. Example:read nameecho "Hello, $name"
read
read nameecho "Hello, $name"
Positional parameters represent command-line arguments passed to a script.For example, $1, $2, and so on. $0 refers to the script name.
$1
$2
$0
Example:if [ $a -gt $b ]; then echo "a is greater"else echo "b is greater"fi
if [ $a -gt $b ]; then echo "a is greater"else echo "b is greater"fi
You can use a for loop:for i in 1 2 3; do echo $idone
for
for i in 1 2 3; do echo $idone
== is used for string comparison, while -eq is used for numeric comparison.
==
-eq
Use > for overwriting a file and >> for appending. Example:echo "Hello" > file.txt
>
>>
echo "Hello" > file.txt
Use a conditional test:if [ -f filename ]; then echo "File exists"fi
if [ -f filename ]; then echo "File exists"fi
$? stores the exit status of the last executed command. 0 means success, and any non-zero value indicates an error.
$?
0
my_function() { echo "Hello from function"}
Use the command:chmod +x script.sh
chmod +x script.sh
set -e makes the script exit immediately if any command fails, helping prevent execution of dependent commands after an error.
set -e
You can use bash -x script.sh or add set -x within the script to trace command execution.
bash -x script.sh
set -x
Use ${#var}. Example:len=${#name}
${#var}
len=${#name}
The trap command catches signals and executes custom commands before the script exits. Example:trap echo Exiting; rm temp.txt EXIT
trap
trap echo Exiting; rm temp.txt EXIT
Arguments are accessed as $1, $2, etc., inside the function.my_func() { echo $1 $2; }my_func Hello World
my_func() { echo $1 $2; }my_func Hello World
Append an ampersand (&) to the command. Example:./script.sh &
./script.sh &
Bash supports indexed arrays:arr=(apple banana cherry)Access with ${arr[0]}.
arr=(apple banana cherry)
${arr[0]}
Example:if [ -z "$var" ]; then echo "Empty"fi
if [ -z "$var" ]; then echo "Empty"fi