How do I assign the first search result to a bash variable?
I can highlight the path to a specific variable from bash:
VAR1=/home/alvas/something
I can find it automatically:
$ cd
$ locate -b "something" .
/home/alvas/something
/home/alvas/someotherpath/something
But how do I assign the first result from a location definition as the value of a variable?
I've tried the following but it doesn't work:
alvas@ubi:~$ locate -b 'mosesdecoder' . | VAR1=
alvas@ubi:~$ VAR1
VAR1: command not found
source to share
You need to assign the output of the command to a locate
variable:
VAR1=$(locate -b 'mosesdecoder' . | head -n 1)
(Use head
to get top lines n
).
The construct $(...)
is called command substitution, and you can read about it in the Command Substitution section of the Bash Reference Manual or the POSIX Shell Specification .
source to share
read
, redirections and process replacements are your friends:
IFS= read -r var1 < <(locate -b 'mosesdecoder' .)
And using lowercase variable names is considered good practice.
Also it would be better to use a flag -0
if yours locate
supports it:
IFS= read -r -d '' var1 < <(locate -0 -b 'mosesdecoder' .)
just in case you have newlines or funny characters in your paths.
source to share