ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

Shell Script Chapter 4: Special Operators

prodevelopertutorial February 12, 2019

In this chapter we shall know about some special operators, which makes shell script powerful while writing and executing the scripts.

4.1. Redirectors
4.2. Pipes
4.3. exit status
4.4. Shell Special Variables
4.5. eval command
4.6. sleep command
4.7. trap command

4.1. Redirectors

Usually we give input to the script from standard input [STDIN] and get the output in standard output [STDOUT] i.e display. And write the error in standard error[STDERR].
By default, keyboard is the standard input, display is the standard output and standard error.

But with the help of redirection operator “>” it is possible to redirect the output to a file or any other location.
Linux assigns a specific number called as file descriptor number as shown below:

0 for standard input
1 for standard output
2 for standard error

4.1.1 Some of the example below:

> Redirect to standard output
2> Redirect to standard error
2>&1 Redirect standard error to standard output
< Redirect to standard input
| Pipe, used to give output of one command to input to another.
>> Append to standard output

Example 1: The “>” operator

ls > ls_list.txt

The above command will redirect the output to “ls_list.txt”

Example 2: The “2>” operator

cdls 2> err.out

The above command will redirect the STDERR to “err.out”

Example 3: The “2>&1” operator

ls 2>&1 > hello.out

The above command will redirect the STDERR and STDOUT to “hello.out”

4.2 Pipes

Pipes are used to give the output of one command to the input to another command.

Example:

ls | wc -l

Output:

24

Here ls will give its output to “wc -l”. “wc” is word count. Hence it will count the number of files present in the folder.

4.3 exit status

Any shell program after execution, it will return it’s status to the system. With the help of return status, we can know if the script is executed successfully or not. Exit status of “0” will be returned upon successful completion. a non zero status will be returned if it fails. “$?” is used to get the exit status of the last command executed.

There are some pre determined reserved meanings, programmers are recommended not to use those values in their script.

1 – general errors
2 – Misuse of shell built-ins. Usually when there is a permission problem.
126 – Command invoked cannot execute. Usually when there is a permission problem.
127 – “command not found”. Possible a typo
128 – Invalid argument to exit. Example when you return “exit 34.54”. Error because exit takes only integer args in the range 0 – 255
128+n – Fatal error signal “n”. Example kill -9 $PPID. $? returns 137 (128 + 9).
130 – Script terminated by Control-C
255\* – Exit status out of range

4.4. Shell Special Variables

In the previous chapters we have used special operators like “$0” “$1” “$?”, which did not make much sense then. In this section we shall understand in detail about these variables.

$0 It holds the name of the script currently executing
$n “n” is a place holder for integer variable. If the input has 4 arguments, then all the 4 argument can be accessed by: $1 for first argument, $2 for second argument, $3 for argument etc.
$# It outputs the number of arguments sent to the script.
$? Gives the exit status of the last command executed.
$$ Returns the process number of the current shell
$! Process number of the last background running process.

There are 2 other special variables that are tricky to understand. They are:
$*
$@

Their behaviour changes when they are used with and without quotes.

1. With quotes:

“$*”
“$@”
and call it with:

./myScript.sh “a a” “b b” “c c”

it’s equivalent to:

“$*” will return “a a b b c c”
“$@” will return “a a” “b b” “c c”

2. When used without quotes, they’re the same:

$*
$@

would be equivalent to:

$* “a” “a” “b” “b” “c” “c”
$@ “a” “a” “b” “b” “c” “c”

Example:

#!/bin/bash

echo "The script name is $0"
echo "The first argument is $1"
echo "The second argument is $2"
echo "The third argument is $3"
echo "Total number of variables entered $#"
echo "All the entered variables $*"
echo "All the entered variables $@"
echo "The process number of the current shell is $$"

Output:

sh 20_example.sh 123 345
The script name is 20_example.sh
The first argument is 123
The second argument is 345
The third argument is
Total number of variables entered 2
All the entered variables 123 345
All the entered variables 123 345
The process number of the current shell is 10774

4.5. eval command

eval command is used to execute arguments as a shell command.

For example:

a=5
b=’$a’
eval echo $b

Output:

5

In the above example, we expect the output to be “5” but instead it returns “$a”. Because the shell will take it as a string variable. To get the correct value use “eval” command.

a=5
b=’$a’
echo $b

Output:
$a

4.6. sleep command

sleep command is used to pause the execution for the given number of seconds.

4.7. trap command

trap command is used to catch a signal during the script execution.

Example:

Create a file 21_trap.sh

#!/bin/bash

#set a trap for exit with 0, when the script will exit with 0, this will be executed
trap 'echo "Exit 0 signal detected..."' 0

echo "Sample text"

exit 0

Output:

Sample text
Exit 0 signal detected...

 

 

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT