4

I can allocate a path to a certain 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 locate as a variable's value?

I tried the following but it doesn't work:

alvas@ubi:~$ locate -b 'mosesdecoder' . | VAR1=
alvas@ubi:~$ VAR1
VAR1: command not found
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
alvas
  • 115,346
  • 109
  • 446
  • 738

2 Answers2

9

You need to assign the output of the locate command to the variable:

VAR1=$(locate -b 'mosesdecoder' . | head -n 1)

(Use head to get the top n lines).

The construct $(...) is called command substitution and you can read about it in the Command Substitution section of the Bash Reference Manual or of the POSIX Shell Specification.

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
fejese
  • 4,601
  • 4
  • 29
  • 36
3

read, redirections and process substitutions are your friends:

IFS= read -r var1 < <(locate -b 'mosesdecoder' .)

And using lowercase variable names is considered good practice.

It would also be better to use the -0 flag, if your locate supports it:

IFS= read -r -d '' var1 < <(locate -0 -b 'mosesdecoder' .)

just in case you have newlines or funny symbols in your paths.

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
  • 1
    Yes deleted because you already have this answer which was posted not only few seconds faster it was also more accurate. – anubhava Nov 11 '14 at 15:10