0

Why is the following expression giving me a expr: syntax error?

pingval=`expr ping6 -c 1 "$url"`

Basically I want to use the value returned by the above expression in another expression e.g.

var=$($pingval|tail -1 ....

Any suggestions?

user3352349
  • 177
  • 2
  • 4
  • 16

1 Answers1

0

Why are you using expr at all? It's generally used for simple maths / string functions.

You can assign the result (stdout) of that expression just using the backticks, or in a more modern way directly with:

pingval=$(ping6 -c1 "$url" | tail -1)

If you did want to build the shell expression before using, try something like:

cmd="ping6 -c 1 '$url' | tail -1"
echo cmd | sh 
declension
  • 4,110
  • 22
  • 25
  • Basically I want to use pingval in multiple expressions. Having used the above method I keep getting an error PING: Command not found? – user3352349 Nov 16 '14 at 16:20
  • Which of the two methods caused that? And what operating system is this on? – declension Nov 16 '14 at 16:23
  • using a vi editor in unix. The error comes in the expression in which I try and use the value given pingval i.e. cmd=$($pingval| tail -1| awk '{print $4}') – user3352349 Nov 16 '14 at 16:27
  • This works for me: `var=$(ping6 -c 1 "$url" | tail -1 | awk '{print $4}')"`, giving something like `0.025/0.025/0.025/0.000` – declension Nov 16 '14 at 16:44
  • I appreciate that, the same method works for me. The only issue is that I want to use the value given by pingval multiple times without having to re-run the ping expression. – user3352349 Nov 16 '14 at 16:48
  • That's fine - using `$(...)` evaluates the expression once only. The value `$var` or `$pingval` is just a string after that – declension Nov 16 '14 at 16:51
  • So why do you think: `pingval=$(ping6 -c 1 "$url")` `var=$($pingval| tail -1| awk '{print $4}')` is giving me the error? – user3352349 Nov 16 '14 at 16:54
  • The clue's in the name there: `pingval` is a (string) _value_, but you're trying to _execute_ it in the second bit. Either call it `pingcmd` and *don't* execute with `$(...)` (i.e. second example in my answer), or use `echo` in your second statement: `var=$(echo $pingval | tail -1 | awk '{print $4}')` – declension Nov 16 '14 at 18:04
  • @user3352349 If the answer helped, please mark the question as complete (or upvote) or if not, explain why - thanks. – declension Nov 24 '14 at 22:28