0

I have to create a script on RHEL and was wondering if I am able to save the output of a command as a variable. For example:

4.2.2 Ensure logging is configured (Not Scored) : = OUTPUT (which comes from the command sudo cat /etc/rsyslog.conf)

This is what I have now.

echo " ### 4.2.2 Ensure logging is configured (Not Scored) : ### "
echo " "
echo "Running command: "
echo "#sudo cat /etc/rsyslog.conf"
echo " "

sudo cat /etc/rsyslog.conf

Thank you!

Rubén
  • 34,714
  • 9
  • 70
  • 166

2 Answers2

2
variable=$(command)
variable=$(command [option…] argument1 arguments2 …)
variable=$(/path/to/command)

Taken from https://linuxhint.com/bash_command_output_variable/

Wolfgang Blessen
  • 900
  • 10
  • 29
2

Here is an example:

MESSAGE=$(echo "Hello!")
echo $MESSAGE
Hello!

Or the old standard:

MESSAGE=`echo "Hello!"`
echo $MESSAGE
Hello!

In your case:

FILE_CONTENT=$(cat /etc/rsyslog.conf)

NOTE!!!: It is very important to not use spaces near equal!

This form is incorrect:

MESSAGE = `echo "Hello!"`
MESSAGE: command not found
McLeon
  • 66
  • 3
  • 1
    It is good to explain that what you are doing (and what the OP is looking for) is called *Command Substitution*. Where the output of a command is substituted in place of the command for assignment to a variable. (I know you know but the OP may not -- always helps if they want to search further). Good note that `$(...)` is preferred over the older `\`...\``. – David C. Rankin Sep 23 '21 at 06:37
  • Thank you for the explanation! Really appreciate it :) – user14135159 Sep 23 '21 at 06:49
  • `echo $MESSAGE` is buggy. See [I just assigned a variable, but `echo $variable` shows something different!](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – Charles Duffy Oct 25 '22 at 02:37