Assigning output of a command to a variable(BASH)

12,864

Solution 1

well, using the '$()' subshell operator is a common way to get the output of a bash command. As it spans a subshell it is not that efficient.

I tried :

UUID=$(grep UUID /etc/fstab|awk '/ext4/ {print $1}'|awk '{print substr($0,6)}')
echo $UUID # writes e577b87e-2fec-893b-c237-6a14aeb5b390

it works perfectly :)

EDIT:

Of course you can shorten your command :

# First step : Only one awk
UUID=$(grep UUID /etc/fstab|awk '/ext4/ {print substr($1,6)}')

Once more time :

# Second step : awk has a powerful regular expression engine ^^
UUID=$(cat /etc/fstab|awk '/UUID.*ext4/ {print substr($1,6)}')

You can also use awk with a file argument ::

# Third step : awk use fstab directlty
UUID=$(awk '/UUID.*ext4/ {print substr($1,6)}' /etc/fstab)

Solution 2

Just for trouble-shooting purposes, and something else to try to see if you can get this to work, you could also try to use "backticks", e.g,

cur_dir=`pwd`

would save the output of the pwd command in your variable cur_dir, though using $() approach is generally preferable.

To quote from a pages given to me on http://unix.stackexchange.com:

The second form `COMMAND` (using backticks) is more or less obsolete for Bash, since it has some trouble with nesting ("inner" backticks need to be escaped) and escaping characters. Use $(COMMAND), it's also POSIX!

Share:
12,864
Eray Tuncer
Author by

Eray Tuncer

Updated on June 24, 2022

Comments

  • Eray Tuncer
    Eray Tuncer almost 2 years

    I need to assign the output of a command to a variable. The command I tried is:

    grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}'
    

    I try this code to assign a variable:

    UUID=$(grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}')
    

    However, it gives a syntax error. In addition I want it to work in a bash script.

    The error is:

    ./upload.sh: line 12: syntax error near unexpected token ENE=$( grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}'
     )'
    
    ./upload.sh: line 12:   ENE=$( grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}'
     )'