How i can put the result of a command inside a bash variable?

#!/bin/bash
#...
for i in `ls -c1 /usr/share/applications`
do
name="cat $i | grep ^Name= | cut -d = -f2"
echo $name
#...
done

Now inside name as output is present:

while i want only the result of the command.

Ideally i would like obtain that information using only bash ... or bash+sed or bash+awk but i don't known if is possible so, for the moment, i used bash+grep+cut.

The final project will be an automatic menu generator for pekwm and, i hope, even for icewm.

If is possible i would like obtain that information using only the language that i specify above because i don't want use big languages (i means big package as perl, python, etc).
The final stage will be a test even on openbsd.

Note:
This is the second day that i'm broken my head on the wall. :wall:

name=`cat $i | grep ^Name= | cut -d = -f2`
1 Like

If i use ' i obtain that output:

cat $i | grep ^Name= | cut -d = -f2

instead the result of the command.
Don't work ... :frowning:

Those are not single quotes but backquotes, also called a grave accent mark. Usually to the left of the number 1 key. You can also do this which handles nesting commands better:

name=$(cat $i | grep ^Name= | cut -d = -f2)

Actually, save a process and useless use of cat:

name=$(grep ^Name=  $i | cut -d = -f2)
1 Like

Ok, now i tried using backquotes.
But i obtain errors instead of the result:

$ ./prova.sh

cat: arandr.desktop: File o directory non esistente

cat: qv4l2.desktop: File o directory non esistente

...

Naturally that files are present.

The `ls ...` command substitution in the for loop will mangle any filenames containing IFS characters (by default, space, tab, and newline). Perhaps that's related to your breakage.

Regards,
Alister

#!/bin/bash

for i in `ls -c1 /usr/share/applications`
do
name=`cat /usr/share/applications/$i | grep ^Name= | cut -d = -f2`
echo $name
done

Ok thanks i resolved there was another error inside the script. :slight_smile:

---------- Post updated at 06:00 PM ---------- Previous update was at 05:52 PM ----------

Thanks for the suggestions:

but for categories i use a more complex solution:

categories=`cat /usr/share/applications/$i | grep ^Categories= | sed 's/;/=/g' | cut -d = -f2`

work
if i change on the other way don't work.

You get a useless use of cat award.

Fix even for that command:

categories=$(grep ^Categories= /usr/share/applications/$i | sed 's/;/=/g' | cut -d = -f2)