Using input as a variable

This guide will show how to parse inputs inside variables in bash scripts.

Step 1

Create a file named vartest and edit it in your favourite text editor:

$ touch vartest
$ chmod +x vartest
$ vi vartest

 

Step 2 #

If the input variable is an argument:

#!/bin/bash
echo $1 $2 $3

 

Step 3 #

Now, if you run your script with 3 arguments, console will print them:

$ ./vartest apple car dog apple car dog

 

Step 4 #

Modify your script. Let it shows if running process exist:

#!/bin/bash
ps aux | grep "$@" | grep -v "grep"

 

Step 5 #

Run your script with “bash” argument. Console should print somwething similar to this:

$ ./vartest bash user 18783 0.1 0.1 22704 5208 pts/0 Ss 20:03 0:00 -bash

 

Step 6 #

Modify your script again. Let it wait for your input from console:

#!/bin/bash
echo "Hello, how should I call you?"
read yourname
echo "You've got very nice name, $yourname"

 

Step 7 #

Run your script without any arguments, and write your name:

$ ./vartest
Hello, how should I call you?
Joe
You've got very nice name, Joe