Command Line Arguments

You can pass arguments to your shell script when you execute it. To pass an argument, you just need to write it right after the name of your script.

Another thing that you need to keep in mind is that $0 is used to reference the script itself.

  • $? ---- Exit status of last run command, 0 means success and non-zero indicates failure.

  • $0 ---- File name of our script

  • $1..$n ---- Script arguements

  • $# ----- number of args that our script was run with

  • $? ---- Exit status of last run command, 0 means success and anything else indicates failure.

#!/bin/bash

# Print value
echo "Argument one is $1" 
echo "Argument two is $2" 
echo "Argument three is $3"

# $1 is first argument
# $2 is second argument
# $3 is third argument

Run Script like this

./hello.sh dog cat bird

User Input

To read the Bash user input, we use the built-in Bash command called read. It takes input from the user and assigns it to the variable.

read name
#!/bin/bash

# User input
read name
read -p “name” name >> same line input
read -sp “pass” passwd>> invisible input
# Print value
echo “$name”

Sample Script

#!/bin/bash
echo "Enter your Name:"
read Name
echo "Enter username and password"
read -p 'username: ' username
read -sp 'password: ' psw

Comment

Comments are used to leave yourself notes through your code. To do that in Bash, you need to add the # symbol at the beginning of the line.

# Test commands

Bash also contains multiline Comments.

<<comment
 "Code" or "Comments"
comment

Last updated