Open In App

Shell Scripting – True Command

Last Updated : 27 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A shell provides an interface with the help of which users can interact with the system easily. To directly interact with a shell, we use an operating system. On a Unix-based operating system, every time we write a command using a terminal, we interact with the system. To interpret or analyze Unix commands, we use a shell. The main job of a shell is to take commands from the user and convert them into the kernel’s understandable form. To summarize this, we can see it as a medium between a user and the kernel system of an OS. The kernel is a computer program that is considered the main part of a computer’s operating system.

This article focuses upon the shell scripting- True command.

True command:

This command is referred to as “Do nothing, successfully”. This is because, on a UNIX-based operating system, the main purpose of this command is to return the successful exit status, which also means that it outputs nothing. It should be used if a part of a script always returns true. Its basic syntax is given below:

Syntax:

true [ arguments (optional) ]

It doesn’t matter whether you provide arguments, the true command always returns successfully.

Exit status:

zero (0)
It signifies success

Example :

In this script, we have used true command without any argument.

#!/bin/sh

# true command without any argument
true

Output:

Example:

In this script, we are using the true command with an argument.

#!/bin/sh

# true command using an argument
true GeekforGeeks.txt

Output:

Verify exit status:

We can verify the exit statement of the true command but this command has to be used along with another command. For this purpose, a special shell variable (?) is used to store the status of the true command. This mechanism is illustrated in the below script.  

Example:

#!/bin/sh

# Evaluates true then print the statement

true; echo “Status of the previous command is $?.”

Output:

If statement:

We can use the true command even in the if statement. This mechanism is illustrated in the below script.  

Example:

#!/bin/sh

if true; then echo “True Command”; else echo “Not A True Command”; fi

Output:

Example:

To execute the else part in the above script we can use Not (!) operator just before the true command.

#!/bin/sh

# Now it evaluate false 

if ! true; then echo “True Command”; else echo “Not A True Command”; fi

Output:

While statement:

We can use the true command in a while loop also. It is used to create infinite loops not only in shell scripting but also in other programming languages. 

Example:

#!/bin/sh

# while true: Print "Infinite loop"

while true; do 
  echo "Infinite loop"; 
done

Output:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads