How do I run a shell command from a script?

Published on Aug. 22, 2023, 12:18 p.m.

To run a shell command from a script in Linux, you can use the backtick (`) operator or the “subshell” syntax $(command). Here’s an example:

#!/bin/bash
output=`ls -l`
echo $output

This will run the “ls -l” command and store the output in the “output” variable, which is then printed to the console. Alternatively, you can use the subshell syntax:

#!/bin/bash
output=$(ls -l)
echo $output

This achieves the same result as using the backtick operator. Note that if the command produces a large amount of output, it may be more efficient to redirect the output to a file and then read the file in the script. This can be done using the “>” operator, like this:

#!/bin/bash
ls -l > output.txt
# do something with output.txt

This redirects the output of the “ls -l” command to a file called “output.txt”.

Tags: