0

Hello im writing a bash code which has some positional parameters but whats the best approach to add an optional seconds parameter which will allow some function to run for x seconds? This is what code looks like:

doaction()
{
(run a process)
}

while [ $# -gt -0 ]; do
  case "$1" in
  --action|-a)
     doaction ;;
  --seconds|-s)
     ???????? $2
     shift ;;
  esac
shift
done

After x seconds kill process. Also what happens when i run the script like ./script -s 10 -a instead of ./script -a -s 10

Thanks

2 Answers2

0

It looks like the timeout command is probably useful here. However, this only works on a script separate from the one that is currently running (as far as I can tell).

For your second question, the way you currently have things written, if you use ./script -a -s 10 then the result would be that the action would run before the delay is set. You can fix this by using a flag to indicate that the action should be executed, and you can ensure that the timeout is set (if at all) before the execution.

Here is my suggestion for a possible solution:

while [ $# -gt -0 ]; do
    case "$1" in
    --action|-a)
        action=true;;
    --seconds|-s)
        time="$2"
        shift;;
    esac;
    shift
done

if $action; then
    timeout $time /path/to/action.sh
else
    # do something else
fi

Where /path/to/action.sh is the location of the script that you want to run for a specific amount of time. You can test that the script exits after the specified number of seconds by replacing the script with the bash command top or something else which runs indefinitely.

heuristicus
  • 1,130
  • 12
  • 31
0

You can use "getopts" to solve your problem. You might find the information on this link to be useful for your scenario.

Community
  • 1
  • 1
Sarfraaz Ahmed
  • 577
  • 5
  • 12