Assign Output of a Shell Command to a Variable

How do I set a variable to the output of a command in Bash?

In addition to backticks `command`, command substitution can be done with $(command) or "$(command)", which I find easier to read, and allows for nesting.

OUTPUT=$(ls -1)
echo "${OUTPUT}"

MULTILINE=$(ls \
-1)
echo "${MULTILINE}"

Quoting (") does matter to preserve multi-line variable values; it is optional on the right-hand side of an assignment, as word splitting is not performed, so OUTPUT=$(ls -1) would work fine.

How to assign the output of a Bash command to a variable?

Try:

pwd=`pwd`

or

pwd=$(pwd)

Notice no spaces after the equals sign.

Also as Mr. Weiss points out; you don't assign to $pwd, you assign to pwd.

Assign output of a shell command to a variable

You missed the echo

size=$(echo ${result[$i]} | awk '{print $1}')

Here the output the the echo is passed as input to the awk

The $() or back ticks just run the command and assign it to a variable, so when you just write

${result[$i]} | awk '{print $1}'

it won't give you anything as nothing is passed as input to the awk command.

How would I store the shell command output to a variable in python?

By using module subprocess. It is included in Python's standard library and aims to be the substitute of os.system. (Note that the parameter capture_output of subprocess.run was introduced in Python 3.7)

>>> import subprocess
>>> subprocess.run(['cat', '/etc/hostname'], capture_output=True)
CompletedProcess(args=['cat', '/etc/hostname'], returncode=0, stdout='example.com\n', stderr=b'')
>>> subprocess.run(['cat', '/etc/hostname'], capture_output=True).stdout.decode()
'example.com\n'

In your case, just:

import subprocess

v = subprocess.run(['cat', '/etc/redhat-release'], capture_output=True).stdout.decode()

Update: you can split the shell command easily with shlex.split provided by the standard library.

>>> import shlex
>>> shlex.split('cat /etc/redhat-release')
['cat', '/etc/redhat-release']
>>> subprocess.run(shlex.split('cat /etc/hostname'), capture_output=True).stdout.decode()
'example.com\n'

Update 2: os.popen mentioned by @Matthias

However, is is impossible for this function to separate stdout and stderr.

import os

v = os.popen('cat /etc/redhat-release').read()

Assigning the output of a command to a variable

You can use a $ sign like:

OUTPUT=$(expression)

Assigning a command output to a shell script variable

To assign output of some command to a variable you need to use command substitution :

variable=$(command)

For your case:

c=$(echo {b%?} |rev | cut -d '/' -f 1 | rev)

Just wondering why dont you try

basename ${b} 

Or just

echo ${b##*/}
home1

If you want to trim last number from your path than:

b="/home/home1"
echo $b
/home/home1
b=${b//[[:digit:]]/}
c=$(echo ${b##*/})
echo ${c}
home


Related Topics



Leave a reply



Submit