how to refactor simple script to be pipeable (take in input from stdout)

 To refactor a simple script to be pipeable, you can modify it to accept input from standard input (stdin) instead of taking input as command-line arguments. This allows you to use the script in a pipeline where the output of one command becomes the input of your script. Here's a basic example of how to do this:


Let's say you have a simple script named `myscript.sh` that accepts two numbers as command-line arguments and adds them:


```bash

#!/bin/bash

num1="$1"

num2="$2"

sum=$((num1 + num2))

echo "The sum is: $sum"

```


To make it pipeable, you can modify the script to read input from stdin and perform the addition. Here's a refactored version:


```bash

#!/bin/bash

while read -r num1 num2; do

    sum=$((num1 + num2))

    echo "The sum is: $sum"

done

```


With this refactored script, you can use it in a pipeline like this:


```bash

echo "5 7" | ./myscript.sh

```


You can also provide input from a file like this:


```bash

./myscript.sh < input.txt

```


Where `input.txt` contains lines of numbers to be added, for example:


```

3 4

8 2

```


This refactoring allows you to use the script in a more flexible and pipeable manner, as it reads input from stdin, making it suitable for use in pipelines and other automated workflows.

Comments

Popular posts from this blog

bad character U+002D '-' in my helm template

GitLab pipeline stopped working with invalid yaml error

How do I add a printer in OpenSUSE which is being shared by a CUPS print server?