Assigning command output to a variable (BASH)

I need to assign the output of a command to a variable. The command I tried:

grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}' 

I am trying to use this code to assign a variable:

 UUID=$(grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}') 

However, it gives a syntax error. In addition, I want it to work in a bash script.

Mistake:

 ./upload.sh: line 12: syntax error near unexpected token ENE=$( grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}' )' ./upload.sh: line 12: ENE=$( grep UUID fstab | awk '/ext4/ {print $1}' | awk '{print substr($0,6)}' )' 
+7
source share
2 answers

Well, using the $ () 'operator on the head is the usual way to get the output of a bash command. Since it covers a subshell, it is not so effective.

I tried:

 UUID=$(grep UUID /etc/fstab|awk '/ext4/ {print $1}'|awk '{print substr($0,6)}') echo $UUID # writes e577b87e-2fec-893b-c237-6a14aeb5b390 

it works great :)

EDIT:

Of course, you can shorten your command:

 # First step : Only one awk UUID=$(grep UUID /etc/fstab|awk '/ext4/ {print substr($1,6)}') 

Again:

 # Second step : awk has a powerful regular expression engine ^^ UUID=$(cat /etc/fstab|awk '/UUID.*ext4/ {print substr($1,6)}') 

You can also use awk with the file argument:

 # Third step : awk use fstab directlty UUID=$(awk '/UUID.*ext4/ {print substr($1,6)}' /etc/fstab) 
+14
source

Just for troubleshooting and something else, to try to figure out if you can make it work, you can also try using “back steps”, like

 cur_dir=`pwd` 

will save the output of the pwd in your cur_dir variable, although using the $() approach is usually preferable.

In the quote from the pages provided to me at http://unix.stackexchange.com :

The second form of `COMMAND` (using backticks) is more or less deprecated for Bash, as it has some problems with nesting (" internal "return lines must be escaped) and escaping characters. Use $(COMMAND) , it is also POSIX!

+2
source

All Articles