|
Command substitution lets you capture the output of a command and use it as a value. This is one of the most powerful features in shell scripting. The modern syntax uses |
|
|
Output:
Current user: root |
|
|
You can also use backticks, but |
|
|
Output:
Current user: root |
|
|
Command substitution can be used directly in strings
by using the You can also use the backticks syntax, but |
|
|
Output:
Current user: root |
|
|
Command substitution can be nested with This is useful when you need to capture the output of a command and use it as a value in another command. Remember to quote the nested commands to avoid word splitting and globbing. |
|
|
Output:
Shell: sh Shell directory: /bin Parent directory: / |
|
|
Command substitution can be also be used in conditional checks. This should be used sparingly as it can make the code harder to read when nested deeply or if the command is complex. For more complex conditional checks, it’s better to capture the output of the command in a variable and use that in the conditional check. |
|
|
Output:
Running on Linux |
|
|
Command substitution strips trailing newlines from the output. This is usually what you want. To preserve trailing newlines, append a character and then remove it with parameter expansion. |
|
|
Output:
Output: 'Hello' Preserved: 'Hello ' |
|
|
Store command exit in a variable too if needed. |
|
|
Output:
Result: ls: cannot access '/nonexistent': No such file or directory Exit code was: 2 |
|
|
You can use command substitution in arithmetic if the output is a number. |
|
|
Output:
File count: 3 Double the files: 6 |
|