Neekoy
Neekoy

Reputation: 2533

Using a BASH script variable into an executed command

Can someone please help with this because I can't seem to find a solution. I have the following script that works fine:

#!/bin/bash

#Checks the number of lines in the userdomains file

NUM=`awk 'END {print NR}' /etc/userdomains.hristian`;

echo $NUM


#Prints out a particular line from the file (should work with $NUM eventually)

USER=`sed -n 4p /etc/userdomains.hristian`

echo $USER


#Edits the output so that only the username is left

USER2=`echo $USER | awk '{print $NF}'`

echo $USER2

However, when I substitute the 4 on line 12 with the variable $NUM, like this, it doesn't work:

USER=`sed -n $NUMp /etc/userdomains.hristian`

I tried a number of different combinations of quotes and ${}, however none of them seem to work because I'm a BASH newbie. Help please :)

Upvotes: 0

Views: 50

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74645

I'm not sure exactly what you've already tried but this works for me:

$ cat out
line 1
line 2
line 3
line 4
line 5
$ num=4
$ a=`sed -n ${num}p out`
$ echo "$a"
line 4

To be clear, the issue here is that you need to separate the expansion of $num from the p in the sed command. That's what the curly braces do. Note that I'm using lowercase variable names. Uppercase ones should be be reserved for use by the shell. I would also recommend using the more modern $() syntax for command substitution:

a=$(sed -n "${num}p" out)

The double quotes around the sed command aren't necessary but they don't do any harm. In general, it's a good idea to use them around expansions.

Presumably the script in your question is a learning exercise, which is why you have done all of the steps separately. For the record, you could do the whole thing in one go like this:

awk 'END { print $NF }' /etc/userdomains.hristian

In the END block, the values from the last line in the file can still be accessed, so you can print the last field directly.

Upvotes: 2

QuiteClose
QuiteClose

Reputation: 686

Your trying to evaluate the variable $NUMp rather than $NUM. Try this instead:

USER=`sed -n ${NUM}p /etc/userdomains.hristian`

Upvotes: 1

Related Questions