Commands take arguments: grep -c ERROR till.log. Your scripts can take arguments too. Inside the script, they are numbered variables:
./count.sh$0ERROR$1~/logs/till.log$2
| Variable | Holds |
|---|---|
$0 | The script, as you ran it |
$1, $2, … $9 | The first, second, … ninth argument |
An example
~/count.sh:
bash
#!/bin/bash
# Usage: count.sh WORD FILE
echo "$1 lines in $2: $(grep -c "$1" "$2")"text
learner@tidepool:~$ ./count.sh ERROR ~/logs/till.log
ERROR lines in /home/learner/logs/till.log: 3
learner@tidepool:~$ ./count.sh WARN ~/logs/till.log
WARN lines in /home/learner/logs/till.log: 1The same script answers a new question when you give it new arguments.
The shell changes ~ before the script starts, so $2 holds the full path.
Put quotes around arguments
Write "$1", not $1. An argument can have spaces, as in "Use Variables in Commands".
Give them names
$1 does not say what it holds. Copy it into a named variable at the top:
bash
#!/bin/bash
# Usage: count.sh WORD FILE
word="$1"
file="$2"
echo "$word lines in $file: $(grep -c "$word" "$file")"The # Usage: comment tells the next reader which arguments to give, and in which order.