1

I am trying to write a bash script that essentially acts like the traceroute command, I have written the following code:

#! /bin/bash

ttl=1
dest_ip=$1

#Send packets with increasing ttl and stop when the ping is sucsessfull
until ["ping -t $ttl -c 1 $dest_ip" = "0"]; do
        echo "$ttl"
        (($ttl+=1))
done

I ran this and get the error enter image description here

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Keren
  • 23
  • 4
  • 1
    Your condition also has syntax errors. Should just be `if `. Your don't need `[` and whitespace is important to syntax. – jordanm Jun 27 '23 at 16:05
  • 1
    First step when debugging a shell script: Paste it into shellcheck.net. Second step, run it with `bash -x`. Last resort: Post to [so]. – Barmar Jun 27 '23 at 16:07
  • @jordanm `until` is correct (it's a negated form of `while`). But the square-brackets do need to be removed, see ["Bash conditional based on exit code of command"](https://stackoverflow.com/questions/49849957/bash-conditional-based-on-exit-code-of-command). – Gordon Davisson Jun 27 '23 at 16:16
  • 1
    Please always copy&paste error messages *as text* and format these in the same way as your code. [Edit] your question to fix this. – Bodo Jun 27 '23 at 16:26
  • Set integer flag: `declare -i ttl=1; ttl+=1; echo $ttl` – Cyrus Jun 27 '23 at 16:44
  • `ttl` has the value 1. Therefore, parameter expansion replaces $ttl by 1. Therefore, the command `(($ttl+=1))` expands to `((1+=1))`, which obviously does not make sense. You can find this kind of error easily by debugging the program with `set -x` and/or using [shellcheck](https://www.shellcheck.net/). – user1934428 Jun 28 '23 at 06:39

2 Answers2

1

Addressing the make a variable larger by 1 issue ...

The error message shows that (($tt1+=1) is being processed as ((1+=1)) (ie, the $tt1 is replaced by the value in tt1) which is generating the error message (attempted assignment to non-variable, ie, 1 is not a variable).

You want to reference the variable by name and not by value so: ((tt1+=1)); alternatives: ((tt1++)) and ((tt1=tt1+1))

markp-fuso
  • 28,790
  • 4
  • 16
  • 36
1
while !(ping -q -t $ttl -c 1 $dest_ip > output); do
    echo "$ttl"
    ttl=$((ttl+1))

done

Keren
  • 23
  • 4
  • 1
    The `()` just tells the shell to run the command in a subshell and is not necessary for this example. – jordanm Jun 27 '23 at 19:34