Save the result of find as a variable in a shell script [duplicate]
Matthew Martinez
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-gccHow 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 0 2 Answers
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 2 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') \$xAdditionally, 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.
3