Symbols and Operators in shell script

Last updated at: September 09, 2024
Written by: Abdul

Shell scripting relies on a variety of symbols and operators that control the flow of commands, handle input/output redirection, and perform logical operations. Understanding these symbols is crucial for both beginners and advanced users to automate tasks effectively. Symbols like -d and -f check for directories and files, while comparison operators such as -eq, -lt, and -gt help manage conditional logic. Redirection symbols like >, >>, and | allow you to control how data flows between commands and files, offering powerful ways to process and manipulate data.

In addition, shell scripts use special symbols such as $$ to access the current process ID and $? to check the status of the last executed command, aiding in error handling and debugging. Logical operators like && and || are essential for chaining commands based on success or failure. By mastering these common shell script symbols and their use cases, users can build efficient and flexible scripts to automate a wide range of tasks, from system administration to software deployment.

SymbolDescription
-dChecks if a directory exists
if [ -d /path/to/directory ]; then 
  echo "Directory exists"
fi
-fChecks if a file exists
if [ -f /path/to/file ]; then 
    echo "File exists"
 fi
-eq, -ne, -lt, -le, -gt, -geNumerical comparison operators: -eq (equal), -ne (not equal), -lt (less than), -le (less than or equal), -gt (greater than), -ge (greater than or equal)
if [ "$a" -eq "$b" ]; then 
  echo "Equal"
fi
$?Returns the exit status of the last command (0 for success, non-zero for failure)
command; echo $?
$#Returns the number of arguments passed to a script
echo "Number of arguments: $#"
$$Returns the process ID of the current shell
echo "PID of this shell: $$"
$!Returns the process ID of the last background process
sleep 10 &; echo $!
&&Logical AND: Executes the next command only if the previous one was successful
command1 && command2
||Logical OR: Executes the next command only if the previous one failed
command1 || command2
>Redirects output to a file (overwrites)
command > output.txt
>>Appends output to a file
command >> output.txt
<Redirects input from a file
command < input.txt
<<Here document: Reads input from the current script until a given delimiter
cat << EOF ... EOF
|Pipes the output of one command to another command
command1 | command2
*Matches all files or acts as a wildcard in patterns
ls *
?Matches any single character in a filename
ls file?.txt
;Separates multiple commands on a single line
command1; command2
#Marks a comment line
# This is a comment