0

I want to pass the argument in the console while running a script called run.sh as follows

run.sh first count

for example:

./run.sh first 10

i have to pass those first and 10 to the script here

cat file1.txt | head -10

here first should refer to head and count value should be 10. how can i do this?

2
  • 1
    Use cat file1.txt | head $1. $1 refers to the first parameter, $2to the second, etc. Commented May 7, 2013 at 13:53
  • I'm curious: you list first as an argument, but then don't seem to use it in the script. Did you mean to pass file1.txt as the argument — or to use first in place of file1.txt in the command? Also, beware of the impending UUOC Award. Commented May 7, 2013 at 14:41

1 Answer 1

2

Use Positional Parameters

Bash supports positional parameters. Parameters one through nine are stored in $1..$9, but you can have more stored in $* or $@.

For example:

#!/bin/bash

# Read x lines from some arbitrary file. 
head -n "$2" "$1"
Sign up to request clarification or add additional context in comments.

3 Comments

If you need more than $1 through $9 you can use shift, e.g., while $@ ; do # process options ; shift ; done
You can also use ${10} or so, @sigmavirus24.
True @fedorqui, I just happen to more often than not see shift used, so it seems idiomatic to me. I try to be helpful and suggest the idioms they'll see more often than not. But yes for any position > 9, ${position} will work just fine. And if he's keeping track of it in a separate variable then ${$position} should work.