Sh Command


Sh Command; it is the program or command interpreter users interact with in a terminal emulation window. Sh is a standard command language interpreter of Unix based operating system and added in Linux also.

Bash is the running in all the Linux operating system, which is stands for Bourne Again Shell. The Bourne Shell, the C-Shell and the TC-Shell these are some other shell programs.

All sh configuration files stored in “/bin/sh” that is either the Bourne shell, or a symbolic link OR hard link to a compatible shell.

In this article will describing about some of sh command and its uses in Unix or Linux operating systems, you may look here for Linux cp command..

Do you want to know more about “Powershell Commands”

Sh Syntax

sh [-testfile] [arg]


A command is a sequence of words separated by blanks or space.

First word Name of the command to be executed
Second word Remaining words are passed as arguments to the invoked command
“I” It’s Pipeline symbol used by sequence of one or more commands separated by a vertical bar
;“, “&”, “&&” or “|| A list is a sequence of one or more pipelines
“#” The beginning of a word starts a comment

The below words are recognized only as first word of a command, and if not enclosed in quotes:

If, Then, else, elif, fi, case, in, esac, for, while, until, do, done, {,}

Command Substitution

It allows the output of a command to replace the command itself. Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted.

To run a shell command and store its output to a variable or display back using “echo command”


`command-name` (OR) $(command-name)

For Example: Check the Date and Time

 echo ”Today is $ (date)”

Command Substitution in an echo command

echo  ”Text $ (command-name)”

Command Substitution and Shell variables

To store command output to shell variable,


To store system’s host name to a variable called SERVERNAME:


echo “Running command @ $SERVERNAME….”

To store current date and time to a variable called NOW:


echo “$NOW”

To store current working directory name to a variable called CWD:


cd /path/some/where/else

echo “Current dir $(pwd) and now go to old dir”

cd $CWD

Command Substitution and Shell loops

for f in $(ls /etc/.yum)


   echo “$f”


Parameter Substitution

The ‘$’ character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name & symbol are optional. Positional parameters may be assigned values by “set”.

Variables may be set in the form “name=value [ name=value ] …”.

${parameter} A parameter is a sequence of letters, digits or underscores, a digit, or any of the characters * @# ? – $ !. The value, if any, of the parameter is substituted. The  { – required only when parameter is followed by a letter, digit, or underscore that is not to be interpreted as part of its name.  
parameter is * or @ All the positional parameters, starting with $1, are substituted separated by spaces
$0 $0 is set from argument zero when the shell is invoked.
${parameter:-word} If parameter is set and not empty then substitute its value; otherwise substitute word.
${parameter:=word} If parameter is not set and not empty then set it to word;
${parameter:+word} If parameter is set and not empty, then substitute word; otherwise substitute nothing.

Note:  In above Parameter is omitted, the substitutions are only executed if the parameter is set, even if it is empty and word is not evaluated unless it is to be used as the substituted string.

Example:  “echo ${d-`cd`}” will only execute cd if d is unset.

Some list of parameters is automatically set by the Shell in below.

# The number of positional parameters, in decimal.
Options supplied to the shell on invocation or by set.
? The value returned by the last executed command, in decimal.
$ The process number of this shell.
! The process number of the last background command invoked.

The below some parameters are used by the Shell:

Parameter Description
CDPATH The search path for the cd command
PATH The search path for commands
HOME The default argument(home directory) for the cd command.
OPTARG The value of the last option argument processed by the getopts special command.
OPTIND The index of the last option processed by the getopts special command.
MAIL If this variable is set to the name of a mail file then the shell informs the user of the arrival of mail in the specified file.
MAILCHECK If this variable is set, it is interpreted as a value in seconds to wait between checks for new mail. The default is 600 (10 minutes). If the value is zero, mail is checked before each prompt.
MAILPATH A colon-separated list of files that are checked for new mail. MAIL is ignored if this variable is set.
PS1 Primary prompt string, by default $.
PS2 Secondary prompt string, by default >.
LANG, LC_ALL Locale variables.
LC_CTYPE Affects the mapping of bytes to characters for file name generation, for the interpretation of ‘\‘, and for handling $IFS.
SHACCT If this variable is set in the initial environment passed to the shell and points to a file writable by the user, accounting statistics are written to it.
TIMEOUT The shell exists when prompting for input if no command is entered for more than the given value in seconds. A value of zero means no timeout and is the default.
IFS Internal field separators, normally space, tab, and newline.

Blank Interpretation

The results of substitution are scanned for internal field separator characters and divided into distinct arguments where such characters are found. The values of null arguments are mentioned below.

Retained the explicit null arguments.

Removed the implicit null arguments.

File Name Generation

Sh command recognizes the three of the special characters listed in below, which is used to reduce the amount of typing you must do to specify filenames on a command line.

1-the asterisk (*)

2-the question mark (?),

3-the set of brackets ([ ])

Shell interprets these characters as the full filenames is called as filename expansion, which is useful for specify many files on a single command line.

By example, you may be want to print the group files containing records of month of April all of which begin with the letters April. In this place, you can use any one of these special characters to represent the parts of the filenames that vary and you can type one print command and specify all the files that begin with April.

So you can maintain this method to avoid the typed the full name of your file on the command line.


In sh command or any other programming languages quoting is very sensitive because quoted characters given some kind of functionalities but non-quoted character is given some different functionalities. The below characters have a special meaning to the shell and cause termination of a word unless quoted:

  1. ;
  2. &
  3. (
  4. )
  5. |
  6. ^
  7. newline
  8. space
  9. tab

Input and Output

The functionalities of input and output is running before a command is executed. It might be redirected using a distinct notation understood by the shell.

Most Unix system commands fetch input from your terminal and send the resulting output back to your terminal. A command normally reads its input from the standard input, which happens to be your terminal by default. Similarly, a command normally writes its output to standard output, which is again your terminal by default.

Let’s see have some example in the following.

Symbol Description
Standard input symbol
Standard Output symbol
pgm > file Output of pgm is redirected to file
pgm < file Program pgm reads its input from file
pgm >> file Output of pgm is appended to file
n > file Output from stream with descriptor n redirected to file
n >> file Output from stream with descriptor n appended to file
n >& m Merges output from stream n with stream m
n <& m Merges input from stream n with stream m
<< tag Standard input comes from here through next tag at the start of line
| Takes output from one program, or process, and sends it to another
descriptor 0 Standard input (STDIN)
descriptor 1 Standard output (STDOUT)
descriptor 2 Standard error output (STDERR)

Output Redirection

If the notation > file is appended to any command that usually writes its output to standard output, the output of that command will be written to file instead of your terminal.

To check the “who command” which redirects the complete output of the command in the users file.

$ who > users

You can be notice that no output appears at the terminal. This is because the output has been redirected from the default standard output device (the terminal) into the specified file. You can check the users file for the complete content −

$ cat users

Sumo                   tty01   Sep 12 07:30

Paul                  tty05   Sep 12 13:32

Reena                  tty09   Sep 12 10:10

Prince                   tty11   Sep 12 13:07

Philip                    tty12   Sep 12 13:03


Input Redirection

Just as the output of a command can be redirected to a file, so can the input of a command be redirected from a file.

Let’s take this example, to count the number of lines in the file users generated above, you can execute the command as follows.

$ wc – 1 users

3 users


Upon execution, you will receive the following output. You can count the number of lines in the file by redirecting the standard input of the wc command from the file users

$ wc – 1 < users




The very important concepts of the sh command or Unix is Environment, which is defined by environment variables. A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data.

It has list of name-value pairs like as normal argument and the name-value pairs send to executed program. sh command has many ways to interacts to environment.

Let’s see the following example.

First we set a variable SAMPLE and then we access its value using the echo command.

$SAMPLE=”Sh Command”

$echo $SAMPLE

Output of the above program is  Sh Command

You could be note the one important point like, environment variables are set without using the $ sign but while accessing them we use the $ sign as prefix. These variables remember their values until we come out of the shell.

See some Important Environment Variables list in below.

Variable Name Description
PWD Indicates the current working directory as set by the cd command.
HOME Indicates the home directory of the current user: the default argument for the cd built-in command.
UID Expands to the numeric user ID of the current user, initialized at the shell startup.
PATH Indicates the search path for commands. It is a colon-separated list of directories in which the shell looks for commands.
LD_LIBRARY_PATH A Unix system with a dynamic linker, contains a colonseparated list of directories that the dynamic linker should search for shared objects when building a process image after exec, before searching in any other directories.
RANDOM Increments by one each time an instance of bash is started. This variable is useful for determining whether the built-in exit command ends the current session
IFS Indicates the Internal Field Separator that is used by the parser for word splitting after expansion
DISPLAY Contains the identifier for the display that X11 programs should use by default.


We will discuss about the signals for in this portion. Signals are software interrupts sent to a program to indicate that an important event has occurred. The events can differ from user requests to illegal memory access errors.

Few signals, such as the interrupt signal, indicate that a user has asked the program to do something that is not in the usual flow of control. It is having the values inherited by the shell from its parent.

Here are mentioned some general Signals list.

Signals Number Signals Name Description
1 SIGHUP Hang up detected on controlling terminal or death of controlling process
2 SIGINT Issued if the user sends an interrupt signal (Ctrl + C)
3 SIGQUIT Issued if the user sends a quit signal (Ctrl + D)
8 SIGFPE Issued if an illegal mathematical operation is attempted
9 SIGKILL If a process gets this signal it must quit immediately and will not perform any clean-up operations
14 SIGALRM Alarm clock signal (used for timers)
15 SIGTERM Software termination signal (sent by kill by default)

You can easily get the list of signals on your terminal by using the kill –l command.

Sh Command

Note: The actual list of signals differs between Solaris, HP-UX, and Linux.


Every time sh command is executed the substitutions are carried out. The shell first check if a function whether defined with command name; if so, it is chosen for execution. If it not defined the command name, except for the special commands a new process is created and an attempt is made to execute the command through an exec.

The shell parameter $PATH defines the search path for the directory containing the command. The default path is ‘/usr/sbin:/bin:/usr/bin:‘. If the command name contains a / then the search path is not used.

If the file has execute permission but is not an a.out file, it is considered to be a file containing shell commands.


If the first character of argument zero is , commands are read from /etc/profile and $HOME/.profile, if the particular file exists. Commands are read as described below.

-c  string If the -c flag is present then commands are read from string.
-i If the -i flag is present or if the shell input and output are attached to a Terminal (as told by the function isatty())
-s If the -s flag is present or if no arguments remain then commands are read from the standard input. Shell output is written to file descriptor 2.

Job Control

Here we will discuss about job control of the sh command. It permits to user can to stop and resume processes, and to switch between front-end and back-end jobs. In generally, a job consists of the commands of a single pipeline. Each and every job is placed in a single process group. You can be stop any job by using the STOP command otherwise pressing the suspend key, like ^Z.

All jobs are recognized by job IDs of the following form:

Job Description
%, %%, or %+ Current job
%- The job that was previously the current job.
?string The only job whose name contains string.
%number The job with the given number.
Number The job with process group id number.
String The only job for which string is a prefix of its name.

See some built-in commands available in Job Control.

Job Description
bg [jobid …] Places each jobid in the background. The default job id is the current job.
fg [jobid …] Sequentially selects each jobid as the foreground job. The default job id is the current job.
kill [[-s signal | signal] jobid … | -l [status] A special version of the kill command that recognizes job ids in its arguments.
stop jobid … Stops the given jobs (i.e. sends a STOP signal to them).
Suspend Stops the shell itself. This is not allowed if the shell is a session leader.
wait [jobid] The wait command (see above) recognizes job ids in its arguments.



Special Commands

Command Name Description
: No effect; the command does nothing
.file Read and execute commands from file and return. The search path $PATH is used to find the directory containing file.
Break [n] Exit from the enclosing for or while loop, if any. If n is specified then break n levels.
continue[n] Resume the next iteration of the enclosing for or while loop. If n is specified then resume at the nth enclosing loop.
cd[arg] Change the current directory to arg. The shell parameter $HOME is the default arg.
eval[arg…] The arguments are read as input to the shell and the resulting command(s) are executed.
exit[n] Causes the shell to exit with the exit status specified by n. If n is omitted then the exit status is that of the last command executed. An end of file will also exit from the shell.
export[name…] The given names are marked for automatic export to the environment of subsequently-executed commands. If no arguments are given then a list of exportable names is printed.
hash[name…] The shell maintains a hash table of the locations of external commands. If name arguments are given, each one is looked up and is inserted into the table if it is found. Otherwise, a list of the commands currently in the table is printed.
new grp[arg…] Equivalent to “exec newgrp arg …”
return[n] Return from a shell function to the execution level above. With the argument n, the special variable $? is set to the given value.
wait[n] Wait for the specified process and report its termination status.

Final Words

Here have detailed information for sh command. It might be having miss the some of sh command because i was mentioned some important commands. Let us know your valuable comments after read this concept

Leave a Comment

Your email address will not be published.

Pin It on Pinterest

Scroll to Top