Linux output to variable

How to get output of a bash command in a variable

I have been following through some of the similar questions (such as How to set a variable to the output from a command in Bash?), however the accepted answers seem to be non-working for me. I wasn’t sure whether I ought to derail someone else’s question or post my own duplicate, so apologies if I chose wrong here. I wish to get the output and exit status of a number of commands in a script I am putting together. Here is an example of what I have been using:

cmd_output=$(rm $file) exit_status=$? if [ "$" -eq 0 ] then log "Successfully removed the original" $ else fail "Failed to remove the original, the output was: \n $" fi 
# Usage: fail "Failure message" function fail < echo "FATAL ERROR: $1" >> "$/$" exit 1 > # Usage: log "Log message" 3 Where the tab-level is 3. function log < if (("$" > 0)) then eval "printf ' %.0s' " >> "$/$" fi echo "$1" >> "$/$" return 0 > 

In the example above I use the $(cmd) format, but I have also tried using backticks. In my log file, all I see when there is a failure is:

Also, the output of the failed commands ends up on screen as per usual. Is there a common reason that my cmd_output variables would be remaining empty?

3 Answers 3

You have to include the output of the special standard error output stream:

There are three default streams on every program (that are numbered file descriptors):

0. Standard input (where the program normally reads from) 1. Standard output (where the program normally writes to) 2. Standard error (where the program normally writes error messages) 

So to capture the error messages, we must redirect standard error output (stderr) into normal standard output (stdout) which will then be captured by the $(. ) expression.

The syntax for redirection is through the > «operator». Immediately before it you tell which file descriptor to redirect (the default is 1, which is stdout). And you can specify it to redirect to a file. If you write an ampersand ( & ) after it, you force it to redirect into another file descriptor. Therefore, in this example, we redirect file descriptor 2 (stderr) into file descriptor 1 (stdout).

Another observation is that it is probably good practice to place your $file variable between double quotes, in case it has white space characters.

Источник

BASH command output to the variable

Different types of bash commands need to be run from the terminal based on the user’s requirements. When the user runs any command from the terminal then it shows the output if no error exists otherwise it shows the error message. Sometimes, the output of the command needs to be stored in a variable for future use. Shell command substitution feature of bash can be used for this purpose. How you can store different types of shell commands into the variable using this feature is shown in this tutorial.

Читайте также:  What fonts are installed linux

Command Substitution Syntax:

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

variable = ` command `
variable = ` command [ option… ] argument1 arguments2 … `
variable = `/ path / to / command `

***Note: Don’t use any space before and after the equal sign when using the above commands.

Single command output to a variable

Bash commands can be used without any option and argument for those commands where these parts are optional. The following two examples show the uses of simple command substitution.

Example#1:

bash `date` command is used to show the current date and time. The following script will store the output of `date` command into $current_date variable by using command substitution.

Example#2:

`pwd` command shows the path of the current working directory. The following script stores the output of `pwd` command into the variable, $current_dir and the value of this variable is printed by using `echo` command.

Command with option and argument

The option and argument are mandatory for some bash commands. The following examples show how you can store the output of the command with option and argument into a variable.

Example#3:

Bash `wc` command is used to count the total number of lines, words, and characters of any file. This command uses -c, -w and -l as option and filename as the argument to generate the output. Create a text file named fruits.txt with the following data to test the next script.
fruits.txt

Run the following commands to count and store the total number of words in the fruits.txt file into a variable, $count_words and print the value by using `echo` command.

Example#4:

`cut` is another bash command that uses option and argument to generate the output. Create a text file named weekday.txt with seven-weekday names to run the next script.

Create a bash file named cmdsub1.sh with the following script. In this script, while loop is used to read the content of weekday.txt file line by line and read the first three characters of each line by using `cut` command. After cutting, the string value is stored in the variable $day. Next, If the statement is used to check the value of $day is ‘Sun’ or not. The output will print ‘Sunday is the holiday‘ when if the condition is true otherwise it will print the value of $day.

Читайте также:  Vmware and oracle linux

#!/bin/bash
filename = ‘weekday.txt’
while read line; do
day = ` echo $line | cut -c 1 — 3 `
if [ $day == «Sun» ]
then
echo «Sunday is the holiday»
else
echo $day
fi
done < $filename

Using command substitution in loop

You can store the output of command substitution into any loop variable which is shown in the next example.

Example#5:

Create a file named cmdsub2.sh with the following code. Here, `ls -d */` command is used to retrieve all directory list from the current directory. For loop is used here to read each directory from the output and store it in the variable $dirname which is printed later.

Using nested commands

How you can use multiple commands using pipe(|) is shown in the previous example. But you can use nested commands in command substitution where the output of the first command depends on the output of the second command and it works opposite of the pipe(|) command.

Nested command syntax:

Example#6:

Two commands, `echo` and `who` are used in this example as the nested command. Here, `who` command will execute first that print the user’s information of the currently logged in user. The output of the `who` command will execute by `echo` command and the output of `echo` will store into the variable $var. Here, the output of `echo` command depends on the output of `who` command.

Using Command path

If you know the path of the command then you can run the command by specifying the command path when using command substitution. The following example shows the use of command path.

Example#7:

`whoami` command shows the username of the currently logged in user. By default, this command is stored in /usr/bin/ folder. Run the following script to run `whoami` command using path and store in the variable, $output, and print the value of $output.

Using Command Line argument

You can use the command line argument with the command as the argument in the command substitution.

Example#8:

Create a bash file named cmdsub3.sh with the following script. `basename` command is used here to retrieve the filename from the 2 nd command line argument and stored in the variable, $filename. We know the 1 st command line argument is the name of the executing script which is denoted by $0.

Run the script with the following argument value.

Here, the basename of the path, Desktop/temp/hello.txt is ‘hello.txt’. So, the value of the $filename will be hello.txt.

Conclusion:

Various uses of command substitutions are shown in this tutorial. If you need to work with multiple commands or depended commands and store the result temporary to do some other tasks later then you can use this feature in your script to get the output.

Читайте также:  Booting linux on arm

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

How can I assign the output of a function to a variable using bash?

I discovered that newlines were being stripped when I did «echo $VAR». If instead I quoted $VAR, it preserved the newlines.

@lmat-ReinstateMonica you can use what’s called a nameref in bash 4.3 and above to achieve that. this answer covers some of the notion.

You may use bash functions in commands/pipelines as you would otherwise use regular programs. The functions are also available to subshells and transitively, Command Substitution:

Is the straighforward way to achieve the result you want in most cases. I will outline special cases below.

Preserving trailing Newlines:

One of the (usually helpful) side effects of Command Substitution is that it will strip any number of trailing newlines. If one wishes to preserve trailing newlines, one can append a dummy character to output of the subshell, and subsequently strip it with parameter expansion.

function scan2 () < local nl=$'\x0a'; # that's just \n echo "output$$" # 2 in the string + 1 by echo > # append a character to the total output. # and strip it with %% parameter expansion. VAR=$(scan2; echo "x"); VAR="$" echo "$---" 

Use an output parameter: avoiding the subshell (and preserving newlines)

If what the function tries to achieve is to «return» a string into a variable , with bash v4.3 and up, one can use what’s called a nameref . Namerefs allows a function to take the name of one or more variables output parameters. You can assign things to a nameref variable, and it is as if you changed the variable it ‘points to/references’.

function scan3() < local -n outvar=$1 # -n makes it a nameref. local nl=$'\x0a' outvar="output$$" # two total. quotes preserve newlines > VAR="some prior value which will get overwritten" # you pass the name of the variable. VAR will be modified. scan3 VAR # newlines are also preserved. echo "$== $returnstring"

This is relevant. https://stackoverflow.com/a/38997681/5556676

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited May 23, 2017 at 12:02
CommunityBot
1 1 silver badge
answered Oct 8, 2016 at 9:40
Add a comment |
0

I think init_js should use declare instead of local!

function scan3() < declare -n outvar=$1 # -n makes it a nameref. local nl=$'\x0a' outvar="output$$" # two total. quotes preserve newlines > 

Источник

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