Programming Tutorials

test command or [ expr ] in Linux Shell Script

By: Dorris in Linux Tutorials on 2011-01-15  

In Linux shell scripting, the test command or [ expr ] is used to evaluate a condition and return a Boolean value. It is typically used in conditional statements, loops, and other control structures.

The test command or [ expr ] can be used to perform a wide range of tests, including:

  • File tests: to check if a file exists, if it is readable, writable, executable, or if it is a symbolic link, a directory, or a regular file.
  • String tests: to check if a string is empty or not, if it contains a certain substring, if it is of a certain length, or if it matches a pattern using regular expressions.
  • Numeric tests: to check if a number is equal to, greater than, or less than another number.

The test command or [ expr ] is followed by a list of arguments that specify the test to be performed. The syntax of the test command or [ expr ] is as follows:

test expression

or

[ expression ]

The expression can be a combination of variables, operators, and literals, and it must be enclosed in double quotes if it contains spaces or special characters.

For example, to test if a file exists, you can use the following command:

if [ -e /path/to/file ]; then
  echo "File exists"
else
  echo "File does not exist"
fi

In this example, the -e option tests if the file exists, and the if statement checks the Boolean value returned by the test command or [ expr ] and executes the corresponding branch of code.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Linux )

Latest Articles (in Linux)