user5475322
user5475322

Reputation:

Running bash script partially

I have bash script 1.sh:

echo 1
echo 2
echo 3
echo 4

What is the better way to execute only several commands, so in result I would get output:

1
2

or only:

3
4

Upvotes: 0

Views: 395

Answers (1)

terence hill
terence hill

Reputation: 3454

EDIT: if you have a script in which each line is just a simple command like the one you are showing 1.sh, then you can execute only the line you choose by using awk and xargs

For example if you want to select only the line where is the 1 and execute it:

awk '/1/ {print $0}' 1.sh | sh

Or if you want to run the 3 record you can use:

awk '{if(NR == 3) print $0}' 1.sh | sh

On the other end you if can modify 1.sh then I would use an input parameter to choose which lines to execute, like in the following example:

#!/bin/bash

torun=$1

if [ "$torun" -eq 1 ] 
    then
        echo "run command 1"
        echo "run command 1b"
fi

if [ "$torun" -eq 2 ] 
    then
        echo "run command 2"
        echo "run command 2b"
fi

Upvotes: 1

Related Questions