简体   繁体   中英

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...

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

)

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

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

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 .

x= starting line

y= number of lines to execute

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM