0

I have been monitoring the performance of my Linux server with ioping (had some performance degradation last year). For this purpose I created a simple script:

echo $(date) | tee -a ../sb-output.log | tee -a ../iotest.txt
./ioping -c 10 . 2>&1 | tee -a ../sb-output.log | grep "requests completed in\|ioping" | grep -v "ioping statistics" | sed "s/^/IOPing I\/O\: /" | tee -a ../iotest.txt
./ioping -RD . 2>&1 | tee -a ../sb-output.log | grep "requests completed in\|ioping" | grep -v "ioping statistics" | sed "s/^/IOPing seek rate\: /" | tee -a ../iotest.txt
etc

The script calls ioping in the folder /home/bench/ioping-0.6. Then it saves the output in readable form in /home/bench/iotest.txt. It also adds the date so I can compare points in time.

Unfortunately I am no experienced programmer and this version of the script only works if you first enter the right directory (/home/bench/ioping-0.6).

I would like to call this script from anywhere. For example by calling

sh /home/bench/ioping.sh

Googling this and reading about path variables was a bit over my head. I kept up ending up with different version of

line 3: ./ioping: No such file or directory

Any thoughts on how to upgrade my scripts so that it works anywhere?

Magistar
  • 111
  • 9
  • Possible duplicate of [Getting the source directory of a Bash script from within](https://stackoverflow.com/questions/59895/getting-the-source-directory-of-a-bash-script-from-within) – dimo414 Sep 25 '17 at 00:48
  • Possible duplicate of [How do I run a program with a different working directory from current, from Linux shell?](https://stackoverflow.com/questions/786376/how-do-i-run-a-program-with-a-different-working-directory-from-current-from-lin) – tripleee Sep 25 '17 at 04:50
  • `echo $(date)` is a [useless use of `echo`](http://www.iki.fi/era/unix/award.html#echo) and I get the feeling the rest of your script could also be simplified significantly. – tripleee Sep 25 '17 at 08:03

2 Answers2

0

Isn't it obvious? ioping is not in . so you can't use ./ioping.

Easiest solution is to set PATH to include the directory where ioping is. perhaps more robust - figure out the path to $0 and use that path as the location for ioping (assing your script sits next to ioping).

If iopinf itself depend on being ruin in a certain directory, you might have to make your script cd to the ioping directory before running.

John3136
  • 28,809
  • 4
  • 51
  • 69
  • Or rather, put `ioping` somewhere that already is in (or is commonly added to) one's path, such as `/usr/local/bin` or `~/bin`. – chepner Sep 25 '17 at 00:59
0

The trick is the shell's $0 variable. This is set to the path of the script.

#!/bin/sh

set -x
cd $(dirname $0)
pwd

cd ${0%/*}
pwd

If dirname isn't available for some reason, like some limited busybox distributions, you can try using shell parameter expansion tricks like the second one in my example.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131