Difference between revisions of "$1"

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to navigation Jump to search
Line 30: Line 30:
 
In bash functions, $1 server as the first bash function parameter and so on.  
 
In bash functions, $1 server as the first bash function parameter and so on.  
 
===Example===
 
===Example===
 +
<syntaxhighlight lang="bash" >
 +
#!/bin/bash
 +
die(){
 +
local m="$1"  # the first arg
 +
local e=$2    # the second arg
 +
echo "$m"
 +
exit $e
 +
}
  
 +
# if not enough args displayed, display an error and die
 +
[ $# -eq 0 ] && die "Usage: $0 filename" 1
 +
 +
# Rest of script goes here
 +
echo "We can start working the script..."
 +
</syntaxhighlight>
 
Another example:
 
Another example:
 
+
<syntaxhighlight lang="bash" >
 
fingerprints() {
 
fingerprints() {
 
         local file="$1"
 
         local file="$1"
Line 39: Line 53:
 
         done < $file
 
         done < $file
 
}
 
}
 +
</syntaxhighlight>

Revision as of 07:59, 30 January 2020

$1 is the first command-line argument passed to the shell script. Also, know as Positional parameters. For example, $0, $1, $3, $4 and so on. If you run ./script.sh filename1 dir1, then:

  • $0 is the name of the script itself (script.sh)
  • $1 is the first argument (filename1)
  • $2 is the second argument (dir1)
  • $9 is the ninth argument
  • ${10} is the tenth argument and must be enclosed in brackets after $9.
  • ${11} is the eleventh argument.

$1 and positional parameters example

Create a shell script named demo-args.sh as follows:

#!/bin/bash
#!/usr/bin/env bash
script="$0"
first="$1"
second="$2"
tenth="${10}"
echo "The script name : $script"
echo "The first argument :  $first"
echo "The second argument : $second"
echo "The tenth and eleventh argument : $tenth and ${11}"

Run it:

chmod +x demo-args.sh
./demo-args.sh foo bar one two a b c d e f z f z h
Sample outputs from demo-args.sh script

$1 in bash functions

In bash functions, $1 server as the first bash function parameter and so on.

Example

#!/bin/bash
die(){
	local m="$1"  # the first arg 
	local e=$2    # the second arg
	echo "$m" 
	exit $e
}

# if not enough args displayed, display an error and die
[ $# -eq 0 ] && die "Usage: $0 filename" 1

# Rest of script goes here
echo "We can start working the script..."

Another example:

fingerprints() {
         local file="$1"
         while read l; do
                 [[ -n $l && ${l###} = $l ]] && ssh-keygen -l -f /dev/stdin <<<$l
         done < $file
}