深度阅读

How do I run a shell command from a script?

作者
作者
2023年08月22日
更新时间
8.38 分钟
阅读时间
0
阅读量

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”.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。