4

This question already has an answer here:

I want to find the path to a file, and save that output to a variable in a shell script. Specifically, in the bash shell, if I write

GCC_VERSION="find *-gcc"

Then

echo ${GCC_VERSION}

Prints

find some-gcc

How do I get the variable GCC_VERSION to just hold the output of find? That is how do I save the output of the find *-gcc command into the variable GCC_VERSION so that

echo ${GCC_VERSION}

prints

some-gcc

marked as duplicate by muru, Ravexina, Byte Commander, sudodus, Community Apr 5 '18 at 9:29

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

10

First, your find command is incorrect. If you want to look for all files that end in -gcc in the current directory it should be:

$ find . -type f -name "*-gcc"

To save output of find to GCC_VERSION use process substitution:

$ GCC_VERSION=$(find . -type f -name "*-gcc")

Notice that you may have more than one file that ends in -gcc so enclose a variable name in a double quote:

$ echo "$GCC_VERSION"
./mipsel-linux-gnu-gcc
./aarch64-linux-gnu-gcc
./mips-linux-gnu-gcc
./arm-linux-gnueabihf-gcc
3

You need to use back ticks

VARIABLE=`Command`

or better the recommended new-style command substitution syntax

VARIABLE=$(Command)

While both forms are supported, there are limitations to script embedding in the former.

A quote from The Open Group Base Specifications Issue 7, 2018 edition:

The "$()" form of command substitution solves a problem of inconsistent behavior when using backquotes. For example:

                Command               Output
                echo '\$x'              \$x
                echo `echo '\$x'`       $x
                echo $(echo '\$x')      \$x

Additionally, the backquoted syntax has historical restrictions on the contents of the embedded command. While the newer "$()" form can process any kind of valid embedded script, the backquoted form cannot handle some valid scripts that include backquotes. For example, these otherwise valid embedded scripts do not work in the left column, but do work on the right:

echo `                        echo $(
cat <<\eof                    cat <<\eof 
a here-doc with `             a here-doc with )
eof                           eof
`                             )

... end of quote.

Not the answer you're looking for? Browse other questions tagged or ask your own question.