paranoidhominid
paranoidhominid

Reputation: 43

Execute n lines of shell script

Is there a way to execute only a specified number of lines from a shell script? I will try copying them with head and putting them on a separate .sh, but I wonder if there's a shortcut...

Upvotes: 3

Views: 512

Answers (5)

Sam Haddox
Sam Haddox

Reputation: 1

x=starting line

y=number of lines to execute

eval "$(tail -n +$x script | head -$y)"

Upvotes: 0

ojblass
ojblass

Reputation: 21620

Write your own script /tmp/headexecute for example

#!/bin/ksh
trap 'rm -f /tmp/somefile' 0
head -n $2 $1 > /tmp/somefile
chmod 755 /tmp/somefile
/tmp/somefile

call it with the name of the files and the number of lines to execute

/tmp/headexecute /tmp/originalscript 10

Upvotes: 1

Henk Langeveld
Henk Langeveld

Reputation: 8446

Reorganize the shell script and create functions.

Seriously, put every line of code into a function.

Then (using ksh as an example), source the script with "." into an interactive shell.

You can now run any of the functions by name, and only the code within that function will run.

The following trivial example illustrates this. You can use this in two ways: 1) Link the script so you can call it by the name of one of the functions. 2) Source the script (with . script.sh) and you can then reuse the functions elsewhere.

function one {
     print one
}

function two {
     print two
}

(
    progname=${0##*/}
    case $progname in
    (one|two)
         $progname $@
    esac

)

Upvotes: 2

potong
potong

Reputation: 58420

This might work for you (GNU sed):

sed -n '1{h;d};H;2{x;s/.*/&/ep;q}' script

This executes the first two lines of a script.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

Most shells have no such facility. You will have to do it the hard way.

Upvotes: 0

Related Questions