Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • Options used with Bash if
  • Conclusion

Bash if Options

PreviousBash Split String by DelimiterNextBash If Statements for String Comparison

Last updated 1 year ago

According to Linux everything is considered as a file. We often want to know the status of the file like whether it exists or if it is readable. To do that, Bash provides us with plenty of "if" options. Unary expressions are commonly seen, which when used with the if statement, help examine the status of the file.

Prerequisites

Let us assume we have a non-empty file "sample.txt" present in the directory "atlas" and another file "alpha.txt" which doesn’t exist. Similarly, let’s assume an non-existing imaginary directory named "beta"

Options used with Bash if

The Bash if statement is employed for conditional branching, frequently catering to numerical or string comparisons. However, we have the option to use it with commands that return a status of zero when it succeeds and a non-zero status when it fails. Unary expressions help determine the status of a file. Some of the most frequently used flags in Bash scripts are -d, -e, -f, -s and -z.

-a option

It returns true if the file exists.

Syntax

[ -a FILE ]

Example

f [ -a sample.txt ]; then echo true; else echo false; fiif [ -a alpha.txt ]; then echo true; else echo false; fi

The -a flag checks if the specified file exists. If it does, a zero return status is generated and the if condition of the code is executed. In the second case, a non-zero return status results in the execution of the else part.

-b option

It returns true if the file exists and is a block special file. A block special file acts as a direct interface to a block device, which is a device that performs data I/O in units of blocks. These files are meant for logical volumes and disk devices on the Linux operating system.

Syntax

[ -b FILE ]

Example

if [ -b sample.txt ]; then echo true; else echo false; fiif [ -b alpha.txt ]; then echo true; else echo false; fiif [ -b /dev/sda1 ]; then echo true; else echo false; fi

The -b flag checks two things, one for the specified and the other if that file is a block special file. If both conditions are met, a zero return status gets generated triggering the if block of the code.

-c option

It returns true if the file exists and is a character special file. A character special file provides access to an input/output device. These files could be a file descriptor file, a terminal file, or a null file.

Syntax

[ -c FILE ]

Example

if [ -c sample.txt ]; then echo true; else echo false; fiif [ -c alpha.txt ]; then echo true; else echo false; fiif [ -c /dev/null ]; then echo true; else echo false; fi

The -c flag, too, looks for two things, the specified and that if it is a character special file. A return status of zero executes the if conditions of the code provided both conditions are met. Since the first two files are not character special, false gets printed. However, /dev/null is a character special file which is used to dump all the unwanted results to. Hence, the last case displays true on the terminal.

-d option

It returns true if the file exists and is a directory. As Linux treats everything as files, directories are folders. They can be distinguished from normal files using the ls command with -l flag.

Syntax

[ -d FILE ]

Example

ls -l sample.txtls -l atlasif [ -d sample.txt ]; then echo true; else echo false; fiif [ -d alpha.txt ]; then echo true; else echo false; fiif [ -d atlas ]; then echo true; else echo false; fiif [ -d beta ]; then echo true; else echo false; fi

The ls -l command will give a long list of the file. This will include all the necessary details like the permissions and size too. If we look closely we will see that if the result of the command begins with the letter "d", it will imply that it is a directory. For a file, it will begin with a "-". Just remember to execute this from the right place or give the full path. If we are inside the directory atlas and do a [ -d atlas], we are bound to get a false as atlas doesn’t exist inside the atlas directory.

Now that we have confirmed "atlas" is a directory and "sample.txt" is a regular text file, we can use the if statement with the "-d" flag to build the if conditions.

A true will be printed if the directory exists and otherwise it will display false as the output.

-e option

It returns true if the file exists.

Syntax

[ -e FILE ]

Example

if [ -e sample.txt ]; then echo true; else echo false; fiif [ -e alpha.txt ]; then echo true; else echo false; fiif [ -e atlas ]; then echo true; else echo false; fi

As we are now aware that Linux treats everything as files, we can use this option with regular files as well as directories. A true will be printed if the file or the directory exists and otherwise it will display false as the output.

-f option

It returns true if the file exists and is a regular file.

Syntax

[ -f FILE ]

Example

if [ -f sample.txt ]; then echo true; else echo false; fiif [ -f alpha.txt ]; then echo true; else echo false; fiif [ -f atlas ]; then echo true; else echo false; fi

Regular Linux files are files that may include text, data, information, piece of code or program instructions. This flag is widely used by Bash programmers to make the code flow in such a way that tasks get performed only if the file exists. Here, in our case, too, we are checking if the regular file exists and printing true if it does.

-g option

It returns true if the file exists and the SGID bit is set. SGID, standing for Set Group ID, is a powerful special permission we can enable for files, executables and directories in Linux. If set on a file, the file gets executed as the group that owns the file. If set on a directory, any files created in that directory have their group ownership set to that of the directory owner.

Syntax

[ -g FILE ]

Example

ls -l sample.txtchmod u-s,g+s sample.txtls -l sample.txtif [ -g sample.txt ]; then echo true; else echo false; fiif [ -g alpha.txt ]; then echo true; else echo false; fi

When the SGID bit is set on a file, the effective group is set to the group of the file. The process runs with the permissions of the members of the file’s group, instead of the permissions of the person who launches it.

We are setting the SGID bit using the chmod command. We can verify if it is set by ls -l command. We will see the presence of the SGID bit denoted by the letter “s” in the group permissions. Using the -g flag with the if condition will help us to construct if conditions around the SGID bit.

-h or -L option

It returns true if the file exists and is a symbolic link. A symbolic Linux link, also referred to as a symlink, points to another file or folder on the computer, or a connected file system. It can be simply considered as a shortcut.

Syntax

[ -h FILE ] [ -L FILE ]

Example

ln -s sample.txt sample__.txtif [ -h sample__.txt ]; then echo true; else echo false; fiif [ -L sample__.txt ]; then echo true; else echo false; fiif [ -h alpha.txt ]; then echo true; else echo false; fi

We are creating a symlink of sample.txt using the Linux ln command. We can now edit the soft link named sample__.txt and the sample.txt will get updated. Therefore, it acts as a shortcut to the file sample.txt. We can use the -h or the -L flag with if to check if the file has a symbolic link.

-k option

It returns true if the file exists and the sticky bit is set. It is a permission bit that when set on a file or a directory lets only the owner of the file or the directory or the root user to delete or rename the file. No other user is privileged to delete the file created by some other user.

Syntax

[ -k FILE ]

Example

ls -lh sample.txtchmod o+t sample.txtls -lh sample.txtif [ -k sample.txt ]; then echo true; else echo false; fiif [ -k alpha.txt ]; then echo true; else echo false; fi

We are using the chmod command to set the sticky bit of the file sample.txt. We can verify if it’s correctly set using the ls -lh command. When we set the sticky bit, the executable bit of the “other” set of file permissions is set to "t". Using the -k flag with the if condition will help us to construct if conditions around the sticky bit.

-r option

It returns true if the file exists and is readable.

Syntax

[ -r FILE ]

Example

ls -l sample.txtif [ -r sample.txt ]; then echo true; else echo false; fiif [ -r alpha.txt ]; then echo true; else echo false; fi

We can check the permissions on the file sample.txt using the ls -l command to verify if it has read permissions. We can make use of the -r flag with the if statement to have conditions based on the read permissions of the specified file.

-w option

It returns true if the file exists and is writeable.

Syntax

[ -w FILE ]

Example

ls -l sample.txtif [ -w sample.txt ]; then echo true; else echo false; fiif [ -w alpha.txt ]; then echo true; else echo false; fi

We can check the permissions on the file sample.txt using the ls -l command to verify if it has write permissions. We can rely on the -w flag with the if statement to develop conditions based on the write permissions of the specified file.

-x option

It returns true if the file exists and is executable.

Syntax

[ -x FILE ]

Example

ls -l sample.txtif [ -x sample.txt ]; then echo true; else echo false; fiif [ -x alpha.txt ]; then echo true; else echo false; fi

We can check the permissions on the file sample.txt using the ls -l command to verify if it has execute permissions. We can use the -x flag with the if statement to have conditions based on the execute permissions of the specified file.

-s option

It returns true if the file exists and has a size greater than zero.

Syntax

[ -s FILE ]

Example

ls -l sample.txtif [ -s sample.txt ]; then echo true; else echo false; fitouch anotherSample.txtls -l anotherSample.txtif [ -s anotherSample.txt ]; then echo true; else echo false; fi

In the first case we have a non-zero regular file sample.txt. When conditions are created with the if command using the -s flag, the code will flow through the if block and print true. In the latter case, we have created another regular file using the touch command. Since this is an empty file created with the touch command, its size will be zero. Hence, we get the result as false.

-u option

It returns true if the file exists and the SUID bit is set. SUID, abbreviated for Set User ID, executes commands and scripts with the permissions of the file owner, rather than the permissions of the person who launches it. SUID works only on files and not on directories.

Syntax

[ -u FILE ]

Example

ls -lu /bin/suif [ -u /bin/su ]; then echo true; else echo false; fils -lu sample.txtif [ -u sample.txt ]; then echo true; else echo false; fi

We can verify that the /bin/su file has the SUID set whereas sample.txt doesn’t by using the ls -lu command. When the SUID bit is set on a file, a "s" is visible representing the owner’s execute permission. Using the -u flag with the if statement helps to develop conditions and the flow of the program. If the SUID is set, a zero return status will be generated.

-O option

It returns true if the file exists and is owned by the effective user ID.

Syntax

[ -O FILE ]

Example

if [ -O sample.txt ]; then echo true; else echo false; fi

A UID is a user identifier. It is a unique number assigned to each user on the Linux system. We can use the if statement with the help of the -O flag to determine if the specific file is owned by the effective User ID.

-G option

It returns true if the file exists and is owned by the effective group ID.

Syntax

[ -G FILE ]

Example

if [ -G sample.txt ]; then echo true; else echo false; fi

Groups allow us to assign access privileges to multiple users. Users can be members of more than one group at a time. We can use the if statement with the help of the -G flag to determine if the specific file is owned by the specific Group ID.

-N option

It returns true if the file exists and has been modified since it was last read..

Syntax

[ -N FILE ]

Example

if [ -N sample.txt ]; then echo true; else echo false; fiecho "This way we can append a file without reading" >> sample.txtif [ -N sample.txt ]; then echo true; else echo false; fi

We are appending a line to the regular file sample.txt. This way we will be writing to it without reading it. Then we can club the if condition with the -N flag to have conditions if the return value is zero. Similarly, we can have alternate conditions if the return value is non-zero.

-z Option

The -z option is a string comparison operator which can be used to check empty strings and variables.

Syntax

[ -z String ]

Example

var1="Football"var2=""if [ -z "$var1" ]; then echo true; else echo false; fiif [ -z "$var2" ]; then echo true; else echo false; fi

The -z option is a string comparison operator used to check null strings in a Bash. It returns false whenever the string contains one or more characters. It will return true, if the string is empty.

We have two string variables, one is empty and the other one is not. In the if-else statement we perform the empty string check using the "-z" option within the square brackets. If the condition is satisfied and the string is empty, the first part executes, displaying true. However, if the string is non-empty, the else part executes and we get to see a false on the screen.

-n Option

Just like the previous option, we can also use the -n option.

Syntax

[ -n String ]

Example

var1="Football"var2=""if [ -n "$var1" ]; then echo false; else echo true; fiif [ -n "$var2" ]; then echo false; else echo true; fi

The "-n" option is a string comparison operator used to check null strings in a Bash. It returns true whenever the string contains one or more characters. It will return false, if the string is empty. It works exactly opposite to the -z option. If the comparison is done using -n, then for empty strings, it will go to the else part of the condition unlike the -z which goes to the if part. In other words we can say, -n flag performs not empty check.

Conclusion

  • Primaries with if statements, help examine the status of the file.

  • We have understood the use of available bash if flags with examples.

bash if option f
bash if option b
bash if option d
bash if option a
bash if option c
bash if option e
bash if option h and L
bash if option g
bash if option w
bash if option x
bash if option k
bash if option u
bash if option r
bash if option O
bash if option s
bash if option N
bash if option -G
bash if option n
bash if option z