Command substitution in linux

What is command substitution in a shell? [duplicate]

I’m using Ubuntu 16.04 with Bash and I tried to read in Wikipedia, in here and in here, but I failed to understand the meaning of «command substitution» in shell-scripting in general, and in Bash in particular, as in:

What is the meaning of this term? Edit: When I first published this question I already knew the pure concept of substitution and also the Linux concept of variable substitution (replacing a variable with its value by execution), yet I still missed the purpose of this shell feature from the documentation for whatever reason or group of reasons.

My answer after question locked

Command substitution is an operation with dedicated syntax to both execute a command and to have this command’s output hold (stored) by a variable for later use.

An example with date :

printf 'The date is %s\n' "$thedate" 
  1. The command substitution syntax is $() .
  2. The command itself is date .
  3. Combining both we get $(date) , its value is the result of the substitution (that we could get after execution).
  4. We save that value in a variable, $thedate , for later use.
  5. We display the output value held by the variable with printf , per the command above.

Note: \n in printf is a line-break.

OK, everyone needs to relax and stop accusing each other of trolling. If you don’t like a question, then downvote or ignore it and walk away. If you feel you’re being attacked in comments, then do not engage but flag and walk away.

Displaying the output of a command using command substitution and echo is a bad example of command substitution because 1) the output would have been displayed anyway, 2) printf is safer to use for variable data. The example could as well be written date | sed ‘s/^/Today is /’

@Kusalananda I see your point that printing it immediately (with printf ) is useless. I changed the phrasing a bit, from immediately to sometime later , is it more appealing?

2 Answers 2

«Command substitution» is the name of the feature of the shell language that allows you to execute a command and have the output of that command replace (substitute) the text of the command.

There is no other feature of the shell language that allows you to do that.

A command substitution, i.e. the whole $(. ) expression, is replaced by its output, which is the primary use of command substitutions.

The command that the command substitution executes, is executed in a subshell, which means it has its own environment that will not affect the parent shell’s environment.

Not all subshell executions are command substitutions though (see further examples at end).

Example showing that a command substitution is executed in a subshell:

$ s=123 $ echo "hello $( s=world; echo "$s" )" hello world $ echo "$s" 123 

Here, the variable s is set to the string 123 . On the next line, echo is invoked on a string containing the result of a command substitution. The command substitution sets s to the string world and echoes this string. The string world is the output of the command in the command substitution and thus, if this was run under set -x , we would see that the second line above would have been expanded to echo ‘hello world’ , which produces hello world on the terminal:

$ set -x $ echo "hello $( s=world; echo "$s" )" ++ s=world ++ echo world + echo 'hello world' hello world 

( bash adds an extra level of + prompts to every level of a command substitution subshell in the trace output, other shells may not do this)

Читайте также:  Как посмотреть в linux интерфейс

Lastly, we show that the command inside the command substitution was run in its own subshell, because it did not affect the value of s in the calling shell (the value of s is still 123 , not world ).

There are other situations where commands are executed in subshells, such as in

In bash , unless you set the lastpipe option (only in non-interactive instances), the read is executed in a subshell, which means that $message will not be changed in the parent shell, i.e. doing echo «$message» after the above command will echo an empty string (or whatever value $message was before).

A process substitution in bash also executes in a subshell:

This too is distinct from a command substitution.

Источник

How to Use $() and $<> Expansions in a Shell Script

If you are using a Linux system, you might already know how crucial a shell interface is for interacting with your system. On most Linux distributions, Bash is the default shell that we use to run commands and execute scripts. A shell script is a set of commands that, when executed, is used to perform some useful function(s) on Linux. This .sh file, written by a user, contains all the commands used to perform a task so that we do not have to run those commands manually, one by one.

In this tutorial, we will explain two of the most useful bash expansions used in shell scripts:

An expansion in Shell is performed on the script after it has been split into tokens. A token is a sequence of characters considered a single unit by the shell. It can either be a word or an operator.

We have run all the examples and scripts mentioned in this article on a Debian 10 Buster system. However, you can easily replicate them on most Linux shells. We are using the default Debian command line, the Terminal, for this tutorial. On Debian, you can access it through the Application Launcher search bar as follows:

To access the Application launcher, simply hit the Super/Windows key on your keyboard.

$() Command Substitution

According to the official GNU Bash Reference manual:

“Command substitution allows the output of a command to replace the command itself. Bash performs the expansion by executing the command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.” Command substitution occurs when a command is enclosed as follows:

For example, the following echo commands substitute the date command’s output as their input:

You can also use command substitution to assign value to a variable. For example, we will print today’s date through the variable TODAY as follows:

Читайте также:  Script for kali linux

Another utility of the command substitution is in shell loops to get input. Here, we will try to print all the .txt files in our home folder using command substitution:

Using Command Substitution in a Shell Script

The above examples are a few ways in which you can utilize the power of command substitution in your shell script. Here is a sample status report that we can print using the following shell script:

TODAY =$ ( date )
echo «Today is $TODAY «

USERS =$ ( who | wc -l )
echo » $USERS users are currently logged in»

UPTIME =$ ( date ; uptime )
echo «The uptime is $UPTIME «

Command substitution has been used thrice in this script; in printing the date, logged in users and uptime. We saved the script as follows:

Made it executable and then ran it through the following command:

Here is the output of our status.sh script:

You can, of course, create more meaningful scripts by following the examples we have just mentioned.

$<> Parameter Substitution/Expansion

A parameter, in Bash, is an entity that is used to store values. A parameter can be referenced by a number, a name, or by a special symbol. When a parameter is referenced by a number, it is called a positional parameter. When a parameter is referenced by a name, it is called a variable. When a parameter is referenced by a special symbol, it means they are autoset parameters with special uses.

Parameter expansion/substitution is the process of fetching the value from the referenced entity/parameter. It is like you are expanding a variable to fetch its value.

The simplest possible parameter expansion syntax is the following:

Here is how you can use the parameter expansion in Bash:

For example, the simplest usage is to substitute the parameter by its value:

This command will substitute the value of the variable “name” to be used by the echo command:

You might be thinking that the same can be achieved by avoiding the curly braces as follows:

The answer is that during parameter expansion, these curly braces help in delimiting the variable name. Let us explain what we mean by limiting here. Let me run the following command on my system:

The result did not print the value of the variable name as the system thought that I was referring to the variable “name_”. Thus, my variable name was not “delimited”. The curly braces in the following example will delimit the variable name and return the results as follows:

Here are all the ways in which variables are substituted in Shell:

$ This command substitutes the value of the variable.
$ If a variable is null or if it is not set, word is substituted for variable. The value of the variable does not change.
$ If a variable is null or if it is not set, the value of the variable is set to word.
$ If a variable is null or if it is not set, the message is printed to the standard bash error.
$ If variable is set, word is substituted for variable. However, the value of the variable itself does not change.

The above examples are a few ways in which you can utilize the power of variable substitution in Bash. You can incorporate these ways to use expansion in your shell scripts to optimally achieve your task at hand.

Читайте также:  Dns настройка на linux mint

About the author

Karim Buzdar

Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. He blogs at LinuxWays.

Источник

Unix / Linux — Shell Substitution

The shell performs substitution when it encounters an expression that contains one or more special characters.

Example

Here, the printing value of the variable is substituted by its value. Same time, «\n» is substituted by a new line −

#!/bin/sh a=10 echo -e "Value of a is $a \n"

You will receive the following result. Here the -e option enables the interpretation of backslash escapes.

Following is the result without -e option −

The following escape sequences which can be used in echo command −

suppress trailing newline

You can use the -E option to disable the interpretation of the backslash escapes (default).

You can use the -n option to disable the insertion of a new line.

Command Substitution

Command substitution is the mechanism by which the shell performs a given set of commands and then substitutes their output in the place of the commands.

Syntax

The command substitution is performed when a command is given as −

When performing the command substitution make sure that you use the backquote, not the single quote character.

Example

Command substitution is generally used to assign the output of a command to a variable. Each of the following examples demonstrates the command substitution −

#!/bin/sh DATE=`date` echo "Date is $DATE" USERS=`who | wc -l` echo "Logged in user are $USERS" UP=`date ; uptime` echo "Uptime is $UP"

Upon execution, you will receive the following result −

Date is Thu Jul 2 03:59:57 MST 2009 Logged in user are 1 Uptime is Thu Jul 2 03:59:57 MST 2009 03:59:57 up 20 days, 14:03, 1 user, load avg: 0.13, 0.07, 0.15

Variable Substitution

Variable substitution enables the shell programmer to manipulate the value of a variable based on its state.

Here is the following table for all the possible substitutions −

Substitute the value of var.

If var is null or unset, word is substituted for var. The value of var does not change.

If var is null or unset, var is set to the value of word.

If var is null or unset, message is printed to standard error. This checks that variables are set correctly.

If var is set, word is substituted for var. The value of var does not change.

Example

Following is the example to show various states of the above substitution −

#!/bin/sh echo $ echo "1 - Value of var is $" echo $ echo "2 - Value of var is $" unset var echo $ echo "3 - Value of var is $var" var="Prefix" echo $ echo "4 - Value of var is $var" echo $ echo "5 - Value of var is $"

Upon execution, you will receive the following result −

Variable is not set 1 - Value of var is Variable is not set 2 - Value of var is Variable is not set 3 - Value of var is This is default value 4 - Value of var is Prefix Prefix 5 - Value of var is Prefix

Источник

Оцените статью
Adblock
detector